Variables
A variable is a concept used in every programming language. Without variables, we can’t code.
A variable is used to remember a certain value so you can reuse it later on.
The assignment gives its value to a variable. The syntax is the following:
name = value
where to the left of the assignment symbol =, you write the name of your variable and to the right of the assignment symbol =, you write the value to be assigned.
Example
x = 8
result = 4 * 3
message = "hello"
Rules for naming a variable
- A variable name can be composed only by letters (uppercase & lowercase), numbers and underscore.
- A variable name can’t start with a number.
- Python is case sensitive so Age, aGe and age are three different variables.
Text vs Variable
To make sure that Python understands that we are writing text and not defining a new variable, we need to put apostrophe, quote or both around text.
Exercise
In the interpreter, type the following and observe the results:
- age = 14
- age
- age + 2
- age
- age = age + 2
- age
Question 1
Why did the value saved in the variable age change the second time you add 2 and not the first time?
- age = “age” * 2
- age
Question 2
Why is the text age saved in my variable age instead of a number?