Python while / try / if循环

时间:2013-03-27 23:19:18

标签: python

我只是在学习python,并且想知道是否有更好的方法来编写代码,而不是使用try / except和if / else嵌入while循环。这是从学习编码的艰难方式,我试图给用户3个机会输入一个数字,在第三次机会它使用死函数退出。 (评论是为了我自己)

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)

2 个答案:

答案 0 :(得分: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

这是您提供的精简版本,缺少大部分风味文本,但希望它可以为您提供更多洞察其他封装方法,而不是硬编码您的价值观。

答案 1 :(得分:-1)

而不是将try包含在while循环中,我可能会在except内移动while循环,以使您的代码更有条理,更易于阅读,Python的前提。这是一个可以复制和运行的工作示例:

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()