Python Forum

Full Version: increment variable in while loop
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
hello, i have a question please, why the while loop dosen't store the updated integer?
Output:
guess the number: 4 better luck next time the random number is : 8 round 2 ! guess the number: 5 better luck next time the random number is : 8 round 2 ! # supposed to be round 3 guess the number:
as you can see it looped in the second round but it didn't store the new variable in round 3 so it stayed round 2

def normalgame():
    print(" see if you  are lucky or not")
    print(" system will generated a random number between 0 and 10 try to guess the generated number")
    print(" if you want to quit type 911")
    while True:
        Dice = random.randint(0, 10)
        playernumchoise = int(input("guess the number: "))
        round = 1
        round += 1
        if playernumchoise == 911:
            print("Thank you for playing :)")
            break
        if playernumchoise > 10:
            print('please enter a number between 0 and 10')
        elif playernumchoise == Dice:
            print("you are so lucky")
            print("the random number is :", Dice)
        elif playernumchoise == Dice + 1 or playernumchoise == Dice - 1:
            print("too close :)")
            print("the random number is :", Dice)
        elif playernumchoise > Dice + 1 or Dice - 1 < playernumchoise < Dice + 1 or playernumchoise < Dice - 1:
            print("better luck next time")
            print("the random number is :", Dice)

        print("round", round, "!")
thank you
With every loop in while you have:
round = 1
round += 1
So round can't be anything else than 2. You should move round = 1 out of while loop.
in every iteration of the loop you first set round to 1 (line 8) and then immediately increase it by 1 (on line 9)
And round is poor choice for variable name as round() is built-in function, so you override it and will no longer be able to use it.
(Jan-20-2019, 12:25 PM)perfringo Wrote: [ -> ]With every loop in while you have:
round = 1
round += 1
So round can't be anything else than 2. You should move round = 1 out of while loop.

THANK you sir!, i forgot this little information (even i asked for the reasoning behind that in one of my threads xD)

buran: oh i didn't know round is a built in function ill change the name thank you