2012-10-21 107 views
1

也許我的編碼不太好,有些行不會很有意義或不必要,但代碼目的是簡單的:ValueError:對於int()以10爲底的無效字面值:str

我想創建一個函數,使用輸入(字符串),並將其轉換爲整數,這將在數學問題中使用。 加:我想我的代碼來解釋一個隨機生成的數字,並打印爲對應的字符串:

### 'one' --> 1 
### 'zero' --> 0 

import random 

##'one' == 1 
##'zero' == 0 

def name_to_number(name): 
    if name == 'one': 
     return 1 

def number_to_name(comp_number): 
    if comp_number == 1: 
     return 'one' 

def lit_for_num(name): 
    '''(str) -> str''' 

    comp_number = random.randrange(0,1) 
    equation = (abs(comp_number - int(name))) 
    if equation == 0: 
     print('Hallo!') 
     return 'Computer draws' + comp_number 
    else: 
     return 'Computer draws 0' 

任何幫助是非常感謝。

+0

'name'沒有在'lit_for_num'中定義,但是你可以在'int(name)'中使用它。你的意思是'int(guess)'而不是? – nneonneo

+0

是啊,你是對的...我只是修復了它 –

+0

...它仍然崩潰? – nneonneo

回答

2

第一個問題是,你似乎可以用one作爲輸入,因此 int('one')會給你的錯誤。

其次,在:

comp_number = random.randrange(0,1) 
... 
if equation == 0: 
    print('Hallo!') 
    return 'Computer draws' + comp_number 
else: 
    return 'Computer draws 0' 

else子句將始終被調用,因爲comp_number始終爲0

rand.randrange類似於choice(range(start, stop, step)),這意味着randrange(0,1)始終返回0您想randrange(0,2)相反,如果你想要01。或者,使用random.randint(0,1)代替,其中包括端點01

作爲一個獎勵,處理文本編號爲數字,你可能要考慮由Greg Hewgilltext2num

+0

感謝您的回覆,對於不瞭解這類功能的細節我感到有點無聊。 –

+0

@ GaryJ.EspitiaS。不用謝!當我也在學習時,它確實咬了我 - 這就是我知道的:) –

0

下面的代碼對我來說工作得很好。我所要做的只是改變return 'Computer draws'+comp_numberreturn 'Computer draws'+str(comp_number)以及random.randrange(0,1)random.randrange(0,2)

### 'one' --> 1 
### 'zero' --> 0 

import random 

##'one' == 1 
##'zero' == 0 

def name_to_number(name): 
    if name == 'one': 
     return 1 

def number_to_name(comp_number): 
    if comp_number == 1: 
     return 'one' 

def lit_for_num(name): 
    '''(str) -> str''' 

    comp_number = random.randrange(0,1) 
    equation = (abs(comp_number - int(name))) 
    if equation == 0: 
     print('Hallo!') 
     return 'Computer draws' + str(comp_number) 
    else: 
     return 'Computer draws 0' 
相關問題