Variable assignment
- Python course
- Beginner
- Lesson 7/116
- 4 min
Learn to assign variables with = and dynamic typing.
What is a variable?
A variable is a named box that stores a value. In Python we assign a value with the = sign:
age = 25
name = "Alex"The name on the left is the variable, the value on the right is what it holds. When you assign, Python creates the variable and binds the value.
You can print a variable with print: print(age) prints 25.
Dynamic typing
Python is dynamically typed: you do not declare the type, Python infers it from the value. The same variable can hold values of different types:
x = 5 # int
x = "text" # now strThis flexibility is handy but be careful: code that ignores types may produce surprising errors. You can check the type any time with type(x).
Practice Declare a variable and print it
Assign 25 to the age variable. Then print it with print(age).
Starter code
# Declare the variableSample solution
age = 25
print(age)Expected output
25
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which is a valid assignment?
- 25 = age
- age == 25
- age = 25 Correct answer
- age: 25
Explanation: age = 25 has the name on the left and value on the right.
2 Assign 5 to x
x ____
print(x)
x =
print(x)
Explanation: = . Assignment uses a single =.
3 When is a variable's type set in Python?
- When the type is declared
- At compile time
- Before the program starts
- When a value is assigned Correct answer
Explanation: Python is dynamically typed; the type comes from the value.