2017-05-28 44 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' ^^ –

相关问题