Variables
What are Variables?
- Variables are named locations for storing data in a program
- They hold values that can change while the program runs
- Variables should have meaningful names that are obvious and simple.
Python Examples
String
In this example, the variable is called ‘name’ and the value is “Alice”.
name = "Alice" print(name)
Integer
In this example, the variable is called ‘age’ and the value is 25.
age = 25 print(age)
Real / Float
In this example, the variable is called ‘pi’ and the value is ‘3.14’.
pi = 3.14 print(pi)
Reusing a Variable
In this example, the variable is called ‘message’ and it’s value is “Bye”.
The variable is used more than one time. On line 2 it is printed out once, but on line 3 is is printed out twice.
message = "Bye" print(message) print(message, message)
Changing a Variable's Value
In this example, the variable is called ‘score’. On line 1 score is set to 10, but on line 2 it is set to 20.
When ‘score’ is printed out on line 3, it will display 20.
score = 10 score = 20 print(score)