Python course · Module 1: Python Basics

Variables - Paths in the Jungle

8 min read ·
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:

# Compass points north
direction = "North"

# Map shows coordinates
latitude = -3.4653
longitude = 29.3608

# Counting discovered species
species_count = 47

# Did we find a rare species?
rare_species_found = True

The = 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:

# Syntax: variable_name = value

# Text (strings)
explorer_name = "Darwin"
jungle_type = "tropical"

# Whole numbers (integers)
team_size = 5
days_in_jungle = 14

# Decimal numbers (floats)
temperature = 32.5
humidity = 78.3

# Logical values (booleans)
is_safe = True
found_water = False

Important: 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:

# Snake case (recommended in Python)
jungle_temperature = 30
discovered_species = ["Python", "Parrot", "Lion"]

# Can contain letters, digits, underscores
species_1 = "Python regius"
species_2 = "Panthera leo"
rare_species_2024 = "New species"

# Can start with an underscore
_private_notes = "Secret information"
__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:

# Cannot start with a digit
# 1st_species = "Error!"  # SyntaxError

# Cannot contain spaces or hyphens
# jungle temperature = 30  # SyntaxError
# jungle-temperature = 30  # SyntaxError

# Cannot use special characters
# species! = "Error"  # SyntaxError
# species@ = "Error"  # SyntaxError

# Cannot be a Python keyword
# if = 5  # SyntaxError
# for = 10  # SyntaxError
# def = "text"  # SyntaxError

jungle_temperature = 30  # correct: underscore instead of a space

The 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:

# You CANNOT use these names as variables:
# False      await      else       import     pass
# None       break      except     in         raise
# True       class      finally    is         return
# and        continue   for        lambda     try
# as         def        from       nonlocal   while
# assert     del        global     not        with
# async      elif       if         or         yield

import keyword
print(len(keyword.kwlist))  # 35

You 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:

# Descriptive names - you immediately know what they store
daily_temperature = 32
discovered_species_count = 15
expedition_start_date = "2024-11-24"

# Bad names - unclear, short
t = 32  # What is t?
x = 15  # What does x mean?
d = "2024-11-24"  # Date of what?

# Snake case (Python style)
jungle_humidity_level = 80

# camelCase (popular in JavaScript and Java) - not for Python variables!
jungleHumidityLevel = 80

# Long names are OK if they're descriptive
number_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:

explorer_name = "Darwin"
expedition_day = 5

# Simple print
print(explorer_name)  # Darwin
print(expedition_day)  # 5

# Print with text
print("Explorer:", explorer_name)  # Explorer: Darwin

# F-string (the best way!) - Python 3.6+
print(f"Hello, {explorer_name}!")
# Hello, Darwin!

print(f"Expedition day: {expedition_day}")
# Expedition day: 5

# Complex f-strings
species_found = 12
days = 3
print(f"We discovered {species_found} species in {days} days!")
# We discovered 12 species in 3 days!

print(f"Temperature: {30}°C")  # Temperature: 30°C

Python 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:

# Day 1 of the expedition
species_count = 5
print(f"Day 1: {species_count} species")  # Day 1: 5 species

# Day 2 - we found more
species_count = 12
print(f"Day 2: {species_count} species")  # Day 2: 12 species

# Day 3 - adding new discoveries
species_count = species_count + 7  # 12 + 7 = 19
print(f"Day 3: {species_count} species")  # Day 3: 19 species

Each 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:

# Assigning multiple variables in one line
x, y, z = 10, 20, 30
print(f"x={x}, y={y}, z={z}")  # x=10, y=20, z=30

# Same value for multiple variables
a = b = c = 0
print(f"a={a}, b={b}, c={c}")  # a=0, b=0, c=0

# Swapping values
first = "A"
second = "B"
print(f"Before: first={first}, second={second}")  # Before: first=A, second=B

first, second = second, first  # Magic swap!
print(f"After: first={first}, second={second}")  # After: first=B, second=A

During 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:

# Simple question
name = input("What's your name? ")
print(f"Hello, {name}!")

# Input ALWAYS returns a string (text)!
age_text = input("How old are you? ")
print(type(age_text))  # <class 'str'>

# Converting to a number
age = int(age_text)  # Change string → int
print(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:

# Program: Explorer's Journal
print("=== Expedition Journal ===")

# Collecting data
explorer_name = input("Explorer name: ")
location = input("Location: ")
species_found = int(input("How many species did you discover today? "))
temperature = float(input("Temperature (°C): "))
notes = input("Notes for the day: ")

# Displaying the report
print("\n--- DAILY REPORT ---")
print(f"Explorer: {explorer_name}")
print(f"Location: {location}")
print(f"Discovered species: {species_found}")
print(f"Temperature: {temperature}°C")
print(f"Notes: {notes}")
print("--- 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:

  1. Asks for your name
  2. Asks for your favorite animal
  3. Asks for your favorite number
  4. Displays: "Hello {name}! Your favorite animal is {animal} and your favorite number is {number}!"
Code for this lesson: main.py
# Task: Create a program that collects user data

# TODO: Ask for the name
name = input("What is your name? ")

# TODO: Ask for favorite animal
animal = input("Favorite animal: ")

# TODO: Ask for favorite number
number = input("Favorite number: ")

# TODO: Display a message using an f-string
print(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) and int(), 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.

Docs entries used in this lesson

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. 1. Which variable name is VALID in Python?

  2. 2. Which naming style is recommended for variables in Python?

  3. 3. The input() function returns data as:

  4. 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:

  1. Coding taskCreating Your First Variable
  2. Coding taskDifferent Variable Types
  3. Coding taskF-strings
  4. QuestionVariable Naming
  5. QuestionSnake case
  6. Click in orderBuilding print()
  7. QuestionInput function
  8. QuestionPrint function
  9. Put in orderProgram with f-string

Useful articles