I'm trying to write a very basic Python program to calculate the number of minutes per week.
I've created an Hr_Per_Day
variable, but when I update this variable, min_per_day
, which should update, doesn't. Why not?
Here's the code:
Hr_Per_Day = 24
min_per_day = Hr_Per_Day * 60
min_per_day
**OUTPUT: 1440**
Hr_Per_Day = 26
min_per_day
**OUTPUT: 1440**
Why doesn't min_per_day
update after I change Hr_Per_Day
to 24? Any help would be appreciated!
I expected min_per_day
to update after changing Hr_Per_Day
.
CodePudding user response:
min_per_day = Hr_Per_Day * 60
It seems like you expect this assignment to act like an ongoing formula, and if Hr_Per_Day
ever changes, then min_per_day
will also change.
Python doesn't work that way.
That assignment is a one-time calculation, using the value of Hr_Per_Day
at that moment. If that value changes later, it will have no effect on min_per_day
.
CodePudding user response:
Its important to understand two things:
- Python statements are run one by one and are always completed before the next statement is run.
- Variables hold values - each variable can hold 1 value that cannot be changed - the variable can be assigned a new value, but the value itself never changes.
So in your case, you calculate the value of min_per_day
by reading the value of Hr_Per_day
and doing a mathematical operation on it, then the result is stored in the variable min_per_day
.
After that, if you assign a new value to the variable Hr_Per_Day
, it cannot change the result of the previous statement. If you want to tell Python to recalculate the value for min_per_day
based on the new value of Hr_Per_Day
, you have to run the calculation statement again - something like this:
Hr_Per_Day = 24
min_per_day = Hr_Per_Day * 60
print(min_per_day)
# Output: 1440
Hr_Per_Day = 26
min_per_day = Hr_Per_Day * 60
print(min_per_day)
# Output: 1560