</>
CodeLearn Pro
Start Learning Free โ†’

Python โ€” Complete Beginner Tutorial

6 modules ยท 17 examples ยท Click โ–ถ Run on any example to see the output

โœฆ Beginner
โ† Overview

๐Ÿ’ก How to use this page

Read the explanation, study the code, then hit โ–ถ Run to see the output.

Module 01

Variables & Data Types

A variable is like a labelled box โ€” you put a value in it and give it a name so you can use it later. Python figures out the type automatically, so you never have to declare it.

Creating Variables

In Python you just write the name, an equals sign, and the value. That is it โ€” no special keywords needed. You can store text (called a string), whole numbers (integers), decimal numbers (floats), or true/false values (booleans).

example.pyPython 3
# Text โ€” called a "string", always in quotes
name = "Alice"

# Whole number โ€” called an "integer"
age = 25

# Decimal number โ€” called a "float"
height = 1.72

# True or False โ€” called a "boolean"
is_student = True

# Print them all out
print(name)
print(age)
print(height)
print(is_student)
Click Run to see output
๐Ÿ’ก

Variable names should be lowercase with underscores between words, like my_name or favourite_colour. This is called "snake_case" and is the Python standard.

The print() Function

print() is how Python shows you information. You can print multiple things at once, combine text and variables using f-strings (put an f before the quote), and even do maths inside print().

example.pyPython 3
name = "Bob"
age = 30
city = "Cape Town"

# Print a single value
print(name)

# Print multiple things (separated by commas)
print("Name:", name, "| Age:", age)

# f-string: put variables directly in text
print(f"My name is {name} and I am {age} years old.")
print(f"I live in {city}.")

# Maths inside print
print(f"Next year I'll be {age + 1}.")
Click Run to see output
๐Ÿ’ก

f-strings (f"...") are the modern, easiest way to mix variables and text. The variable goes inside curly braces {}.

Getting Input from the User

input() pauses the program and waits for the user to type something. Whatever they type comes back as a string. If you need a number, wrap it with int() or float() to convert it.

example.pyPython 3
# Ask the user for their name
name = input("What is your name? ")
print(f"Hello, {name}!")

# Ask for a number โ€” must convert with int()
age = int(input("How old are you? "))
next_year = age + 1
print(f"Next year you will be {next_year}.")

# Ask for a decimal number
price = float(input("Enter a price: "))
discounted = price * 0.9   # 10% off
print(f"With 10% discount: R{discounted:.2f}")
Click Run to see output
๐Ÿ’ก

input() always returns a string (text). If someone types "25", Python sees it as the text "25", not the number 25. Use int() or float() to convert it to a number you can do maths with.

Module 02

Operators & Conditions

Operators let you do maths and compare values. Conditions (if/elif/else) let your program make decisions โ€” like "if the score is above 50, print pass, otherwise print fail".

Maths Operators

Python has all the basic maths operators plus two special ones: // for integer division (no decimal) and % for the remainder (called modulo).

example.pyPython 3
a = 20
b = 6

print(a + b)    # Addition       โ†’ 26
print(a - b)    # Subtraction    โ†’ 14
print(a * b)    # Multiplication โ†’ 120
print(a / b)    # Division       โ†’ 3.33...
print(a // b)   # Integer div    โ†’ 3
print(a % b)    # Remainder      โ†’ 2
print(a ** 2)   # Power          โ†’ 400

# Common shorthand
score = 10
score += 5      # same as: score = score + 5
print(score)
Click Run to see output
๐Ÿ’ก

The % (modulo) operator gives you the remainder after division. 20 % 6 = 2 because 6 goes into 20 three times with 2 left over. It is great for checking if a number is even: num % 2 == 0.

if / elif / else

if runs a block of code only when a condition is True. elif ("else if") checks another condition. else runs if nothing else matched.

example.pyPython 3
score = 75

if score >= 80:
    print("Grade: A โ€” Excellent!")
elif score >= 70:
    print("Grade: B โ€” Good job!")
elif score >= 60:
    print("Grade: C โ€” Average")
elif score >= 50:
    print("Grade: D โ€” Just passed")
else:
    print("Grade: F โ€” Try again")

# One-line shorthand (for simple checks)
age = 20
status = "Adult" if age >= 18 else "Minor"
print(f"Status: {status}")
Click Run to see output
๐Ÿ’ก

Python uses INDENTATION (spaces at the start of a line) to group code. Everything indented under an if belongs to it. Use 4 spaces โ€” never mix spaces and tabs.

Comparison & Logical Operators

Comparison operators compare two values and give back True or False. Logical operators (and, or, not) combine multiple conditions.

example.pyPython 3
age = 22
has_id = True

# Comparison operators
print(age == 22)    # Equal to         โ†’ True
print(age != 18)    # Not equal        โ†’ True
print(age > 18)     # Greater than     โ†’ True
print(age < 30)     # Less than        โ†’ True
print(age >= 22)    # Greater or equal โ†’ True
print(age <= 25)    # Less or equal    โ†’ True

print("---")

# Logical operators: and, or, not
print(age >= 18 and has_id)   # Both must be True
print(age < 18 or has_id)     # At least one True
print(not has_id)              # Flips True to False

print("---")

# Real example
if age >= 18 and has_id:
    print("Welcome! You may enter.")
else:
    print("Sorry, you cannot enter.")
Click Run to see output
๐Ÿ’ก

"and" only gives True if BOTH sides are True. "or" gives True if at least ONE side is True. "not" flips True to False and False to True.

Module 03

Loops

Loops let you repeat code without copy-pasting it. A for loop repeats a set number of times. A while loop keeps going as long as a condition is True.

for Loops

A for loop goes through each item in a sequence one by one. Use range() to loop a specific number of times.

example.pyPython 3
# Loop through a list of items
fruits = ["apple", "banana", "cherry"]

for fruit in fruits:
    print("I like", fruit)

print("---")

# range(5) gives: 0, 1, 2, 3, 4
for i in range(5):
    print(f"Count: {i}")

print("---")

# range(start, stop) โ€” stops BEFORE end number
for i in range(1, 6):
    print(f"Number: {i}")

print("---")

# range(start, stop, step) โ€” count by 2s
for i in range(0, 10, 2):
    print(i, end=" ")
print()
Click Run to see output
๐Ÿ’ก

range(5) starts at 0 and goes UP TO but NOT INCLUDING 5. So you get 0,1,2,3,4 โ€” that is 5 numbers total.

while Loops

A while loop keeps repeating as long as its condition stays True. Always make sure something inside the loop eventually makes the condition False.

example.pyPython 3
# Count from 1 to 5
count = 1

while count <= 5:
    print(f"Count is: {count}")
    count += 1    # IMPORTANT: increase or loop runs forever!

print("Done!")

print("---")

# Guessing game example
secret = 7
guess = 0
attempts = 0

while guess != secret:
    guess = int(input("Guess the number (1-10): "))
    attempts += 1
    if guess < secret:
        print("Too low! Try again.")
    elif guess > secret:
        print("Too high! Try again.")

print(f"Correct! You got it in {attempts} attempt(s).")
Click Run to see output
๐Ÿ’ก

Every while loop needs something inside it that eventually makes the condition False. Without it, the loop runs forever โ€” this is called an "infinite loop".

break and continue

break immediately stops a loop. continue skips the rest of the current step and goes to the next one.

example.pyPython 3
# break: stop the loop early
print("Finding first even number over 5:")
for i in range(1, 20):
    if i > 5 and i % 2 == 0:
        print(f"Found it: {i}")
        break
    print(f"  Checking {i}...")

print("---")

# continue: skip this step, go to next
print("Odd numbers only:")
for i in range(1, 11):
    if i % 2 == 0:
        continue   # skip even numbers
    print(i, end=" ")
print()

print("---")

# Practical: skip empty strings
names = ["Alice", "", "Bob", "", "Charlie"]
print("Non-empty names:")
for name in names:
    if name == "":
        continue
    print(f"  Hello, {name}!")
Click Run to see output
๐Ÿ’ก

"break" is like an emergency exit โ€” it gets you out of the loop immediately. "continue" is like skipping a song โ€” it jumps to the next item without stopping the whole loop.

Module 04

Lists & Tuples

A list is a collection of items in a specific order. Think of it like a shopping list โ€” you can add things, remove things, and look up items by their position. Tuples are like lists but cannot be changed once created.

Creating & Accessing Lists

Lists use square brackets []. Items are separated by commas. Every item has an index (position number) starting from 0. Negative indexes count from the end.

example.pyPython 3
# Creating a list
colours = ["red", "green", "blue", "yellow", "purple"]

# Accessing items by index (starts at 0!)
print(colours[0])    # First item
print(colours[1])    # Second item
print(colours[-1])   # Last item
print(colours[-2])   # Second from last

print("---")

# Slicing: get a range of items [start:stop]
print(colours[1:4])   # index 1, 2, 3 (not 4)
print(colours[:3])    # From start to index 3
print(colours[2:])    # From index 2 to end

print("---")

print(len(colours))           # Number of items
print("blue" in colours)      # Check if item exists
print("orange" in colours)    # โ†’ False
Click Run to see output
๐Ÿ’ก

Indexing starts at 0, not 1. So a list with 5 items has indexes 0,1,2,3,4. The last valid index is always len(list) - 1.

Changing Lists โ€” Common Methods

Lists are "mutable" โ€” you can change them after creating them. Python gives you handy built-in methods to add, remove, sort, and more.

example.pyPython 3
shopping = ["milk", "eggs", "bread"]
print("Start:", shopping)

shopping.append("butter")
print("After append:", shopping)

shopping.insert(1, "cheese")
print("After insert:", shopping)

shopping.remove("eggs")
print("After remove:", shopping)

last = shopping.pop()
print("Popped:", last)
print("After pop:", shopping)

shopping.sort()
print("Sorted:", shopping)

shopping.reverse()
print("Reversed:", shopping)

nums = [1, 2, 2, 3, 2, 4]
print("2 appears:", nums.count(2), "times")
Click Run to see output
๐Ÿ’ก

append() adds to the END. insert(index, value) adds at a SPECIFIC position. remove() deletes the first matching item. pop() removes and returns the last item.

Module 05

Functions

A function is a reusable block of code you give a name to. Instead of writing the same code over and over, you write it once as a function and call it whenever you need it.

Defining & Calling a Function

Use the def keyword to define a function. Give it a name, then parentheses (), then a colon. The indented code below it is the function body.

example.pyPython 3
# Define a function
def say_hello():
    print("Hello there!")
    print("Welcome to Python.")

# Call the function
say_hello()
say_hello()   # Call it again!

print("---")

# Function with a parameter (input value)
def greet(name):
    print(f"Hello, {name}!")
    print(f"Nice to meet you, {name}.")

greet("Alice")
greet("Bob")
greet("Charlie")
Click Run to see output
๐Ÿ’ก

Defining a function does NOT run it. It just saves it for later. You must CALL the function (say_hello()) to actually run the code inside it.

Return Values & Default Parameters

Functions can send a value back using return. Default parameters have a fallback value if you do not pass one.

example.pyPython 3
def add(a, b):
    result = a + b
    return result

total = add(10, 5)
print("10 + 5 =", total)
print("20 + 30 =", add(20, 30))

print("---")

# Default parameter โ€” used if argument not given
def greet(name, greeting="Hello"):
    return f"{greeting}, {name}!"

print(greet("Alice"))
print(greet("Bob", "Good morning"))
print(greet("Carol", "Hey"))

print("---")

def is_even(number):
    return number % 2 == 0

print(is_even(4))
print(is_even(7))

for num in range(1, 8):
    if is_even(num):
        print(f"{num} is even")
Click Run to see output
๐Ÿ’ก

return stops the function immediately and sends a value back. A function can only return ONE value โ€” but that value can be a list, letting you return multiple things at once.

Variable Scope

Variables created inside a function only exist inside that function. Understanding scope prevents a very common beginner bug.

example.pyPython 3
# Global variable (created outside any function)
language = "Python"

def show_info():
    version = 3.12           # Local variable
    print(f"Language: {language}")   # Can read global โœ…
    print(f"Version: {version}")

show_info()
# print(version) โ† This would CRASH!

print("---")

def double(number):
    number = number * 2   # Only changes local copy
    return number

my_num = 10
result = double(my_num)
print(f"Original: {my_num}")   # Still 10 โ€” not changed!
print(f"Doubled:  {result}")
Click Run to see output
๐Ÿ’ก

Local variables live and die inside their function. If you try to use a local variable outside the function, Python will say "NameError: name is not defined".

Module 06

Dictionaries

A dictionary stores data as key-value pairs โ€” like a real dictionary where you look up a word (key) to find its meaning (value). Instead of an index number, you use a meaningful label to find your data.

Creating & Using Dictionaries

Dictionaries use curly braces {}. Each item is a key: value pair. The key is usually a string. Use square brackets with the key name to get the value.

example.pyPython 3
student = {
    "name": "Alice",
    "age": 20,
    "grade": "A",
    "city": "Cape Town"
}

# Accessing values by key
print(student["name"])
print(student["age"])
print(student["grade"])

print("---")

# Safer way: .get() โ€” returns None if key missing
print(student.get("city"))
print(student.get("phone"))          # Returns None, no crash!
print(student.get("phone", "N/A"))   # Default if missing

print("---")

student["age"] = 21
print("Updated age:", student["age"])

student["email"] = "alice@example.com"
print("Email added:", student["email"])

print("name" in student)    # True
print("phone" in student)   # False
Click Run to see output
๐Ÿ’ก

If you access a key that does not exist with [], Python crashes with a KeyError. Use .get() instead โ€” it returns None (or a default you choose) without crashing.

Looping & Dictionary Methods

You can loop through a dictionary to see all its keys, values, or both at once using .keys(), .values(), and .items().

example.pyPython 3
person = {
    "name": "Bob",
    "age": 28,
    "job": "Developer",
    "city": "Durban"
}

print("Keys:")
for key in person:
    print(" ", key)

print("---")

print("Values:")
for value in person.values():
    print(" ", value)

print("---")

print("All info:")
for key, value in person.items():
    print(f"  {key}: {value}")

print("---")

del person["city"]
print("After delete:", person)

students = {
    "Alice": {"grade": "A", "score": 95},
    "Bob":   {"grade": "B", "score": 82},
    "Carol": {"grade": "A", "score": 91},
}

for name, info in students.items():
    print(f"{name} got {info['grade']} ({info['score']}%)")
Click Run to see output
๐Ÿ’ก

.items() gives you both the key and value at once as a pair โ€” this is what you will use 90% of the time when looping through a dictionary.

You finished the Python tutorial!

You now know the core of Python โ€” variables, conditions, loops, lists, functions and dictionaries. These are the building blocks of everything else. Pick a direction and keep going!