私は Learn Python the Hard Way の演習 35 を行っています。以下は元のコードで、0 と 1 だけを含まない数字を受け入れるように変更するよう求められています。
def gold_room():
print "This room is full of gold. How much do you take?"
next = raw_input("> ")
if "0" in next or "1" in next:
how_much = int(next)
else:
dead("Man, learn to type a number.")
if how_much < 50:
print "Nice, you're not greedy, you win!"
exit(0)
else:
dead("You greedy bastard!")
これは私のソリューションであり、正常に動作し、浮動小数点値を認識します。
def gold_room():
print "This room is full of gold. What percent of it do you take?"
next = raw_input("> ")
try:
how_much = float(next)
except ValueError:
print "Man, learn to type a number."
gold_room()
if how_much <= 50:
print "Nice, you're not greedy, you win!"
exit(0)
else:
dead("You greedy bastard!")
同様の質問を検索すると、次のコードに示す別のソリューションを作成するのに役立ついくつかの回答が見つかりました。問題は、 isdigit() を使用すると、ユーザーが float 値を入力できないことです。したがって、ユーザーが 50.5% を受け取りたいと言った場合、数字の入力方法を学ぶように指示されます。それ以外の場合は整数に対して機能します。どうすればこれを回避できますか?
def gold_room():
print "This room is full of gold. What percent of it do you take?"
next = raw_input("> ")
while True:
if next.isdigit():
how_much = float(next)
if how_much <= 50:
print "Nice, you're not greedy, you win!"
exit(0)
else:
dead("You greedy bastard!")
else:
print "Man, learn to type a number."
gold_room()