Why ever reassign a variable?


I’ve reached that part of my Python lesson to learn that a variable can be defined and then re-assigned.

What reason would anyone have for doing this? Wouldn’t it keep the code less confusing to just keep things defined the way they were instead of changing them somewhere else down the line?

Here’s the example I have from the lesson:

# my_int is set to 7 below. What do you think
# will happen if we reset it to 3 and print the result?

my_int = 7

# Change the value of my_int to 3 on line 8!

my_int = 3

# Here's some code that will print my_int to the console:
# The print keyword will be covered in detail soon!

print my_int


It happens a lot in a program.

In a purist environment variable values would never change. But that takes specialized functional code which is a little beyond the scope of these lessons.

What if my_int is the iterator in a dynamic loop? If it does not change then the loop will continue forever, or until the system shuts down the program, which is not something we would expect since infinite loops are a fundamental aspect of many programs.


Few things in life are constant
Think about things a program could do, let’s say a bonus calculator.
Heres some pseudocode

sales = 0;      // amount of sales an employee made
pay = 2000;  // base pay

sales = input("How many sales did you make? ") // set sales equal to whatever the user says

if (sales > 10) {   // if employee made more than ten sales
    pay += 500;  // increase their pay by 500

I had two variables sales and pay. Both have the potential to change throughout my very short program.
It is the nature of variables to change, that’s why they are called variables!


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.