2017-05-28 78 views
0

**編輯:***已解決!*檢測輸入是int還是str•Python 2.7

編程一個程序,它會告訴你,如果你足夠大,可以投票。而且,當它詢問你的年齡時,如果用戶輸入的是字母而不是數字,我希望它能說某件事,例如「請輸入數字,而不是字母,重新啓動」。這裏是我現在所擁有的代碼:

name = raw_input("What is your name?: ") 
print("") 
print("Hello, "+name+".\n") 
print("Today we will tell you if you are old enough to vote.") 
age = input("How old are you?: ") 
if age >= 18: 
    print("You are old enough to vote, "+name+".") 
elif age < 18: 
    print("Sorry, but you are not old enough to vote, "+name+".") 
+0

我建議你使用字符串格式化,即「用'.'' '你好,%S替換所有這些' '喂,' +名字+'。 %name'。這裏有一個很好的字符串格式化教程:https://pyformat.info/ –

回答

-1

你可以嘗試這樣的事情:

name = raw_input("What is your name?: ") 
print("") 
print("Hello, "+name+".\n") 
print("Today we will tell you if you are old enough to vote.") 
while True: 
    try: 
     #get the input to be an integer. 
     age = int(raw_input("How old are you?: ")) 
     #if it is you break out of the while 
     break 
    except ValueError: 
     print("Please enter a number, not a letter. Restart.") 
if age >= 18: 
    print("You are old enough to vote, "+name+".") 
elif age < 18: 
    print("Sorry, but you are not old enough to vote, "+name+".") 
+0

我想這一點,但我得到了一個錯誤:回溯(最近通話最後一個):文件「vote.py」,8號線,在年齡= INT(輸入(「你多大了?:」))文件「」,第1行,在 NameError:名稱'Dhbe'未定義 – MrSprinkleToes

+0

將'input'更改爲'raw_input' –

+0

現在檢查編輯 –

0
name = raw_input("What is your name?: ") 
print("") 
print("Hello, "+name+".\n") 
print("Today we will tell you if you are old enough to vote.") 
while True: 
    age = raw_input("How old are you?: ") 
    try: 
     age = int(age) 
    except ValueError: 
     print("Please enter a number, not a letter. Restart.") 
    else: 
     break 
if age >= 18: 
    print("You are old enough to vote, "+name+".") 
elif age < 18: # else: 
    print("Sorry, but you are not old enough to vote, "+name+".") 

try-except-else,我們儘量年齡將從字符串爲整數。如果發生ValueError,則意味着輸入字符串不是合法的整數。如果沒有,那麼我們可以跳出while循環並執行以下任務。

注意1:最好不要在python2中使用input()。請參閱this

注2:elif是沒用的。只需使用else即可。

+0

我無法弄清楚如何適應代碼。 D: – MrSprinkleToes

+0

編輯:完成示例並添加一些解釋。 – frankyjuang

+0

你大概意思'嘗試 - 除了-else',而不是'的try-catch-else' ^^ –

相關問題