2016-12-05 73 views
0

我正在製作一個程序,其中每次輸入「1」加速時汽車會加速5或減速5,減速時輸入「2」 ,或者「3」退出。如何添加到循環以外的變量,以便記錄

我的問題是,我現在設置它的方式是,它不記得一次它通過循環後的速度。

這是我的時刻:

def main(): 
    speed = 0 
    question = int(input("Enter 1 for accelerate, 2 for decelerate, or 3 to exit:")) 
    while question == 1: 
     speed = speed + 5 
     print("Car speed:", speed) 
     main() 
    while question == 2: 
     speed = speed - 5 
     print("Car speed:", speed) 
     main() 
    if question == 3: 
     print("done") 

main() 

我怎麼讓它記住的速度?

+2

如何將速度作爲參數傳遞給'main'的遞歸定義並返回值? – karthikr

+1

你明白遞歸是什麼嗎?如果沒有,那就不要使用它。換句話說,重新啓動一個函數比重新調用它更好,重新設置你的值爲0 –

+0

你每次調用'main'都重置'speed'。在函數外部指定'速度',並將其作爲參數輸入。正如@KarthikRavindra所說,將它作爲'main'中的參數傳遞。 – Jakub

回答

2

不要再撥main()。保持一個while循環,檢查所輸入的值不是3退出:

question = 0 
while question != 3: 
    # do checks for non-exit values (1 and 2) here 
    question = int(input("Enter ...")) 
+0

這需要在循環之前聲明'question' –

+0

他確實在循環之前聲明瞭它。如果需要,我會延長答案。 – yelsayed

+0

那麼,'while'應該是'if'在問題 –

0

當您再次調用主,你有一個新的命名空間,並聲明範圍內的新變量。你的價值觀被保存下來,只是不在你認爲的地方。

另外,不要再打電話給你的功能

def main(): 
    speed = 0 
    while True: 
     question = int(input("Enter 1 for accelerate, 2 for decelerate, or 3 to exit:")) 
     if question == 1: 
      speed = speed + 5 
     elif question == 2: 
      speed = speed - 5 
     elif question == 3: 
      print("done") 
      break 
     print("Car speed:", speed) 
0

爲什麼使用遞歸?你只需要一段時間,對吧?

def main(): 
    speed = 0 
    question = 0 
    while question != 3: 
     question = int(input("Enter 1 for accelerate, 2 for decelerate, or 3 to exit:")) 
     if question == 1: 
      speed = speed + 5 
      print("Car speed:", speed) 
     if question == 2: 
      speed = speed - 5 
      print("Car speed:", speed) 
     if question == 3: 
      print("done") 
    print("Final speed is", speed) 

main() 

當他們在評論中提到的,什麼情況是,你在呼喚在每種情況下爲主。因此,main的環境是一個全新的var環境,速度設置爲0,就像代碼的第二行一樣。

對於您的特定問題,我認爲遞歸是必要的。但是,如果您想使用它,則必須將速度作爲參數傳遞。

+1

我假設你並不是要在條件中調用'main()' - 這是沒有必要的,並且反駁你的評論。 – AChampion

+0

沒錯! Thx的頭! –

0

您可以創建一個函數,在該函數中進行計算,然後返回最終速度。

請注意,如果用戶輸入非integer值,您的代碼可能會中斷。這就是爲什麼在我的例子中,我使用try...except來捕獲錯誤而不中斷處理。

此外,請注意,使用此實際算法,最終速度可能會有負值,這是不正確的。你應該爲這個案例添加一個測試來處理這個問題。

def get_speed(speed = 0): 
    while 1: 
     try: 
      # Here your program may crash and can give an error of type ValueError 
      # This is why i'm using try ... except to catch the exception 
      question = int(input("Enter 1 for accelerate, 2 for decelerate, or 3 to exit: ")) 
      if question == 1: 
       speed += 5 
      elif question == 2: 
       speed -= 5 
      elif question == 3: 
       print("done") 
       print("Car speed: ", speed) 
       return speed # Return and save your speed 
       break 
     except ValueError: 
      pass 
# You can initialize your begenning speed 
# or use the default speed which is equal to 0 
# NB: output_speed will store the returned speed 
# if you need it for further calculations 
output_speed = get_speed() 
相關問題