6

我可能有一个最愚蠢的问题......

如何判断 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 行...如果最终没有输入,我将如何测试?该代码适用于输入的任何内容,但如果未提供任何条目则中断......

我敢肯定这非常简单,但感谢您提供任何帮助。

4

1 回答 1

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.
于 2013-08-30T22:05:08.327 回答