0

我只是在学习 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)
4

2 回答 2

1

这是使用递归的另一种方法:

def dead(why):
    print why, "Good bye!"
    exit(0)

def typenumber(attempts):
    if attempts:
        answer = raw_input('> ')
        try:
            int(answer)
        except ValueError:
            print "Better type a number..."
            return typenumber(attempts -1)
        else:
            return True

if typenumber(3):
    print 'you got it right'
else:
    dead("Man, learn to type a number.")


> a
Better type a number...
> b
Better type a number...
> 3
you got it right

它是您提供的内容的精简版本,缺少大部分风味文本,但希望它可以为您提供更多关于封装而不是硬编码您的值的方法的见解。

于 2013-03-27T23:32:16.837 回答
-1

在 Python 的前提下,我可能会将 while 循环移入其中,以使您的代码更有条理且更易于阅读,而不是将您的代码封装try在一个循环中。这是一个可以复制和运行的工作示例:whileexcept

def gold_room():
    print "this room is full of gold. How much do you take?"
    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
            while True:
                chance = 0 #how many chances they have to type a number
                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)

gold_room()
于 2013-03-27T23:38:34.363 回答