2015-11-06 60 views
1

發現錯誤試圖運行我的代碼時,我不斷收到一個錯誤:不能在Python代碼

Traceback (most recent call last): 
    File "E:\healthtest.py", line 3, in <module> 
    if raw_input() == "Hit": 
NameError: name 'raw_input' is not defined 

我不知道我做錯了什麼,但這裏是我一直在使用的代碼。

health = "10" 

    if raw_input() == "Hit": 
    health = health - 5 

我希望你能幫助我,並提前致謝。

+0

[**'raw_input' **](HTTPS://docs.python .org/2/library/functions.html#raw_input)是Python 2.7。 –

+4

可能的重複[如何在Python 3.1中使用raw \ _input](http://stackoverflow.com/questions/954834/how-do-i-use-raw-input-in-python-3-1) –

回答

3

這是raw_input(),而不是raw_input

除非你使用Python 3.x中,它已更名爲輸入()

此外,關於健康,你首先分配一個字符串值,然後試圖帶走-5,就好像它是一個int()。

+0

我修正了這一點。我剛上傳了一箇舊版本的代碼。讓我編輯它。 – Andrew

+0

您使用的是什麼版本的Python? –

+0

@Andrew你沒有修復它! Python 3.x中沒有'raw_input' – Psytho

0

確保您使用input()和縮進正確

health = 10 # health is an integer not a string 

if input()=='hit': 
    health -= 5 # pay attention to the indentation 


hit # my input 

health 
Out[34]: 5 # output of health after input 

您可以藉此進一步我分配input()到VAR做更多的驗證。

inp = input() 

if inp.lower()=='hit': 
    # continue code 

.lower()允許輸入諸如 '擊中', '命中', 'HIT' ...

'Hit' == 'hit' 
Out[35]: False 

'Hit'.lower() == 'hit' 
Out[36]: True 
+0

感謝:D這也非常有幫助! – Andrew