We use cookies to enhance your experience on the site
CodeWorlds

Variables - Paths in the Jungle

Welcome back, @name! Darwin here. In the first lesson you learned the basics of Python. Now it's time for the next step - variables.

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, we call these variables.

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 = True

Creating Variables

Creating a variable in Python is simple:

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 = False

Important: Python automatically recognizes the variable type! You don't need to declare it.

Variable Naming - Jungle Rules

✅ Allowed:

1# Snake case (recommended in Python)
2jungle_temperature = 30
3discovered_species = ["Python", "Parrot", "Tiger"]
4
5# Can contain letters, digits, underscores
6species_1 = "Python regius"
7species_2 = "Panthera tigris"
8rare_species_2024 = "New species"
9
10# Can start with an underscore
11_private_notes = "Secret information"
12__hidden_treasure = "Treasure"

❌ Not Allowed:

1# Cannot start with a digit
2# 1st_species = "Error!"  # SyntaxError
3
4# Cannot contain spaces
5# jungle temperature = 30  # SyntaxError
6
7# Cannot use special characters
8# species! = "Error"  # SyntaxError
9# species@ = "Error"  # SyntaxError
10
11# Cannot be a Python keyword
12# if = 5  # SyntaxError
13# for = 10  # SyntaxError
14# def = "text"  # SyntaxError

Python Keywords (reserved):

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

Good Naming Practices

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 (used in other languages, but in Python only for classes)
15jungleHumidityLevel = 80  # Not for variables!
16
17# ✅ Long names are OK if they're descriptive
18number_of_rare_species_discovered_in_2024 = 3  # Clear!

Displaying Variables

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!

Changing Variable Values

Variables can change their value (that's why they're called "variables"!):

1# Day 1 of the expedition
2species_count = 5
3print(f"Day 1: {species_count} species")  # 5
4
5# Day 2 - we found more
6species_count = 12
7print(f"Day 2: {species_count} species")  # 12
8
9# Day 3 - adding new discoveries
10species_count = species_count + 7  # 12 + 7 = 19
11print(f"Day 3: {species_count} species")  # 19

Multiple Variables at Once

Python allows for clever assignments:

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}")  # A, B
13
14first, second = second, first  # Magic swap!
15print(f"After: first={first}, second={second}")  # B, A

Input - Collecting Data from the User

Sometimes we need data from the user:

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! If you need a number, you must convert it.

Practical Example - Expedition Journal

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 ---")

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}!"

Summary

In this lesson you learned:

  • ✅ What variables are and how to create them
  • ✅ Variable naming rules
  • ✅ Displaying variables with `print()` and f-strings
  • ✅ Changing variable values
  • ✅ Getting data from the user with `input()`

Checkpoint

Before moving on, make sure that:

  • [ ] You can create a variable
  • [ ] You understand naming rules
  • [ ] You know the difference between `input()` (string) and `int()`, `float()`
  • [ ] You can use f-strings

In the next lesson Darwin will show you data types - how to classify discoveries in the jungle! 🌴🐍

Go to CodeWorlds