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 に答える