Changing a value
A variable is created the first time a value is stored in it, with name = value. In the last module most values came from input. A value written straight into the code works the same way, and a new value can be built from other variables:
greeting = "Good morning"
city = "Lisbon"
message = greeting + ", " + city + "!"
print(message)
Good morning, Lisbon!Nothing here comes from the user, so the program greets Lisbon on every run until someone edits the code. Values fixed in the code like this are called hard-coded.
A variable can vary
As its name says, the value of a variable can change. Each assignment replaces the old value, and the variable always holds the latest one:
status = "waiting"
print(status)
status = "running"
print(status)
status = "done"
print(status)
waiting
running
doneA new value from the old one
The new value can be built from the old value of the same variable:
title = input("Title: ")
title = "* " + title + " *"
print(title)
title = title + " (draft)"
print(title)
Summer plansTitle: Summer plans
* Summer plans *
* Summer plans * (draft)title = "* " + title + " *" would be nonsense in mathematics, but remember that = is an instruction, not a claim. Python first works out the right side with the value title has right now, "* " + "Summer plans" + " *", and only then stores the result back in title.
Each line uses the value of that moment
Python runs the lines in order, and each line uses the values the variables have when that line runs. Changing a variable later doesn't change anything that was already built from it:
pet = "cat"
sentence = "My " + pet + " is asleep."
pet = "dog"
print(sentence)
print(pet)
My cat is asleep.
dogsentence was built while pet was still "cat". From then on it's a finished string: it doesn't remember which variables its parts came from.