Flu*_*tor 2 python if-statement
如何创建"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
Run Code Online (Sandbox Code Playgroud)
谢谢你的帮助.
假设您正在使用python2.x:我认为更好的方法是将输入作为raw_input
.然后你知道它是一个字符串:
r = raw_input("enter radius:") #raw_input always returns a string
Run Code Online (Sandbox Code Playgroud)
上面语句的python3.x等效于:
r = input("enter radius:") #input on python3.x always returns a string
Run Code Online (Sandbox Code Playgroud)
现在,从那里构建一个浮点(或尝试):
try:
radius = float(r)
except ValueError:
print "bad input"
Run Code Online (Sandbox Code Playgroud)
关于python版本兼容性的一些进一步说明
在python2.x中,input(...)
相当于eval(raw_input(...))
意味着你永远不知道你将从中返回什么 - 你甚至可以在SyntaxError
里面获得一个内容input
!
关于 在python2.x上使用的警告input
作为旁注,我建议的程序使您的程序免受各种攻击.考虑一下用户投入的日子有多糟糕:
__import__('os').remove('some/important/file')
Run Code Online (Sandbox Code Playgroud)
提示时代替数字!如果您eval
通过使用input
python2.x或eval
明确使用您之前的语句,那么您刚刚some/important/file
删除了.哎呀.
归档时间: |
|
查看次数: |
368 次 |
最近记录: |