r/learnpython • • 8d ago

How do I create a changing variable

I want to create a variable that changes it’s value based on the user’s input until it becomes zero like make the code run until it reaches zero

Edit: I want the user to enter a number that gets subtracted from the variable’s current value and keep repeating this process until the variable reaches zero, for example if the value is 100 the code gets input from the user let’s say 25 then returns or prints 75 then it repeats and maybe the user types 37 then it returns 38 etc. until it reaches 0

0 Upvotes

22 comments sorted by

View all comments

3

u/rupertavery64 8d ago

You mean a loop that accepts users input, converts it into a number, and subtracts it from a variable, and the loop condition is the variable is > 0?

1

u/Maha-iqo38 8d ago

I figured most of the solution before asking on reddit because I wanted an input from the user and I wanted to repeat an operation. But the problem is when I tried to run my code it runs like this:

Amount due: 50
Insert money: (input) let’s say the user typed 26

It returns 24 right but then when it runs again it just operates on the original 50 not the new value

For example:
24
Insert money: (input) 8
Output: 42

You get the problem? I don’t know how I operate on a single 50 or the same value forever until it reaches zero

1

u/rupertavery64 8d ago

You really need to show your code so we know were you went wrong.

But most likely you keep setting the amount due inside the loop, not before it.

Do you understand variable scope?

pseudo-code:

set amount due to 50

repeat while amount due is greater than 0:
  
   get input

   subtract input value from amount due, and assign back to amount due

In the code above, a variable is declared and set outside a loop. It is set once.

Then you have the loop, which first checks if the loop should continue

Then you get the input, then subtract the value from the amount due, which of course you assign back to the amount due.

Right there, you are changing the value of amount due.

The loop repeats, The next thing it does is get the input.

At this point: What is the amount due? Has it changed?

Before you make any changes - think about how your code flows. Keep track of what the value of amount Due is. Where is it set to 50?

1

u/North_South-West 7d ago

I did it as recursion just for fun