PyStart

Learn Python

From zero to hero — every concept explained with real-life analogies and annotated code.

1

Getting Started & Basic Syntax

8 sections · The foundations you need

1.1 What is Python & What Can It Do

Imagine you have a Swiss Army knife for the digital world — that's Python. It's a programming language that can do almost anything: build websites, analyze data, automate boring tasks, create games, power AI, and much more.

Python was created by Guido van Rossum and released in 1991. Its philosophy is simple: readability counts. The code looks almost like English, which makes it one of the most beginner-friendly languages on the planet.

Real-world uses: Instagram runs on Python (Django). Netflix uses it for data analysis. NASA uses it for scientific computing. Even the controller of a robotic vacuum cleaner might be running Python!

Why it's great for beginners: The syntax is readable like English, there's a massive community ready to help, and you can start building useful things after just a few lessons. It's like learning to cook — you don't need to be a chef to make a delicious meal.

# Python is so readable, it almost reads like English print("Hello, World!") # This single line is a complete Python program! # It tells the computer to display a message on screen.
Try Exercises for Section 1.1

1.2 Installing Python & Your First Line of Code

Think of this like learning to say your first word in a new language. Before you can have conversations, you need to set up the environment and say that very first "Hello."

Step 1 — Download: Go to python.org and download the latest version for your operating system (Windows, macOS, or Linux). Run the installer — and make sure to check the box that says "Add Python to PATH" on Windows!

Step 2 — Open IDLE or Terminal: IDLE is Python's built-in code editor that comes with the installation. On Mac/Linux, you can also open the Terminal and type python3.

Step 3 — Type your first line: Type print("Hello, World!") and press Enter. Congratulations — you just ran your first Python program!

# Your very first Python program print("Hello, World!") # Output: # Hello, World! # Try changing the message: print("I'm learning Python!") # Output: # I'm learning Python!
Try Exercises for Section 1.2

1.3 Comments

Imagine you're following a recipe and you leave sticky notes for yourself — "don't forget the salt!" or "this takes 20 minutes." That's exactly what comments are in Python: notes you write in your code that the computer completely ignores.

Single-line comments start with #. Everything after the # on that line is ignored by Python.

Multi-line comments use triple quotes """ ... """. Technically they're string literals, but when not assigned to a variable, they serve as multi-line comments.

# This is a single-line comment print("Hello") # You can also place comments after code """ This is a multi-line comment. It can span multiple lines. Python will ignore all of it. """ print("Comments help you remember what your code does!")
Try Exercises for Section 1.3

1.4 Variables

Think of variables as labeled boxes. You put something in a box and write a name on it so you can find it later. In Python, you create a variable by simply writing a name, an equals sign, and a value.

Unlike some other languages, Python doesn't require you to declare the type of a variable — it figures it out automatically. You just assign a value and go.

Variable names should be descriptive (use student_name instead of x). They can contain letters, numbers, and underscores, but can't start with a number.

# Creating variables is like labeling boxes name = "Alex" # A box labeled "name" containing the text "Alex" age = 25 # A box labeled "age" containing the number 25 is_student = True # A box labeled "is_student" containing True print(name) # Output: Alex print(age) # Output: 25 # You can change what's inside the box anytime age = 26 # Happy birthday! Age is now 26 print(age) # Output: 26
Try Exercises for Section 1.4

1.5 Data Types

Imagine you have different shaped containers — tall ones for numbers, flat ones for text, and on/off switches for True/False. Python has four basic data types that work just like this:

  • int (integer) — Whole numbers like 42, -7, 0. Think: counting apples.
  • float — Decimal numbers like 3.14, -0.5, 2.0. Think: measuring temperature.
  • str (string) — Text like "Hello", 'Python'. Think: writing a message.
  • bool (boolean) — Only True or False. Think: a light switch — on or off.

You can check the type of any value using the type() function.

# The four basic data types score = 95 # int — a whole number temperature = 36.6 # float — a decimal number greeting = "Hi there" # str — text (in quotes) is_raining = False # bool — True or False # Check types with type() print(type(score)) # <class 'int'> print(type(temperature)) # <class 'float'> print(type(greeting)) # <class 'str'> print(type(is_raining)) # <class 'bool'>
Try Exercises for Section 1.5

1.6 Type Conversion

Imagine you need to repackage items from one type of container to another. You have water in a tall bottle (int) but need it in a wide bowl (float). That's type conversion — Python lets you convert between data types using special functions.

The key functions are: int(), float(), str(), and bool(). Each one takes a value and tries to convert it to that type.

Be careful: not all conversions work! Trying to convert "hello" to an int will cause an error, because Python can't turn that text into a number.

# Converting between types age_str = "25" age_int = int(age_str) # "25" → 25 (string to int) age_float = float(age_str) # "25" → 25.0 (string to float) price = 9.99 price_int = int(price) # 9.99 → 9 (float to int, truncates!) number = 42 number_str = str(number) # 42 → "42" (int to string) # Boolean conversion — any non-zero/non-empty value is True print(bool(0)) # False print(bool(1)) # True print(bool("")) # False (empty string) print(bool("Hi")) # True (non-empty string)
Try Exercises for Section 1.6

1.7 Input with input()

Imagine ordering at a restaurant — you sit down, and the waiter waits for you to tell them what you want. The input() function works the same way: it pauses your program and waits for the user to type something.

Whatever the user types is returned as a string — even if they type a number. If you need a number, you'll need to convert it with int() or float().

You can pass a string to input() to show a prompt — like a sign that says "What would you like to order?"

# Getting user input name = input("What is your name? ") print("Hello, " + name + "!") # Input is always a string — convert for numbers age = input("How old are you? ") # age is a string like "25" age_num = int(age) # now it's an integer 25 print("Next year you'll be", age_num + 1)
Try Exercises for Section 1.7

1.8 Operators

Operators are the buttons on your calculator, the pans on your balance scale, and the traffic lights of your program. Python has four main groups:

  • Arithmetic — Like calculator buttons: + - * / % // **
  • Assignment — Like putting results in a box: = += -= *=
  • Comparison — Like a balance scale, returns True/False: == != > < >= <=
  • Logical — Like traffic light decisions: and or not

% is modulo (remainder), // is floor division (rounds down), ** is exponentiation (power).

# Arithmetic operators print(10 + 3) # 13 addition print(10 - 3) # 7 subtraction print(10 * 3) # 30 multiplication print(10 / 3) # 3.333... division (always float) print(10 % 3) # 1 remainder (modulo) print(10 // 3) # 3 floor division print(2 ** 3) # 8 exponent (2 to the power of 3) # Assignment operators x = 10 x += 5 # x = x + 5 → x is now 15 x -= 3 # x = x - 3 → x is now 12 x *= 2 # x = x * 2 → x is now 24 # Comparison operators print(5 == 5) # True equal? print(5 != 3) # True not equal? print(5 > 3) # True greater than? # Logical operators print(True and False) # False — both must be True print(True or False) # True — at least one True print(not True) # False — flips the value
Try Exercises for Section 1.8
2

Branching — The if Family

5 sections · Making decisions in code

2.1 if Statement

Imagine a bouncer at a club door — they check your ID, and only let you in if you meet the condition (you're old enough). That's exactly what an if statement does in Python: it checks a condition, and if it's True, the code inside runs. If it's False, the code is simply skipped.

The condition must be an expression that evaluates to True or False. The code block inside the if must be indented (typically 4 spaces) — Python uses indentation instead of curly braces to define blocks.

# Basic if statement — the bouncer check age = 20 if age >= 18: print("Welcome to the club!") # If age is 20, the condition is True → prints the message # If age were 15, the condition is False → nothing happens
Try Exercises for Section 2.1

2.2 if…else

Picture a fork in the road — you can go left or right, there's no third option. if…else gives your program exactly two paths: one for when the condition is True, and one for when it's False.

This is perfect for yes/no, pass/fail, on/off situations. Every possible outcome is covered — one of the two blocks will always run.

# if...else — a fork in the road score = 45 if score >= 60: print("You passed!") else: print("You failed. Try again!") # Since score is 45 (less than 60), the else block runs # Output: You failed. Try again!
Try Exercises for Section 2.2

2.3 if…elif…else

Think of a restaurant menu with multiple meal choices — you pick one dish from many options. if…elif…else lets you check multiple conditions in order. Python goes through them one by one and runs the first block where the condition is True.

The else at the end is optional — it acts as the "none of the above" catch-all. You can have as many elif clauses as you need.

# if...elif...else — a menu with multiple choices grade = 85 if grade >= 90: print("A — Excellent!") elif grade >= 80: print("B — Good job!") elif grade >= 70: print("C — Not bad") elif grade >= 60: print("D — Barely passed") else: print("F — Failed") # grade is 85 → first True condition is >= 80 # Output: B — Good job!
Try Exercises for Section 2.3

2.4 Nested if

Imagine a building with rooms inside rooms — first you enter the building (outer if), then you enter a specific room (inner if). A nested if is simply an if statement placed inside another if statement.

The inner if only gets checked if the outer if was True. Each level adds another indentation. Try to avoid going more than 2-3 levels deep — deeply nested code gets hard to read!

# Nested if — rooms inside rooms has_ticket = True age = 20 if has_ticket: # First check: do you have a ticket? print("Ticket checked.") if age >= 18: # Second check: are you old enough? print("Enjoy the movie!") else: print("Sorry, this movie is for adults only.") else: print("You need a ticket first!") # Both conditions True → "Ticket checked." then "Enjoy the movie!"
Try Exercises for Section 2.4

2.5 Branching Practice

Let's put it all together with some mini problems that combine if, elif, and else. These are the kinds of real-world logic you'll write all the time!

Practice makes perfect — try modifying the values and see how the output changes. Understanding branching is the key to making your programs "think."

# Problem 1: Grading system score = 78 if score >= 90: letter = "A" elif score >= 80: letter = "B" elif score >= 70: letter = "C" elif score >= 60: letter = "D" else: letter = "F" print("Grade:", letter) # Output: Grade: C # Problem 2: Leap year check year = 2024 if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0): print(year, "is a leap year") else: print(year, "is not a leap year") # Output: 2024 is a leap year # Problem 3: Discount calculator total = 150 if total >= 100: discount = 0.2 # 20% off elif total >= 50: discount = 0.1 # 10% off else: discount = 0 # no discount print("You pay:", total * (1 - discount)) # Output: You pay: 120.0
Try Exercises for Section 2.5
3

Loops

6 sections · Repeating actions efficiently

3.1 for Loop Basics

Imagine an assembly line — each item comes down the line one by one, and the same process is applied to every single one. That's a for loop: it iterates over a sequence (like a list or range) and processes each item in order.

The most common pattern is for variable in range(...):. The range() function generates a sequence of numbers for the loop to iterate through.

Remember: range(5) gives you 0, 1, 2, 3, 4 — it starts at 0 and stops before the number you give it.

# for loop with range — the assembly line for i in range(5): print("Processing item", i) # Output: # Processing item 0 # Processing item 1 # Processing item 2 # Processing item 3 # Processing item 4 # range(start, stop) — count from 1 to 5 for num in range(1, 6): print(num) # prints 1, 2, 3, 4, 5 # Iterating over a list fruits = ["apple", "banana", "cherry"] for fruit in fruits: print("I like", fruit)
Try Exercises for Section 3.1

3.2 while Loop Basics

Think of running laps on a track — you keep going as long as you still have energy. A while loop keeps running as long as its condition is True. The moment the condition becomes False, the loop stops.

Important: Make sure something inside the loop eventually makes the condition False! Otherwise you'll create an infinite loop that runs forever. Always have a way to "run out of energy."

# while loop — running laps while you have energy energy = 5 while energy > 0: print("Running a lap! Energy:", energy) energy -= 1 # decrease energy each lap print("Out of energy! Time to rest.") # Output: # Running a lap! Energy: 5 # Running a lap! Energy: 4 # Running a lap! Energy: 3 # Running a lap! Energy: 2 # Running a lap! Energy: 1 # Out of energy! Time to rest.
Try Exercises for Section 3.2

3.3 Loop Control: break/continue

Sometimes you need special actions in a loop: break is like an emergency exit — you immediately leave the entire loop. continue is like saying "skip this one, move on" — you skip the rest of the current iteration and jump to the next one.

Use break when you've found what you're looking for and don't need to keep looping. Use continue when you want to skip certain items but keep looping.

# break — the emergency exit for num in range(1, 10): if num == 5: print("Found 5! Emergency exit!") break print(num) # Output: 1, 2, 3, 4, then "Found 5! Emergency exit!" # The loop stops — 6, 7, 8, 9 are never printed # continue — skip this one, move on for num in range(1, 6): if num == 3: print("Skipping 3!") continue print(num) # Output: 1, 2, "Skipping 3!", 4, 5 # 3 is skipped but the loop continues
Try Exercises for Section 3.3

3.4 Nested for Loops

Think of a calendar — weeks within months, each day gets its turn. A nested for loop is a loop inside another loop. For every iteration of the outer loop, the inner loop runs completely from start to finish.

This is incredibly useful for working with grids, tables, or any 2D structure. The outer loop handles rows, the inner loop handles columns.

# Nested for loops — like a calendar for week in range(1, 4): # 3 weeks print("--- Week", week, "---") for day in ["Mon", "Wed", "Fri"]: # 3 days each week print(" " + day) # Output: # --- Week 1 --- # Mon Wed Fri # --- Week 2 --- # Mon Wed Fri # --- Week 3 --- # Mon Wed Fri # Drawing a rectangle with nested loops for row in range(3): for col in range(5): print("⬛", end=" ") print() # new line after each row
Try Exercises for Section 3.4

3.5 Nested while Loops

Picture a clock — seconds tick within minutes tick within hours. A nested while loop works the same way: an inner while loop runs inside an outer while loop, and each has its own condition.

Be extra careful with nested while loops — make sure both conditions will eventually become False, or you'll have an infinite loop on your hands!

# Nested while loops — like a clock hours = 0 while hours < 3: # outer loop: hours minutes = 0 while minutes < 2: # inner loop: minutes print(f"Time: {hours}:{minutes:02d}") minutes += 1 hours += 1 # Output: # Time: 0:00 # Time: 0:01 # Time: 1:00 # Time: 1:01 # Time: 2:00 # Time: 2:01
Try Exercises for Section 3.5

3.6 Mixed Branch + Loop Nesting

Imagine a security checkpoint at an airport — everyone goes through the line (loop), but some people get pulled aside for extra screening (if condition). Combining loops with if statements is one of the most common and powerful patterns in programming.

You can put if inside for, for inside if, or any combination. The key is to think step by step: what repeats? What's the condition?

# Mixed: loop + if — airport security checkpoint passengers = ["Alice", "Bob", "Charlie", "Diana"] extra_screening = ["Bob", "Diana"] for person in passengers: # everyone goes through the line if person in extra_screening: # some get pulled aside print(person, "→ extra screening") else: print(person, "→ cleared") # Output: # Alice → cleared # Bob → extra screening # Charlie → cleared # Diana → extra screening # Another example: sum only even numbers total = 0 for num in range(1, 11): if num % 2 == 0: # check if even total += num print("Sum of even numbers:", total) # Output: Sum of even numbers: 30 (2+4+6+8+10)
Try Exercises for Section 3.6
4

Function Basics — def

5 sections · Writing reusable code

4.1 What Are Functions & Built-in Functions

Think of functions as vending machine buttons — press one, get a specific result. You don't need to know the machinery inside; you just push the button and out comes your snack. Functions are reusable blocks of code that perform a specific task.

Python comes with many built-in functions that are ready to use right away — no setup needed. You've already used several! Each built-in function is like a button on the vending machine that's already installed and labeled for you.

  • print() — displays output on screen
  • len() — tells you the length of something (string, list, etc.)
  • type() — tells you the data type of a value
  • int(), float(), str() — convert between types
  • input() — gets user input
  • range() — generates a sequence of numbers
# Built-in functions — vending machine buttons already installed print(len("Hello")) # 5 — length of the string print(type(42)) # <class 'int'> print(max(3, 7, 1)) # 7 — the largest value print(min(3, 7, 1)) # 1 — the smallest value print(abs(-15)) # 15 — absolute value print(round(3.14159, 2)) # 3.14 — round to 2 decimal places # There are 60+ built-in functions in Python! # You can explore them all at docs.python.org
Try Exercises for Section 4.1

4.2 Custom Functions with def

If built-in functions are like pre-installed vending machine buttons, then writing your own function is like creating a brand-new recipe. You decide exactly what goes in and what comes out. Once you define it, you can use it as many times as you want — no need to rewrite the same code over and over!

You define a function with the def keyword, followed by the function name, parentheses, and a colon. The code inside must be indented. To use it, just call the function by name with parentheses.

# Defining your own function — writing a new recipe def greet(): print("Welcome to Python!") print("Let's have some fun!") # Call the function — use your recipe greet() # Output: # Welcome to Python! # Let's have some fun! # Call it as many times as you want! greet() # prints again greet() # and again!
Try Exercises for Section 4.2

4.3 Function Parameters

Imagine a form with blanks to fill in — the structure is always the same, but you fill in different information each time. Parameters are those blanks. They let you pass different data into your function each time you call it, making your function flexible and reusable.

When you define the function, the blanks are called parameters. When you call the function and fill in actual values, those values are called arguments. The function uses the parameter names inside its body to work with the data.

# Function with parameters — blanks in a form def greet_person(name): # "name" is the parameter (the blank) print("Hello,", name, "!") # use it inside the function # Call with different arguments (fill in the blank) greet_person("Alice") # Hello, Alice ! greet_person("Bob") # Hello, Bob ! # Multiple parameters — multiple blanks def introduce(name, age): print(f"I'm {name} and I'm {age} years old.") introduce("Charlie", 22) # I'm Charlie and I'm 22 years old. introduce("Diana", 28) # I'm Diana and I'm 28 years old.
Try Exercises for Section 4.3

4.4 Return Values

Remember the vending machine? You press a button and it gives you a snack back. The return statement is how a function hands you a result. Without return, a function just does its work silently and gives back None (Python's way of saying "nothing").

When a function returns a value, you can store it in a variable, use it in calculations, or pass it to another function. The return statement immediately ends the function — no code after it will run.

# Return values — the vending machine gives you a snack back def add(a, b): result = a + b return result # hand the result back # Now you can use the returned value total = add(3, 5) print(total) # 8 print(add(10, 20)) # 30 — use it directly! # Without return, you get None def no_return(): print("I do something but return nothing") x = no_return() # prints the message print(x) # None — no return value!
Try Exercises for Section 4.4

4.5 Function Calls & Nested Calls

Imagine delegating tasks at work — you ask one person to handle something, they ask another person for help, and the result bubbles back up to you. In Python, you can call a function from inside another function, and you can even use a function call as an argument to another function.

This is incredibly powerful. It means you can build complex behavior from simple, well-tested pieces — like assembling LEGO blocks. Each function does one job well, and they combine to solve bigger problems.

# Nested function calls — delegating tasks def double(n): return n * 2 def add_one(n): return n + 1 # Call one function inside another result = add_one(double(5)) # Step 1: double(5) → 10 # Step 2: add_one(10) → 11 print(result) # 11 # You can even nest built-in functions print(len(str(12345))) # 5 # Step 1: str(12345) → "12345" # Step 2: len("12345") → 5 # Function calling another function (delegation) def get_greeting(name): return "Hello, " + name + "!" def print_greeting(name): message = get_greeting(name) # delegate to get_greeting print(message) print_greeting("Pythonista") # Hello, Pythonista!
Try Exercises for Section 4.5