Bra*_*wan -2 python python-2.7
我下面有一些代码,choice只接受整数输入,但如果输入不是整数,则输出一些特殊的代码.但是,下面的代码来处理这个问题似乎有点冗长.无论如何要解决它?
from sys import exit
def gold_room():
print "This room is full of gold. How much do you take?"
choice = raw_input("> ")
if "0" in choice or "1" in choice or "2" in choice or "3" in choice or "4" in choice or "5" in choice or "6" in choice or "7" in choice or "8" in choice or "9" in choice:
how_much = int(choice)
else:
dead("Man, learn to type a number.")
if how_much < 50:
print "Nice, you're not greedy, you win!"
exit(1)
else:
dead("You're greedy!")
def dead(why):
print why, "Good job!"
exit(0)
gold_room()
Run Code Online (Sandbox Code Playgroud)
尝试类似的东西:
try:
how_much = int(choice)
except ValueError:
dead('Man, learn to type a number.')
Run Code Online (Sandbox Code Playgroud)
并且查找更容易请求宽恕而不是理由的许可.