2

如何创建“if”语句以确保输入变量是数字而不是字母?

radius = input ('What is the radius of the circle? ') 

#need if statement here following the input above in case user
#presses a wrong key    

谢谢你的帮助。

4

2 回答 2

6

假设您使用的是 python2.x:我认为更好的方法是将输入作为raw_input. 然后你知道它是一个字符串:

r = raw_input("enter radius:")  #raw_input always returns a string

上述语句的 python3.x 等效项是:

r = input("enter radius:")      #input on python3.x always returns a string

现在,从中构造一个浮点数(或尝试):

try:
    radius = float(r)
except ValueError:
    print "bad input"

关于 python 版本兼容性的一些进一步说明

在 python2.x 中,input(...)相当于eval(raw_input(...))这意味着你永远不知道你会从中得到什么——你甚至可以在SyntaxError里面得到一个提升input

关于在 python2.x 上使用的警告input

作为旁注,我提出的程序使您的程序免受各种攻击。考虑一下如果用户输入以下内容将是多么糟糕的一天:

__import__('os').remove('some/important/file')

提示时而不是数字!如果您eval通过input在 python2.x 上使用或eval显式使用之前的语句,则您刚刚some/important/file删除了该语句。哎呀。

于 2013-01-04T01:17:01.040 回答
3

尝试这个:

if isinstance(radius, (int, float)):
    #do stuff
else:
    raise TypeError  #or whatever you wanna do
于 2013-01-04T01:14:17.700 回答