我有可能是最愚蠢的问题......
如何判断raw_input是否从未输入任何内容?(空值)
final = raw_input("We will only cube numbers that are divisible by 3?")
if len(final)==0:
print "You need to type something in..."
else:
def cube(n):
return n**3
def by_three(n):
if n%3==0:
return cube(n)
else:
return "Sorry Bro. Please enter a number divisible by 3"
print by_three(int(final))
Run Code Online (Sandbox Code Playgroud)
特别是2号线...如果最终没有输入,我将如何测试?对于输入的任何内容,代码都可以正常工作,但如果没有提供输入则会中断....
我确信这很简单,但任何帮助都表示赞赏.
没有条目导致空字符串; 空字符串(如空容器和数字零)测试为布尔值false; 只需测试not final:
if not final:
print "You need to type something in..."
Run Code Online (Sandbox Code Playgroud)
您可能希望删除所有空格的字符串,以避免在仅输入空格或制表符时断开:
if not final.strip():
print "You need to type something in..."
Run Code Online (Sandbox Code Playgroud)
但是,您仍需要验证用户是否输入了有效的整数.您可以捕获ValueError异常:
final = raw_input("We will only cube numbers that are divisible by 3?")
try:
final = int(final)
except ValueError:
print "You need to type in a valid integer number!"
else:
# code to execute when `final` was correctly interpreted as an integer.
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8332 次 |
| 最近记录: |