Back to the main roadmap | Previous lesson: Basic Syntax | Next lesson: Conditionals
Think of a variable as a labeled box.
You can store something inside the box and give it a name so you can use it later.
age = 10Here:
ageis the name of the box.10is the value stored inside the box.
You can access the value anytime.
age = 10
print(age)10
The value stored in a variable can be changed at any time.
age = 10
age = 11
print(age)11
The old value (10) is replaced by the new value (11).
Different kinds of values are stored using different data types.
| Data Type | Description | Example |
|---|---|---|
int |
Whole numbers | age = 10 |
float |
Numbers with decimal points | height = 4.5 |
str |
Text (String) | name = "Alex" |
bool |
Only True or False |
is_student = True |
Stores whole numbers.
age = 10
print(age)10
Stores decimal numbers.
height = 4.5
print(height)4.5
Stores text.
Strings are written inside single quotes (' ') or double quotes (" ").
name = "Alex"
print(name)Alex
A Boolean can have only one of two values:
TrueFalse
is_student = True
print(is_student)True
Python is smart enough to determine the data type based on the value you assign.
You don't need to specify the type yourself.
age = 10
height = 5.8
name = "Alex"
is_student = TruePython automatically understands:
10→int5.8→float"Alex"→strTrue→bool
Use the type() function to find the data type of a variable.
age = 10
print(type(age))<class 'int'>
Another example:
name = "Alex"
print(type(name))Back to the main roadmap | Previous lesson: Basic Syntax | Next lesson: Conditionals
<class 'str'>
Follow these rules when naming variables.
# Correct
my_age = 20
# Incorrect
my age = 20# Correct
age1 = 20
# Incorrect
1age = 20age = 20
Age = 30
print(age)
print(Age)20
30
age and Age are considered two different variables.
-
A variable is a named container used to store data.
-
Variables can be updated by assigning a new value.
-
Python has four common data types:
intfloatstrbool
-
Use
type()to check the data type of a variable. -
Variable names cannot contain spaces or start with numbers.
-
Python is case-sensitive (
ageandAgeare different).
Next Lesson: Conditionals