Variables
What is a variable?
A variable is a name that stores a value in your program. Think of it as a labeled box where you can keep information.
Declaring and assigning values to variables
Declaring a variable means creating the “box” and giving it a name. Variable names should be descriptive (e.g., user_name, not just x).
Assigning a value to a variable means putting something in the box. The = symbol is used to assign a value to a variable. You can change a variable’s value anytime by assigning a different value to it.
Usually variables are initialised with a particular value when it is declared, so the two steps of declaring and assigning a value occur together.
Why use variables?
Variables help you:
-
Save information for later use. Once you’ve stored “Welcome to your personal teaching app!” in the variable
greeting, you can reuse it anywhere in the program after it has been declared. -
Make your code easier to read and change. You can change the value of
greetingto something different elsewhere in the program; in this case you are assigning a new value to the variablegreeting. The old value is overwritten and completely forgotten after this assignment happens, and the variable will have the new value for the rest of the program or until it is assigned another new value.
E.g. If you run the code:
greeting = "Hello!"
greeting = "Goodbye!"
print(greeting) # Output: Goodbye!
x = 5
y = 3
sum = x + y
print(sum) # Output: 8
← Back to where you were | → Start the course from the beginning
