2015-05-14 210 views
1

我有這段代碼。如果你運行它,一切工作正常,如果你按照說明。然而,我想勉強它,但是當你輸入太多的軍隊,然後你修復你的錯誤,你會在函數重新啓動時修正錯誤後得到一個錯誤。代碼故障?

請看看並幫我修復它。

import time 
warriors = 100 
def deploy(): #Calls fighters to front lines 
    amount = input('How many warriors would you like to send to the front lines? Your limit is %i warriors. Keep in mind that enemy invaders have been spotted inside your base. You must keep 10 warriors in base at all times. ' %(warriors)) 
    try: 
     amount = int(amount) 
    except ValueError: 
     print('Please use numbers.') 
     time.sleep(1.5) 
     deploy() 
    if amount <= warriors: 
     print (type(amount)) 
    elif amount > warriors: 
     print("You can't send that many warriors. You only have %i warriors." %(warriors)) 
     time.sleep(1.5) 
     amount=0 
     deploy() 
    else: 
     print("You did something wrong. Try again.") 
     time.sleep(1.5) 
     deploy() 
fighters = deploy() 
warriors = warriors - fighters 

回答

1

你不應該使用遞歸(例如一個函數自己重複調用)來嘗試和驗證。對於一些良好模式的一般例子,canonical question是一個好的開始。在你的情況下,我可能會稍微重構。

import time 

warriors = 100 


def deploy(): 
    while True: 
     amount = input("...") # your text here 
     try: 
      amount = int(amount) 
     except ValueError: 
      print("Please use numbers.") 
      # move the time.sleep to the end 
     else: # only execute if the try block succeeds 
      if amount > warriors: 
       print("You can't send that many warriors. " 
         "You only have %i warriors." % warriors) 
      else: 
       # everything went right! 
       print(type(amount)) # why are you doing this...? 
       return amount # did you forget this in your sample code? 
     # if you get here: something broke 
     time.sleep(1.5) 

也就是說,這是一種醜陋的,因爲它是如此之深嵌套。記住禪:「扁平比嵌套好。」讓我們重構一下,爲我們做一個新的函數來驗證。

import time 

warriors = 100 


def int_less_than(prompt, ceil, type_error_msg=None, 
        value_error_msg=None, callback=None): 
    """Returns a validated integer 

    input(prompt) must be less than ceil. Print to console a std error msg 
    if none is specified. If you specify a callback: run the callback if any 
    errors are detected. 
    """ 

    while True: 
     user_in = input(prompt) 
     try: 
      user_in = int(user_in) 
     except ValueError: 
      print(type_error_msg or "You must enter a number") 
     else: 
      if user_in > ceil: 
       print(value_error_msg or "You must enter a number " 
             "less than {}".format(ceil)) 
      else: 
       return user_in 
     if callback is not None: 
      callback() # lets us insert a time.sleep call 

def deploy(): 
    amount = int_less_than("How many warriors would you like to...", 
          warriors, 
          callback=lambda: time.sleep(1.5)) 
    return amount