Python Prep
Your interactive study guide for the Class VII IT exam
Decision Making: if / elif / else
What is Decision Making?
In everyday life, you make decisions all the time: "If it's raining, I'll take an umbrella. Otherwise, I'll wear sunglasses."
Python lets your programs make decisions too, using if, elif (short for "else if"), and else statements.
The if Statement
The simplest form — do something only if a condition is true:
age = 15
if age >= 13:
print("You are a teenager!")
The if...else Statement
When you want to do one thing if a condition is true, and something else if it's false:
marks = 35
if marks >= 40:
print("Pass")
else:
print("Fail")
The if...elif...else Statement
When there are multiple conditions to check — Python tests them one by one, top to bottom, and runs the first one that's true:
marks = 75
if marks >= 90:
print("Grade: A")
elif marks >= 70:
print("Grade: B")
elif marks >= 50:
print("Grade: C")
else:
print("Grade: F")
elif is short for "else if". You can have as many elif blocks as you need, but only one else at the end.
How it Works — Flowchart
Here's how Python decides which block to run:
Step-by-Step: Trace Through an if/elif/else
Let's trace this code line by line:
temperature = 28
if temperature >= 35:
print("It's very hot!")
elif temperature >= 25:
print("It's warm.")
else:
print("It's cool.")
We start with temperature = 28. Python will check conditions top to bottom.
Check: Is 28 >= 35?
28 is NOT greater than or equal to 35, so this is False.
Python skips the if block and moves to elif.
Check: Is 28 >= 25?
28 IS greater than or equal to 25, so this is True!
Python runs this block and prints "It's warm."
Since the elif was True, Python skips the else entirely. It never even looks at it.
Practice Time!
What does this code print?
x = 5
if x > 3:
print("A")
elif x > 4:
print("B")
else:
print("C")
What keyword is used to check additional conditions after an if?
Every if, elif, and else line must end with what character?
Write a program that checks if the variable num is positive, negative, or zero. For num = 7, it should print "Positive".
Loops: for & range()
Why Loops?
Imagine you want to print "Hello" 100 times. Writing print("Hello") 100 times would be crazy! A for loop lets you repeat code as many times as you want.
The for Loop
A for loop goes through a sequence of values one by one:
for i in [1, 2, 3]:
print(i)
The range() Function
Instead of writing out a list of numbers, range() generates them for you. It has three forms:
| Syntax | What it generates | Example |
|---|---|---|
range(stop) |
0, 1, 2, ..., stop-1 | range(5) → 0, 1, 2, 3, 4 |
range(start, stop) |
start, start+1, ..., stop-1 | range(2, 6) → 2, 3, 4, 5 |
range(start, stop, step) |
start, start+step, ... | range(0, 10, 2) → 0, 2, 4, 6, 8 |
range() never includes the stop value! range(1, 5) gives you 1, 2, 3, 4 — not 5.
Visualizing range(1, 6)
Common Patterns
total = 0
for i in range(1, 6):
total += i
print(total)
for i in range(5, 0, -1):
print(i)
for i in range(0, 11, 2):
print(i, end=" ")
Step-by-Step: How a for Loop Executes
Let's trace this loop iteration by iteration:
total = 0
for i in range(1, 4):
total += i
print("i =", i, "total =", total)
Before the loop starts: total = 0. The range(1, 4) will produce: 1, 2, 3.
Iteration 1: i = 1
total = 0 + 1 = 1
Prints: i = 1 total = 1
Iteration 2: i = 2
total = 1 + 2 = 3
Prints: i = 2 total = 3
Iteration 3: i = 3
total = 3 + 3 = 6
Prints: i = 3 total = 6
Loop ends. range(1, 4) has no more values. Final total = 6.
i takes each value from range one at a time. The body runs once per value. After the last value, the loop stops.
Practice Time!
What does range(20, 1, -3) produce?
The ________() function generates a sequence of numbers.
Write a program that prints the multiplication table of 5 (from 1 to 10). Each line should look like: 5 x 1 = 5
Print a right triangle of stars with 5 rows:
*
**
***
****
*****
Built-in Functions
What are Built-in Functions?
Built-in functions are like tools in a toolbox — Python provides them ready to use, no installation needed. You've already been using print() and range()!
These are different from functions you write yourself. They're part of Python's standard library.
len(), max(), min(), sum(), print(), and input() are all standard library functions.
Quick Reference
| Function | What it does | Example | Result |
|---|---|---|---|
print() |
Displays output on screen | print("Hi") |
Hi |
input() |
Gets text from the user | name = input("Name? ") |
Waits for typing |
len() |
Counts items or characters | len("Hello") |
5 |
max() |
Returns the largest value | max(3, 7, 1) |
7 |
min() |
Returns the smallest value | min(3, 7, 1) |
1 |
sum() |
Adds up all items in a list | sum([1, 2, 3]) |
6 |
len() — Count things
len() returns the number of items in a sequence (string, list, etc.):
word = "Python"
print(len(word)) # 6 characters
numbers = [10, 20, 30]
print(len(numbers)) # 3 items
len() is a standard library function, not a method. You call it as len(x), not x.len().
max() and min() — Find extremes
These find the largest and smallest values:
scores = [85, 92, 78, 95, 88]
print("Highest:", max(scores))
print("Lowest:", min(scores))
You can also pass values directly: max(5, 10, 3) returns 10.
sum() — Add it all up
sum() adds all the numbers in a list (or any sequence):
prices = [10, 25, 15, 30]
print("Total:", sum(prices))
sum() needs a list — sum([1, 2, 3]) works, but sum(1, 2, 3) does NOT.
input() — Get user input
input() pauses the program and waits for the user to type something:
name = input("What is your name? ")
print("Hello,", name)
input() always returns a string. If you need a number, convert it: age = int(input("Age? "))
Step-by-Step: Using Built-in Functions Together
Let's say we have a list of test scores and want to analyze them:
scores = [72, 85, 91, 68, 77]
We have 5 scores. Let's use built-in functions to learn about them.
len(scores) counts the items → 5
max(scores) finds the largest → 91
min(scores) finds the smallest → 68
sum(scores) adds them all → 393
We can even combine them to calculate an average:
average = sum(scores) / len(scores)
print(average) # 393 / 5 = 78.6
sum() gives the total, len() gives the count. Divide to get the average!
sum()/len() for averages, max()-min() for range. You don't need to write loops for these — Python does it for you!
Practice Time!
What does len("OpenAI") return?
What does sum([10, 20, 30]) return?
Given the list scores = [85, 42, 95, 67, 48], use built-in functions to print:
- The maximum value (as
Max: 95) - The minimum value (as
Min: 42) - The number of items (as
Total: 5) - The sum (as
Sum: 337)
String Methods: upper(), lower(), replace()
What are String Methods?
Strings (text) in Python come with built-in methods — special powers you can use to transform text. Unlike functions like len(), methods are called on the string using a dot:
# Function — called with the string inside parentheses
len("hello") # → 5
# Method — called ON the string with a dot
"hello".upper() # → "HELLO"
.upper() — Convert to UPPERCASE
Returns a new string with all letters converted to uppercase:
word = "Python standard library"
print(word.upper())
.lower() — Convert to lowercase
Returns a new string with all letters in lowercase:
name = "JOHN DOE"
print(name.lower())
.replace() — Swap text
Replaces all occurrences of one substring with another:
sentence = "I love cats. Cats are great."
new_sentence = sentence.replace("cats", "dogs")
print(new_sentence)
replace() is case-sensitive! "Cats" (capital C) was not replaced because we searched for "cats" (lowercase c).
Chaining Methods
You can chain multiple methods together:
text = "Hello World"
print(text.upper().replace("WORLD", "PYTHON"))
String Transformation Flow
Step-by-Step: String Transformations
Let's start with a string and transform it step by step:
msg = "Hello, World!"
Our original string is: "Hello, World!" (13 characters)
Apply .upper():
print(msg.upper()) # "HELLO, WORLD!"
Every letter becomes uppercase. Numbers, spaces, and punctuation stay the same.
Important: msg itself is still "Hello, World!" — the original doesn't change!
Apply .replace("World", "Python"):
print(msg.replace("World", "Python"))
# "Hello, Python!"
It found "World" and swapped it with "Python". Case must match exactly!
Chain them together:
print(msg.lower().replace("world", "python"))
# "hello, python!"
. connects one result to the next method — like a pipeline!
Practice Time!
What does this code print?
word = "Python standard library"
print(word.upper())
print(word.lower())
print(len(word))
To swap "cat" with "dog" in a string, use the _________() method.
Given text = "Hello Python World", print three lines:
- The text in all uppercase
- The text in all lowercase
- The text with "Python" replaced by "Earth"
Boolean Logic: and, or
What are Booleans?
A Boolean is a value that is either True or False. Every time you write a condition like x > 5, Python evaluates it to a Boolean.
print(5 > 3) # True
print(5 == 3) # False
print(10 <= 10) # True
Combining Conditions with and
and means both conditions must be true. Think of it like: "You can ride the roller coaster if you are tall enough AND old enough."
age = 15
height = 160
if age >= 12 and height >= 150:
print("You can ride!")
else:
print("Sorry, not allowed.")
Truth Table for and
| A | B | A and B |
|---|---|---|
| True | True | True |
| True | False | False |
| False | True | False |
| False | False | False |
and returns True only when both sides are True.
Combining Conditions with or
or means at least one condition must be true. Think: "You get a discount if you are a student OR a senior citizen."
is_student = True
is_senior = False
if is_student or is_senior:
print("You get a discount!")
else:
print("Regular price.")
Truth Table for or
| A | B | A or B |
|---|---|---|
| True | True | True |
| True | False | True |
| False | True | True |
| False | False | False |
or returns True when at least one side is True. It's only False when both are False.
Using and / or with if
A practical exam-style example:
x = True
y = False
if x and y:
print("Both x and y are True")
else:
print("x is False or y is False or both x and y are False")
x is True but y is False. Since and requires both to be True, the condition is False, so the else block runs.
Step-by-Step: Evaluating Boolean Expressions
Let's evaluate this code step by step:
age = 16
has_ticket = True
is_vip = False
if (age >= 18 and has_ticket) or is_vip:
print("Welcome to the concert!")
else:
print("Sorry, you can't enter.")
The condition has both and and or. Let's break it down.
First, evaluate the and part (and is checked before or):
age >= 18 → 16 >= 18 → False
False and True → False
Since the left side of and is False, the whole and is False — Python doesn't even check has_ticket!
Now evaluate the or part:
False or is_vip → False or False → False
The whole condition is False, so the else block runs.
Output: Sorry, you can't enter.
What would change the result?
- If
age = 18: theandbecomes True, so they get in - If
is_vip = True: theorbecomes True, so they get in (even though they're underage!)
and is checked before or. Use parentheses to make your intent clear. Think of and as stricter (both must be true) and or as more lenient (one is enough).
Practice Time!
What does True and False evaluate to?
What does False or True evaluate to?
Write a program that checks if a person is eligible to vote. They need to be 18 or older AND a citizen. Use the variables below — it should print "Eligible".
Binary Number Addition
What is Binary?
We normally count in decimal (base 10) using digits 0–9. Computers count in binary (base 2) using only two digits: 0 and 1.
Each binary digit is called a bit. Here's how binary numbers map to decimal:
| Binary | Decimal | How? |
|---|---|---|
0 | 0 | 0 |
1 | 1 | 1 |
10 | 2 | 1×2 + 0×1 |
11 | 3 | 1×2 + 1×1 |
100 | 4 | 1×4 + 0×2 + 0×1 |
101 | 5 | 1×4 + 0×2 + 1×1 |
110 | 6 | 1×4 + 1×2 + 0×1 |
111 | 7 | 1×4 + 1×2 + 1×1 |
1000 | 8 | 1×8 + 0×4 + 0×2 + 0×1 |
Binary Addition Rules
Binary addition is just like decimal addition, but simpler — there are only 4 rules:
| Operation | Result | Carry |
|---|---|---|
0 + 0 | 0 | No carry |
0 + 1 | 1 | No carry |
1 + 0 | 1 | No carry |
1 + 1 | 0 | Carry 1 to next column |
1 + 1 + 1 (when there's a carry) = 1 with carry 1. Think of it as: 1+1=10, plus 1 more = 11. So result bit is 1, carry is 1.
Worked Example: 1011 + 1101
Let's add step by step, from right to left (just like decimal addition):
| 1 | 1 | 1 | ← carry | ||
| 1 | 0 | 1 | 1 | = 11 | |
| + | 1 | 1 | 0 | 1 | = 13 |
| 1 | 1 | 0 | 0 | 0 | = 24 |
Step by step:
- Column 1 (rightmost): 1 + 1 = 0, carry 1
- Column 2: 1 + 0 + carry 1 = 0, carry 1
- Column 3: 0 + 1 + carry 1 = 0, carry 1
- Column 4: 1 + 1 + carry 1 = 1, carry 1
- Column 5: carry 1 = 1
Result: 11000 (which is 24 in decimal: 11 + 13 = 24 ✓)
Another Example: 1010 + 0111
| 1 | 1 | 1 | ← carry | ||
| 1 | 0 | 1 | 0 | = 10 | |
| + | 0 | 1 | 1 | 1 | = 7 |
| 1 | 0 | 0 | 0 | 1 | = 17 |
Step-by-Step: Binary Addition (0110 + 0111)
Let's add 0110 (6 in decimal) + 0111 (7 in decimal).
Just like decimal addition, we start from the rightmost column and work left.
0 1 1 0
+ 0 1 1 1
---------
? ? ? ?
Column 1 (rightmost): 0 + 1 = 1
No carry. Easy!
0 1 1 0
+ 0 1 1 1
---------
1
Column 2: 1 + 1 = 10 in binary
Write down 0, carry 1 to the next column.
1 ← carry
0 1 1 0
+ 0 1 1 1
---------
0 1
Column 3: 1 + 1 + carry 1 = 11 in binary
Write down 1, carry 1.
Column 4: 0 + 0 + carry 1 = 1
1 1 ← carries
0 1 1 0
+ 0 1 1 1
---------
1 1 0 1
Answer: 1101 in binary = 13 in decimal.
Let's verify: 6 + 7 = 13. Correct!
Practice Time!
Solve: 1100 + 1010
Enter the result (5 bits, left to right):
Solve: 1111 + 0001
Enter the result (5 bits, left to right):
Solve: 10110 + 01101
Enter the result (6 bits, left to right):
What is 1 + 1 in binary?