我正在制作一个程序,每当他们输入“1”加速,“2”减速或“3”退出时,汽车将加速5或减速5。
我的问题是,我现在设置它的方式是它不记得它经过循环一次后的速度。
这就是我现在所拥有的:
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()
如何让它记住速度?
答案 0 :(得分:2)
请勿再次致电main()
。保持一个while循环,检查输入的值是否为3以退出:
question = 0
while question != 3:
# do checks for non-exit values (1 and 2) here
question = int(input("Enter ..."))
答案 1 :(得分:0)
当你再次调用main时,你有一个新的命名空间,并在其中声明新的变量。您的价值会被保存,只是不在您认为的位置。
或者,不要再次调用您的功能
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)
答案 2 :(得分: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。因此,main的环境是一个全新的var环境,其速度设置为0,如代码的第二行所示。
对于您的特定问题,我认为递归是必要的。但是,如果您想使用它,则必须将速度作为参数传递。