Welcome to Programming with Python!
Have you ever wondered how video games know when to give you points, or how apps make decisions? Computers are incredibly fast, but they aren't smart on their own. They need clear, step-by-step instructions written in a language they understand. In this chapter, we will learn how to write programs using a text-based language called Python.
Every single computer program in the world—from a simple calculator to a massive video game—is built using three core building blocks known as the "Big Three" programming constructs:
1. Sequence (doing things in order)
2. Selection (making decisions)
3. Iteration (repeating actions)
Don't worry if this sounds like a lot right now! We are going to break each concept down into small, bite-sized pieces with plenty of everyday examples.
---The Fundamentals: Data Types and Variables
Before building complex programs, a computer needs a way to store and remember information. We use variables as named containers or labelled boxes to store data.
1. Basic Data Types
In Python, different kinds of information are classified into data types:
• Integer (int): Whole numbers with no decimal point, such as \(5\), \(0\), or \(-2\).
• Float / Real (float): Numbers that have decimal points, such as \(3.14\) or \(0.5\).
• String (str): Text or words surrounded by quotation marks, like "Hello World" or "Gamer123".
• Boolean (bool): A simple logical state that can only be either True or False.
2. Input and Output
To communicate with a user, a program must be able to display messages and ask questions:
• Output (print): Displays information on the screen.
Example: print("Welcome to the quiz!")
• Input (input): Asks the user to type something in.
Example: name = input("What is your name? ")
⚠️ Important Trap to Avoid (Type Casting):
The input() function always saves user answers as text (a String). If you ask someone for a number and try to do maths with it, Python will get confused! To fix this, we convert (cast) it into a number using int() or float():
• Correct numeric input: age = int(input("Enter your age: "))
3. Doing Maths with Arithmetic Operators
Computers are brilliant at calculations. Here are the arithmetic symbols you can use in Python:
• Addition: + (e.g. \(5 + 3\))
• Subtraction: - (e.g. \(10 - 4\))
• Multiplication: * (e.g. \(4 \times 2\) is written as 4 * 2)
• Division: / (e.g. \(8 / 2\))
• Integer Floor Division: // (divides and chops off any decimal, e.g. \(7 // 2 = 3\))
• Modulus: % (finds the remainder after division, e.g. \(7 \% 2 = 1\))
Key Takeaway: Variables hold data, print() speaks to the user, input() listens to the user, and type casting with int() lets us do maths on user inputs.
Construct 1: Sequence (Step-by-Step)
Sequence means that the computer executes instructions in exact line-by-line order, from top to bottom.
Everyday Analogy: Baking a Cake
Think about following a recipe. If you bake the cake before mixing the ingredients together, your cake will be ruined! Order matters.
Example in Python:
score = 0
score = score + 10
print(score)
In this sequence, Python creates the variable score, adds \(10\) to it, and finally prints 10. If we moved line 3 to the very top, the computer would give an error because score wouldn't exist yet!
Key Takeaway: Sequence is the natural flow of a program. Changing the order of the lines changes what the program does.
---Construct 2: Selection (Making Decisions)
Selection allows a program to choose different paths of code based on whether a condition is True or False.
Everyday Analogy: The Weather
Imagine looking out the window in the morning: IF it is raining, take an umbrella. ELSE, wear sunglasses. Your brain is performing selection!
1. Comparison Operators
To check conditions, Python compares values using these symbols:
• == (Equal to): Checks if two values are equal.
• != (Not equal to): Checks if two values are different.
• > (Greater than) and < (Less than)
• >= (Greater than or equal to) and <= (Less than or equal to)
⚠️ Common Mistake: = vs ==
• A single = is for assignment (storing data into a variable: score = 10).
• A double == is for comparison (asking a question: if score == 10:).
2. Logical Operators
You can combine conditions using:
• and: Both conditions must be true.
• or: At least one condition must be true.
• not: Flips the result (True becomes False, and False becomes True).
3. The Three Types of Selection
Single-Branch Selection (if)
if score >= 50:
print("You pass!")
Two-Branch Selection (if ... else)
if score >= 50:
print("You pass!")
else:
print("Try again!")
Multi-Branch Selection (if ... elif ... else)
When you have multiple choices, use elif (short for "else if"):
if score >= 80:
print("Grade: A")
elif score >= 50:
print("Grade: B")
else:
print("Grade: C")
Nested Selection
A nested selection is simply an if statement placed inside another if statement for more specific checks.
Python Rules: Colons and Indentation
Notice the colon (:) at the end of selection lines? This tells Python a block of code is starting. The lines underneath are indented (pushed inward by 4 spaces) to show they belong inside that decision.
Key Takeaway: Selection lets programs make choices using if, elif, and else based on Boolean (True/False) conditions.
Construct 3: Iteration (Loops and Repetition)
Iteration means repeating a block of code multiple times. Instead of typing the same line \(100\) times, we write a loop!
1. Count-Controlled Iteration (Definite)
Use a count-controlled loop (a for loop) when you know in advance how many times you want the code to repeat.
Example:
for i in range(4):
print("Hello!")
⚠️ The range() Rule:
Python starts counting from \(0\). The function range(start, stop) stops at \(stop - 1\).
• range(4) generates numbers: \(0, 1, 2, 3\) (a total of \(4\) times).
• range(1, 5) generates numbers: \(1, 2, 3, 4\) (it does not include \(5\)).
2. Condition-Controlled Iteration (Indefinite)
Use a condition-controlled loop (a while loop) when you want code to keep repeating until a specific condition changes to False.
Example (Guessing Game):
secret = "python"
guess = input("Enter password: ")
while guess != secret:
print("Incorrect!")
guess = input("Try again: ")
print("Access granted!")
⚠️ Beware of Infinite Loops!
If the condition in a while loop never becomes False (for example, if the variable inside never gets updated), the loop will run forever and freeze your program.
Key Takeaway: Use for loops when you know how many times to repeat, and while loops when repeating until a condition changes.
Debugging with Trace Tables
A trace table is a tool used to track and test algorithms on paper step-by-step (called a "dry run"). It helps find logic errors by recording variable values and outputs at each line.
Trace Table Example
Let's trace this code snippet:
total = 0
for count in range(1, 4):
total = total + count
print(total)
Step-by-step Trace Table:
| Step / Line # | count |
total |
Condition Evaluated (True/False) |
Output |
|---|---|---|---|---|
| Line 1 | - | \(0\) | - | - |
| Line 2 (Loop 1) | \(1\) | \(1\) | True (\(1 < 4\)) |
- |
| Line 2 (Loop 2) | \(2\) | \(3\) | True (\(2 < 4\)) |
- |
| Line 2 (Loop 3) | \(3\) | \(6\) | True (\(3 < 4\)) |
- |
| Line 2 (End) | \(4\) | \(6\) | False (Loop ends) |
- |
| Line 4 | - | \(6\) | - | 6 |
Quick Review: Common Mistakes Checklist
Check your code for these common beginner slip-ups before running it:
1. Missing Colons: Did you put a : at the end of every if, elif, else, for, and while statement?
2. Indentation: Are your lines of code neatly indented under your loops and selection blocks?
3. Assignment vs Comparison: Did you use == to compare two things, and = only to set values?
4. Text vs Numbers: Did you wrap int() around your input() when doing calculations?