繁体   English   中英

设置“if”以确保变量是数字而不是字母/符号

[英]setting “if” to make sure variable is a number and not a letter/symbol

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

谢谢你的帮助。

假设您正在使用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(...)) ,这意味着你永远不知道从它返回什么 - 你甚至可以在input引发一个SyntaxError

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

作为旁注,我建议的程序使您的程序免受各种攻击。 考虑一下用户投入的日子有多糟糕:

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

提示时代替数字! 如果你eval ING,通过使用以前声明中input上python2.x,或使用eval明确,你只是有some/important/file删除。 哎呀。

尝试这个:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM