我只是在学习 python,想知道是否有更好的方法来编写这个代码,而不是使用嵌入在 while 循环中的 try/except 和 if/else。这是从学习编码困难的方式开始,我试图给用户 3 次输入数字的机会,而在第 3 次机会中,它使用 dead 函数退出。(评论是为了我自己)
def gold_room():
print "this room is full of gold. How much do you take?"
chance = 0 #how many chances they have to type a number
while True: #keep running
next = raw_input("> ")
try:
how_much = int(next) #try to convert input to number
break #if works break out of loop and skip to **
except: #if doesn't work then
if chance < 2: #if first, or second time let them try again
chance += 1
print "Better type a number..."
else: #otherwise quit
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 dead(why):
print why, "Good bye!"
exit(0)