Python course · Module 1: Python Basics
Variables - Paths in the Jungle
In this lesson11
Welcome back! Darwin here. The field journal keeps filling up: marching direction, camp coordinates, number of species. Text from print() vanishes once shown, but a program must store data and come back to it. That is what variables are for.
What Are Variables?
Imagine that during an expedition you find various items:
- A compass pointing the direction
- A map with a marked location
- A notebook with the number of discovered species
Each of these items has a name and stores a value. In Python, these are variables - like labeled jars in the specimen tent. Here is a journal entry as code:
1# Compass points north
2direction = "North"
3
4# Map shows coordinates
5latitude = -3.4653
6longitude = 29.3608
7
8# Counting discovered species
9species_count = 47
10
11# Did we find a rare species?
12rare_species_found = TrueThe = sign is not equality but assignment: the name on the left gets attached to the value on the right. Nothing was displayed - variables wait in memory.
Creating Variables
The syntax is always the same: a name, an equals sign, a value. Only the kind of value changes:
1# Syntax: variable_name = value
2
3# Text (strings)
4explorer_name = "Darwin"
5jungle_type = "tropical"
6
7# Whole numbers (integers)
8team_size = 5
9days_in_jungle = 14
10
11# Decimal numbers (floats)
12temperature = 32.5
13humidity = 78.3
14
15# Logical values (booleans)
16is_safe = True
17found_water = FalseImportant: Python automatically recognizes the variable type! You don't need to declare it. Decimals use a dot: 32,5 raises no error, it creates a pair of numbers, 32 and 5.
Variable Naming - Jungle Rules
A name is a signpost on the trail: readable for you and valid for Python.
Allowed:
A name can contain letters, digits and underscores, and words are joined with an underscore - the snake_case style. Square brackets create a list, you will meet it later:
1# Snake case (recommended in Python)
2jungle_temperature = 30
3discovered_species = ["Python", "Parrot", "Lion"]
4
5# Can contain letters, digits, underscores
6species_1 = "Python regius"
7species_2 = "Panthera leo"
8rare_species_2024 = "New species"
9
10# Can start with an underscore
11_private_notes = "Secret information"
12__hidden_treasure = "Treasure"By convention, a leading underscore means "for internal use".
Not Allowed:
These lines raise a SyntaxError, so Python would refuse to run the program - hence the comments. The last line is the correct version:
1# Cannot start with a digit
2# 1st_species = "Error!" # SyntaxError
3
4# Cannot contain spaces or hyphens
5# jungle temperature = 30 # SyntaxError
6# jungle-temperature = 30 # SyntaxError
7
8# Cannot use special characters
9# species! = "Error" # SyntaxError
10# species@ = "Error" # SyntaxError
11
12# Cannot be a Python keyword
13# if = 5 # SyntaxError
14# for = 10 # SyntaxError
15# def = "text" # SyntaxError
16
17jungle_temperature = 30 # correct: underscore instead of a spaceThe hyphen is out because Python reads it as minus: jungle-temperature is a subtraction, and you cannot assign to a calculation.
Python Keywords (reserved):
Keywords have a fixed meaning in the language, so they cannot be variable names:
1# You CANNOT use these names as variables:
2# False await else import pass
3# None break except in raise
4# True class finally is return
5# and continue for lambda try
6# as def from nonlocal while
7# assert del global not with
8# async elif if or yield
9
10import keyword
11print(len(keyword.kwlist)) # 35You can always check the list in keyword.kwlist. async and await joined in Python 3.7, so older tables miss them.
Good Naming Practices
Python accepts the name t, but in a week you won't remember its meaning. Compare the names:
1# Descriptive names - you immediately know what they store
2daily_temperature = 32
3discovered_species_count = 15
4expedition_start_date = "2024-11-24"
5
6# Bad names - unclear, short
7t = 32 # What is t?
8x = 15 # What does x mean?
9d = "2024-11-24" # Date of what?
10
11# Snake case (Python style)
12jungle_humidity_level = 80
13
14# camelCase (popular in JavaScript and Java) - not for Python variables!
15jungleHumidityLevel = 80
16
17# Long names are OK if they're descriptive
18number_of_rare_species_discovered_in_2024 = 3 # Clear!Both styles run, since Python doesn't check style. It is a convention from the PEP 8 guide: variables in snake_case, PascalCase (e.g. JungleExpedition) for classes. Use snake_case from day one.
Displaying Variables
print() accepts a variable like text, and an f-string, a string with the letter f before the quote, puts values straight into a sentence:
1explorer_name = "Darwin"
2expedition_day = 5
3
4# Simple print
5print(explorer_name) # Darwin
6print(expedition_day) # 5
7
8# Print with text
9print("Explorer:", explorer_name) # Explorer: Darwin
10
11# F-string (the best way!) - Python 3.6+
12print(f"Hello, {explorer_name}!")
13# Hello, Darwin!
14
15print(f"Expedition day: {expedition_day}")
16# Expedition day: 5
17
18# Complex f-strings
19species_found = 12
20days = 3
21print(f"We discovered {species_found} species in {days} days!")
22# We discovered 12 species in 3 days!
23
24print(f"Temperature: {30}°C") # Temperature: 30°CPython evaluates everything in the braces {}: a variable, a calculation, even a bare number, as in the last line. Without the f, the braces are printed literally. A comma in print() works too, but I recommend f-strings: they read better.
Changing Variable Values
Variables can change their value (that's why they're called "variables"!). Each day brings discoveries, and we update the same entry:
1# Day 1 of the expedition
2species_count = 5
3print(f"Day 1: {species_count} species") # Day 1: 5 species
4
5# Day 2 - we found more
6species_count = 12
7print(f"Day 2: {species_count} species") # Day 2: 12 species
8
9# Day 3 - adding new discoveries
10species_count = species_count + 7 # 12 + 7 = 19
11print(f"Day 3: {species_count} species") # Day 3: 19 speciesEach assignment discards the old value. In the last step Python first computes the right side (12 + 7), then attaches the result to the name. A bare species_count + 7 without = would change nothing.
Multiple Variables at Once
Python allows clever assignments: several variables in one line, a shared starting value and swapping places:
1# Assigning multiple variables in one line
2x, y, z = 10, 20, 30
3print(f"x={x}, y={y}, z={z}") # x=10, y=20, z=30
4
5# Same value for multiple variables
6a = b = c = 0
7print(f"a={a}, b={b}, c={c}") # a=0, b=0, c=0
8
9# Swapping values
10first = "A"
11second = "B"
12print(f"Before: first={first}, second={second}") # Before: first=A, second=B
13
14first, second = second, first # Magic swap!
15print(f"After: first={first}, second={second}") # After: first=B, second=ADuring the swap Python reads both values first, then assigns them crosswise, so no helper variable is needed. The number of names must match the number of values: x, y = 1, 2, 3 is a ValueError.
Input - Collecting Data from the User
User data comes through input(): it shows a question, waits for a keyboard answer and hands it to the program:
1# Simple question
2name = input("What's your name? ")
3print(f"Hello, {name}!")
4
5# Input ALWAYS returns a string (text)!
6age_text = input("How old are you? ")
7print(type(age_text)) # <class 'str'>
8
9# Converting to a number
10age = int(age_text) # Change string → int
11print(f"Next year you'll be {age + 1} years old")IMPORTANT: input() always returns a string! A typed 25 is the text "25", and "25" + 1 ends with a TypeError. Only a conversion gives you a number: int() or float().
Practical Example - Expedition Journal
Let's combine everything into an evening journal program: it asks for data, converts the numbers and prints a report:
1# Program: Explorer's Journal
2print("=== Expedition Journal ===")
3
4# Collecting data
5explorer_name = input("Explorer name: ")
6location = input("Location: ")
7species_found = int(input("How many species did you discover today? "))
8temperature = float(input("Temperature (°C): "))
9notes = input("Notes for the day: ")
10
11# Displaying the report
12print("\n--- DAILY REPORT ---")
13print(f"Explorer: {explorer_name}")
14print(f"Location: {location}")
15print(f"Discovered species: {species_found}")
16print(f"Temperature: {temperature}°C")
17print(f"Notes: {notes}")
18print("--- END OF REPORT ---")In int(input(...)) the answer goes straight into the conversion, so species_found is a number. The location field stays a string, because we don't calculate with it.
Practical Exercise
Try to create a program on your own that:
- Asks for your name
- Asks for your favorite animal
- Asks for your favorite number
- Displays: "Hello {name}! Your favorite animal is {animal} and your favorite number is {number}!"
Code for this lesson: main.py
1# Task: Create a program that collects user data
2
3# TODO: Ask for the name
4name = input("What is your name? ")
5
6# TODO: Ask for favorite animal
7animal = input("Favorite animal: ")
8
9# TODO: Ask for favorite number
10number = input("Favorite number: ")
11
12# TODO: Display a message using an f-string
13print(f"Hello {name}! Your favorite animal is {animal} and your favorite number is {number}!")Summary
Before moving on, make sure that:
- You can create a variable and change its value
- You understand naming rules
- You display variables with
print()and f-strings - You know the difference between
input()(string) andint(),float()
In the next lesson Darwin will show you data types - how to classify discoveries in the jungle!
Remember: a variable is a labeled jar in the camp tent - name on the label, value inside, contents swappable at any time.
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. Which variable name is VALID in Python?
2. Which naming style is recommended for variables in Python?
3. The input() function returns data as:
4. What will be displayed: print(f'Temperature: {30}°C')?
Hands-on tasks in the game
- Code editor
Create a variable explorer_name with the value "Darwin":
- Code editor
Create 4 variables of different types: text (str), a whole number (int), a decimal number (float) and a boolean (bool):
- Code editor
Store a name in the variable name and print a greeting with that name using an f-string:
- Click in order
Build a print() call that displays the text Hello:
- Vertical ordering
Arrange the program steps in order: