2013-03-27 143 views
0

我剛剛學習python,想知道是否有更好的方法來編寫代碼,而不是在while循環中使用try/except和if/else。這是從學習編碼困難的方式,我試圖給用戶3次機會輸入一個數字,在第三次使用死亡函數退出的機會。 (該評論是爲了我自己)Python while/try/if循環

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) 
+0

假設代碼有效,對於http://codereview.stackexchange.com,這是一個更好的問題。 – 2013-03-27 23:21:41

+0

在程序中使用exit()是不好的做法。例如,這意味着如果不關閉較大的程序,就不能將代碼嵌入到較大的程序中。而不是退出,從你的方法返回。 – Patashu 2013-03-27 23:42:49

回答

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

相反的包裹你的trywhile循環,我可能會移動的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() 
+0

這不起作用。如果你沒有輸入數字,你會陷入一個無限循環的「更好地輸入數字......」。 – Tim 2013-03-28 00:18:53