How can i retain the value of a variable in python using while loops and if statements? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

How can i retain the value of a variable in python using while loops and if statements?

a=50 i=50 while i>=0: b=int(input()) if b==1: i=a-5 if b==2: print(i) I want the value of i to decrease to zero but it is not decreasing and is stuck at 45.

18th Apr 2019, 11:19 AM
Labhinder Singh
Labhinder Singh - avatar
2 Answers
+ 6
I changed your code so it looks like this and works fine i=50 b=int(input()) while i>=0: if b==1: i=i-5 print(i) if b==2: print(i) I removed a as it is unnecessary And as Honfu said i is always 45 as you assign i to a-5 ( without changing a ANYWHERE!) So it should look like i = i - 5 or i -= 5 Also I moved the input part to the top so you need only 1 input (otherwise you'll have to enter about 10 inputs and face EOF errors)
18th Apr 2019, 12:09 PM
Seniru
Seniru - avatar
+ 5
You wrote i = a-5. You change a nowhere in your loop, so it's always 50. So i is always 45.
18th Apr 2019, 11:21 AM
HonFu
HonFu - avatar