Xenic
Xenic

Reputation: 1

How to add to a variable outside of the loop so that it remembers

I am making a program where a car will accelerate by 5 or decelerate by 5 every time they input a "1" for accelerate, a "2" for decelerate, or a "3" to exit.

My problem is that the way that I have it setup at the moment is that it doesn't remember the speed after it goes through the loop once.

This is what I have at the moment:

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()

How do I make it remember the speed?

Upvotes: 0

Views: 142

Answers (4)

Chiheb Nexus
Chiheb Nexus

Reputation: 9257

You can create a function in which you do your calculations then return the final speed.

Beware, your code may break if the user enter non integer value. This is why in my example i'm using a try...except to catch the error without breaking the processing.

Also, beware that with this actual algorithm, the final speed can have a negative value, which is incorrect. You should add a test for this case to handle this issue.

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()  

Upvotes: 0

Salvador Medina
Salvador Medina

Reputation: 6601

Why use recursion? You just need a while cycle, right?

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()

As they mentioned in the comments, what happens is that you are calling main in each case. Therefore the environment of main is a totally new var environment where speed was set to 0 as in the second line of your code.

For your particular problem I think recursion is note necessary. However, if you would like to use it, then you must pass speed as a parameter.

Upvotes: 0

yelsayed
yelsayed

Reputation: 5532

Don't call main() again. Keep one while loop that checks that the entered value is not 3 for exiting:

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

Upvotes: 2

OneCricketeer
OneCricketeer

Reputation: 191728

When you call main again, you have a new namespace, and are declaring new variables within that. Your values are saved, just just not where you think they are.

Alternatively, don't call your function again

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)

Upvotes: 0

Related Questions