设置“如果”来确保变量是数字而不是字母/符号

2024-04-16 17:02:31 发布

您现在位置:Python中文网/ 问答频道 /正文

如何创建“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    

谢谢你的帮助。在


Tags: oftheinputifhereis字母数字
2条回答

假设您使用的是python2.x:我认为更好的方法是将输入作为raw_input。那么你就知道这是一个字符串:

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

python3.x相当于上述语句:

^{pr2}$

现在,从中构造一个float(或尝试):

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

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

你要知道这是什么意思!在

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

作为补充说明,我建议的程序可以使您的程序免受各种攻击。想想如果一个用户输入以下内容,一天会有多糟糕:

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

而不是一个数字提示!如果您在python2.x上使用input,或者显式地使用eval来执行前面的语句,那么您已经删除了some/important/file。哎呀。在

试试这个:

if isinstance(radius, (int, float)):
    #do stuff
else:
    raise TypeError  #or whatever you wanna do

相关问题 更多 >