检测输入是int还是str•Python 2.7

时间:2017-05-28 15:51:28

标签: python-2.7

**编辑:***这已经解决了!*

我正在编程一个程序,告诉你你是否已经足够投票了。并且,当它询问您的年龄时,如果用户键入字母而不是数字,我希望它说出某些内容,例如"请输入数字,而不是字母。重新启动&#34。这是我现在的代码:

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+".")

2 个答案:

答案 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

答案 1 :(得分:-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+".")