Home > Net >  How to change a variable in a loop in Python
How to change a variable in a loop in Python

Time:03-30

I'm new to Python and was trying to create a word guessing game and ran into a problem with changing a 'guesses remaining' variable. I want the variable 'guess remaining' to go down one every time it loops (15 times) but instead of returning 15 then 14 then 13 etc. it just keeps returning 15. I would love some help, thanks. Here is a summary of the code:

guesses_remaining = 15
for i in range(15):
    (Code)
    guesses_remaining - 1
    print("You have", guesses_remaining, "guesses remaning")

CodePudding user response:

there are two problems here. As one person noted in the comments, you mention guesses in the for loop, but your variable is named guesses_remaining.

The other issue is you're subtracting one from the value of the variable, but you have to also assign the value back to the variable in order for the variable's value to change.

There are two ways to do this:

guesses_remaining = 15
for i in range(15):
    guesses_remaining = guesses_remaining - 1
    print("You have", guesses_remaining, "guesses remaning")
guesses_remaining = 15
for i in range(15):
    guesses_remaining -= 1
    print("You have", guesses_remaining, "guesses remaning")

-= is like a shorthand for 'decrement and reassign'. There are also other things like this, such as =.

CodePudding user response:

 guesses_remaining = 15
 for i in range(15):
    #(Code)
    guesses_remaining -= 1
    print("You have", guesses_remaining, "guesses remaning") 

CodePudding user response:

You need to use equals sign to change variable. Here's an example:

guesses_remaining = 15
for i in range(15):
    guesses_remaining = guesses_remaining - 1
    print("You have", guesses_remaining,"guesses remaining")

If you wish you can write subtraction line using augmented assignment

guesses_remaining -= 1

CodePudding user response:

the problem with your code is that you did not correctly format it. It should look like:

guesses_remaining = 15
for i in range(15):
    (Code)
    guesses_remaining -= 1
    print("You have", guesses_remaining, "guesses remaning")

or

guesses_remaining = 15
for i in range(15):
    (Code)
    guesses_remaining = guesses_remaining - 1
    print("You have", guesses_remaining, "guesses remaning")

In order to change a variable, you need to mention the variable, and then set it equal to the new value. In this case, it would be the old value minus one. Hope this helps!

  • Related