2016-12-05 69 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() 
相关问题