Python - 测试Raw-Input是否没有条目

时间:2013-08-30 22:03:53

标签: python

我有可能是最愚蠢的问题......

如何判断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))

特别是第2行......如果最终没有输入,我将如何测试?该代码适用于输入的任何内容,但如果没有提供输入则会中断....

我确信这很简单,但感谢任何帮助。

1 个答案:

答案 0 :(得分:6)

没有条目导致空字符串;空字符串(如空容器和数字零)测试为布尔值false;只需测试not final

if not final:
    print "You need to type something in..."

您可能想要删除所有空格的字符串,以避免在只输入空格或制表符时中断:

if not final.strip():
    print "You need to type something in..."

但是,您仍需要验证用户是否输入了有效的整数。您可以捕获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.