A variable is a name that points to a value, like a label stuck on a box. Once you've stored a value under a name, you can use the name anywhere in your program instead of typing the value again.
Every value in Python also has a type. Text is a string, whole numbers are integers, decimals are floats and yes/no values are booleans. The type decides what you can do with a value: you can multiply two numbers, but you can't multiply two pieces of text together.
In this lesson you'll create variables, meet the four basic types, build sentences with f-strings, ask the user for input and convert between types.
Creating variables
You create a variable by writing a name, an equals sign and a value:
name = "Maya"
age = 14
height = 1.62The = sign means "store this value under this name", not "is equal to". You can change a variable later by assigning a new value, and the old one is replaced:
score = 10
score = score + 5 # score is now 15Python works out the type from the value, so you never have to declare it in advance.
Naming rules
- Names can contain letters, digits and underscores, but can't start with a digit.
- Names are case-sensitive:
age,AgeandAGEare three different variables. - You can't use Python's own keywords such as
if,fororclassas names. - By convention, Python uses snake_case: lowercase words joined by underscores, like
total_priceorfirst_name.
Choose names that say what the value means. minutes_left is far easier to understand than m or x2.
Assigning several variables at once
Python lets you assign more than one variable in a single line. The values on the right are matched to the names on the left in order:
x, y = 10, 20
first = second = 0 # both names refer to 0
x, y = y, x # swap: x is now 20, y is now 10The swap works because Python builds the right-hand side, (20, 10), completely before assigning anything. In many other languages you need a temporary third variable to swap two values.
Python has no special keyword for constants. Instead, programmers write names that should never change in capitals, such as MAX_LIVES = 3 or VAT_RATE = 0.2. Python will still let you reassign them; the capitals are a signal to other people reading the code.
The four basic types
| Type | Example | Used for |
|---|---|---|
str (string) | "Hello", '42' | Text of any length |
int (integer) | 7, -3, 2024 | Whole numbers |
float | 3.14, 0.5, -2.0 | Numbers with a decimal point |
bool (boolean) | True, False | Yes or no answers |
Use type() to check what type a value is: type(3.5) gives <class 'float'>. Notice that "42" in quotes is a string, not a number. The quotes are what make it text.
Dynamic typing and the None value
Python is dynamically typed: the type belongs to the value, not to the variable. The same name can hold a number now and text later.
result = 42
print(type(result)) # <class 'int'>
result = "forty-two"
print(type(result)) # <class 'str'>This is convenient, but it also means Python won't warn you if you accidentally replace a number with a string. Clear names and consistent types keep programs predictable.
There is one more value you will see often: None. It means "no value yet" or "nothing here". A variable set to None exists, but it does not hold a useful value:
winner = None
if winner is None:
print("No winner yet")Check for it with is None, not == None. Functions that don't return anything also give back None, which you'll meet in the functions lesson.
f-strings: putting values into text
An f-string has an f before the opening quote. Inside it, anything in {curly braces} is replaced by its value:
name = "Maya"
age = 14
print(f"{name} is {age} years old.")This prints Maya is 14 years old. You can even put calculations inside the braces, such as {age + 1}. Add :.2f to show a number with two decimals: {price:.2f}.
input() and converting types
input() shows a message, waits for the user to type something and press Enter, then gives you what they typed as a string, even if they typed a number.
age = input("How old are you? ")
age = int(age) # turn "14" into 14
print(f"Next year you'll be {age + 1}")To do maths with typed numbers, convert them with int() for whole numbers or float() for decimals. str() goes the other way and turns a number into text.
Python Variables Syntax
Variables, f-strings and conversion
variable_name = value
message = f"Text with {variable_name} inside"
number = int("42") # str to int
decimal = float("3.5") # str to float
text = str(99) # int to str
answer = input("Question? ")Python Variables Summary
name = valuestores a value in a variable; assigning again replaces it.- Use descriptive snake_case names. Names are case-sensitive.
- The basic types are
str,int,floatandbool. Check them withtype(). - f-strings like
f"Hi {name}"put values inside text. input()always returns a string. Convert withint(),float()orstr().
Python Variables Examples
Each example shows the code, the output it produces and what each part does.
A profile card
name = "Maya"
age = 14
height = 1.62
likes_coding = True
print(f"Name: {name}")
print(f"Age: {age}")
print(f"Height: {height} m")
print(f"Likes coding: {likes_coding}")
print(type(name), type(age), type(height), type(likes_coding))Name: Maya
Age: 14
Height: 1.62 m
Likes coding: True
<class 'str'> <class 'int'> <class 'float'> <class 'bool'>Line-by-line explanation
- Lines 1 to 4One variable for each of the four basic types.
- Lines 6 to 9f-strings drop each value into a sentence.
- Line 10type() confirms what Python decided each value is.
Updating a variable
lives = 3
print("Lives:", lives)
lives = lives - 1
print("Ouch! Lives:", lives)
lives -= 1
print("Ouch again! Lives:", lives)Lives: 3
Ouch! Lives: 2
Ouch again! Lives: 1Line-by-line explanation
- Line 4The right side is worked out first (3 - 1), then stored back in lives.
- Line 7
-=is a shortcut for the same thing. There are also+=,*=and/=.
A tip calculator with input
Here the user typed 48 and 15.
bill = float(input("Bill amount: "))
percent = int(input("Tip percent: "))
tip = bill * percent / 100
total = bill + tip
print(f"Tip: {tip:.2f}")
print(f"Total to pay: {total:.2f}")Bill amount: 48
Tip percent: 15
Tip: 7.20
Total to pay: 55.20Line-by-line explanation
- Lines 1 to 2input() returns text, so it's converted straight away with float() and int().
- Lines 4 to 5Normal maths now works because both values are numbers.
- Lines 7 to 8
:.2fshows exactly two decimal places, which suits money.
Common Python Variables Mistakes
Doing maths on input() directly
age = input("Age: ")
print(age + 1) # TypeErrorage = int(input("Age: "))
print(age + 1)input() gives back a string, and Python can't add the number 1 to text.
Joining text and numbers with +
points = 20
print("Points: " + points)points = 20
print(f"Points: {points}")Use an f-string, or str(points), to turn the number into text first.
Starting a name with a digit
1st_place = "Ada"first_place = "Ada"Variable names can contain digits but can't begin with one, so the first line is a SyntaxError.
Python Variables in Real Projects
Variables in real programs
A weather app stores the current temperature in a variable, a game keeps score and lives, and an online shop tracks cart_total. Converting types matters too: everything that arrives from a form, a file or the keyboard is text, so real programs convert it to numbers before doing any maths, just like the tip calculator above.
Python Variables FAQ
Do I need to declare a variable's type in Python?
No. Python works out the type from the value you assign, so count = 5 creates an int and count = "5" creates a str. You can add optional type hints such as count: int = 5 to document your intent, but Python does not enforce them when the program runs.
What is the difference between = and == in Python?
A single = assigns a value to a name: age = 14. A double == compares two values and gives True or False: age == 14. Writing = where you meant == inside an if statement is a syntax error, which Python reports straight away.
How do I check the type of a variable?
type(value) shows the exact type, which is handy while learning. In real code, isinstance(value, int) is usually better for checks, because it also accepts subclasses and can test several types at once: isinstance(value, (int, float)).
Why is input() giving me a string when I typed a number?
input() always returns exactly what the user typed, as text. Python can't know whether "42" is meant to be a number, a code or part of an address. Convert it yourself with int() or float(), and expect a ValueError if the text is not a valid number.
Can a Python variable name contain spaces or hyphens?
No. A space ends the name and a hyphen means subtraction, so total price and total-price are both errors. Use an underscore instead: total_price.
Python Variables Exercises
Answer each one and check it instantly. If you get stuck, open the hint before the answer.
Complete the code so it prints Hi, Sam!.
name = "Sam"
print("Hi, {}!")
What does this print?
x = 5
x = x * 2
x += 1
print(x)
Which value is a string?
The user types 7. What does this print?
n = input("Number: ")
print(n * 3)
Which variable name is valid in Python?
Python Variables Quiz
5 questions to check what you learned.
What type is the value
3.0?- int
- str
- float
- bool
Which variable name follows Python's usual style?
- total_price
- TotalPrice
- totalprice!
- total-price
What does
input()always return?- An int
- Whatever type the user typed
- A boolean
- A string
What does
print(f"{7 / 2:.1f}")show?- 3.5
- 3
- 3.50
- 7 / 2
What does
type(int("7") + 0.5)give?- <class 'int'>
- <class 'float'>
- <class 'str'>
- An error