Trouble referencing a modified variable

This is my first post, so sorry if this is dumb. I am a few weeks into my first python class and I am making a choose your own adventure zombie game where each choice you make affects the time until the zombies arrive. I also want a food element where every 20 minutes you need to eat one food. I tried making a variable of elapsed_time which would be 180 (the starting time) minus the time_left, but it doesn’t take into account that the time_left is modified by choices below. What am I doing wrong?

time_left = 180
food = 2
elapsed_time = 180 - time_left

while elapsed_time >= 20:
  print("You have",food, "cans of food.")
  print(elapsed_time, time_left)
  if food > 0:
    elapsed_time -=20
    food-=1
  elif food == 0:
    print("Game Over")
    break

(everything else is below this)

  choice1 = str(input("Gas Station (G) or Warehouse (W)?"))
  if choice1 == "G":
    time_left-=10

an example of a choice below that affects the time left.

you can make elapsed_time a function, if you already know about functions.
A simpler, but a bit more cumbersome solution could be drop the elapsed_time variable and use only time_left, substituting elapsed_time with (180-time_left).
For example, by changing the while to
while (180 - time_left) >= 20:
or, better,
while time_left <= 160:
and so on

When you declare elapsed_time, it is computed only once and store the result number only. It does not remember that it used time_left for this. In your script, the third line is equivalent to simply stating elapsed_time = 0. This is why it doesn’t update when you change the value of time_left.

You want to compute how much time has elapsed, and to do that, you need to turn it into a function:

def elapsed_time():
  return 180 - time_left

Then to get the current value, you must call the function, just like how you use functions like print and input:

if elapsed_time() >= 200:
  print("You have been playing for a while")

This way, the value coming out of elapsed_time will be recalculated each time you request its value.


As a side note, I believe that your first snippet has a few bugs where you check elapsed_time when I think you mean to check or decrement time_left. You might want to consider to not use two names at all and stick to just the one for simplicity:

time_left = 180
food = 2

while time_left >= 20:
  if food > 0:
    print("Nom nom nom")
    time_left -= 20
    food -= 1
  elif food == 0:
    print("Game Over")
    break

print(time_left)

This will give the following output:

Nom nom nom
Nom nom nom
Game Over
140