Chapter 2: Python Basics and Control Flow
MODULE 1 | WEEK 2
Chapter 2: Python Basics and Control Flow
Now we start writing Python. In this chapter we will learn Variables, Data Types, Operators and Control Flow (Ifelse, For loop, While loop), and at the end we will do Hands-on Practice . Run every piece of code yourself in Google Colab. You cannot learn coding just by reading.
2.1 What is Python and Why?
Python is a programming language. A programming language is the language in which we give a computer instructions. Python is popular because its language is simple, like easy English, and most of the libraries for Data Science, AI and ML are built in it.
print() and comments
print("Hello, World!") # shows text on the screen
print(10 + 5) # shows the result of a calculation
print("My name is", "Rania") # several things at once
# This is a comment. Python ignores it.
# Comments are there to explain code to yourself or to others.
2.2 Variables
A variable is a named box in which we keep a value (data) so that we can use it again later by that name.
name = "Rania" # the box name holds "Rania"
age = 20 # the box age holds 20
height = 5.4 # the box height holds 5.4
is_student = True # the box is_student holds True
print(name)
print(age)
age = 21 # changed the value in the box
print(age) # now 21
Rules for Naming Variables
-
A name can start with a letter or underscore (_) , but not with a number ( 1name is wrong).
-
A name can contain only letters, numbers and underscores. Spaces or - will not work.
-
Python's special words (keywords) such as if, for, class cannot be used as names.
-
Names are case-sensitive: age and Age are different variables.
-
Good practice: use snake_case , such as student_name, total_marks .
-
Use meaningful names: write price instead of x .
Several Variables at Once, and Swapping
a, b, c = 1, 2, 3 # three variables in one line
x = y = 0 # both get 0
# Swapping the values of a and b
a, b = 10, 20
a, b = b, a
print(a, b) # 20 10
2.3 Data Types
Every value has a type (data type) . Python recognizes by itself what type a value is. We can check it with the type() function.
| Data type | Meaning | Example |
|---|---|---|
| int | Whole number (no decimal point) | 10, -5, 0, 2026 |
| float | Number with a decimal | 3.14, 99.5, -0.25 |
| str (string) | Text, inside quotes | "Ali", 'Karachi', "123" |
| bool (boolean) | Only two values: true or false | True, False |
| NoneType | Empty / no value | None |
print(type(10)) # <class 'int'>
print(type(3.14)) # <class 'float'>
print(type("Ali")) # <class 'str'>
print(type(True)) # <class 'bool'>
print(type(None)) # <class 'NoneType'>
Type Conversion (Casting)
Sometimes you have to change one type into another. For this we use int(), float(), str(), bool() .
a = int("25") # from "25" (text) to 25 (number)
b = float("3.5") # 3.5
c = str(100) # "100" (text)
d = int(7.9) # 7 (the part after the point is cut off)
print(a + 5, b + 1, c + "0", d)
print(bool(0), bool(5), bool(""), bool("hi")) # False True False True
input() and f-strings
input() asks the user to type something. Remember: the answer from input() is always a string , even if the user types a number. Use int() or float() to turn it into a number.
# When you run this in Colab, a box will appear for you to type in
name = input("What is your name? ")
age = int(input("How old are you? "))
# f-string: the easiest way to put a variable inside text
print(f"Hello {name}! Next year you will be {age + 1} years old.")
2.4 Operators
Operators are symbols that perform some operation on values.
1) Arithmetic Operators (calculations)
| Operator | Name | Example | Result |
|---|---|---|---|
| + | Addition | 7 + 3 | 10 |
| - | Minus | 7 - 3 | 4 |
| * | Multiplication | 7 * 3 | 21 |
| / | Division (always gives a float) | 7 / 2 | 3.5 |
| // | Floor division (whole part only) | 7 // 2 | 3 |
| % | Modulus (the remainder) | 7 % 2 | 1 |
| ** | Power | 2 ** 3 | 8 |
print(7 + 3, 7 - 3, 7 * 3)
print(7 / 2) # 3.5
print(7 // 2) # 3
print(7 % 2) # 1 (divide 7 by 2 and 1 is left over)
print(2 ** 3) # 8
# Use of %: even or odd
print(10 % 2) # 0 -> even
print(9 % 2) # 1 -> odd
2) Comparison Operators
These always give True or False .
| Operator | Meaning | Example | Result |
|---|---|---|---|
== | Is equal? | 5 == 5 | True |
!= | Is not equal? | 5 != 3 | True |
> | Is greater? | 5 > 8 | False |
< | Is smaller? | 5 < 8 | True |
>= | Greater or equal? | 5 >= 5 | True |
<= | Smaller or equal? | 6 <= 5 | False |
3) Logical Operators (and, or, not)
-
and: True only if both conditions are true.
-
or: True if even one of them is true.
-
not: flips it (True becomes False, False becomes True).
age = 20
has_cnic = True
print(age >= 18 and has_cnic) # True (both true)
print(age < 18 or has_cnic) # True (one true)
print(not has_cnic) # False
4) Assignment Operators
x = 10
x += 5 # x = x + 5 -> 15
x -= 3 # x = x - 3 -> 12
x *= 2 # x = x * 2 -> 24
x /= 4 # x = x / 4 -> 6.0
print(x)
5) Membership Operators (in, not in)
fruits = ["apple", "mango", "banana"]
print("mango" in fruits) # True
print("grapes" not in fruits) # True
print("a" in "Karachi") # True
Order of Operators (Precedence)
Python evaluates () first, then ****** , then *** / // %** , then + - , then comparison, then not , and , or . If in doubt, use brackets .
print(2 + 3 * 4) # 14 (3*4 first)
print((2 + 3) * 4) # 20 (the bracket first)
COMMON MISTAKES
-
Confusing = and == . = stores a value, == compares.
-
Assuming the answer of input() is a number. Always apply int() or float().
-
Treating / and // as the same. 7 / 2 = 3.5 whereas 7 // 2 = 3.
-
Directly joining text and a number: "Age: " + 20 will give an error. Use an f-string.
2.5 Control Flow: if, elif, else
Until now our code ran line by line from top to bottom. With Control Flow we teach the code to make decisions : if this condition is true, do this, otherwise do that.
marks = 72
if marks >= 80:
print("Grade A")
elif marks >= 60:
print("Grade B")
elif marks >= 40:
print("Grade C")
else:
print("Fail")
VERY IMPORTANT
In Python, indentation (moving inward, 4 spaces) is very important. The lines that are inside an if are written slightly indented. Wrong indentation gives an IndentationError . It is also necessary to put a : (colon) at the end of the if / elif / else line.
Nested if (an if inside an if)
age = 22
has_ticket = True
if age >= 18:
if has_ticket:
print("Please go in")
else:
print("Get a ticket first")
else:
print("Under age")
What Counts as 'True' for Python? (Truthy / Falsy)
The values treated as False : 0, 0.0, "" (empty text), [] (empty list), None, False . Almost everything else is treated as True .
name = ""
if name:
print("Name found")
else:
print("Name is empty") # this will run
2.6 for loop
A loop is a way of making a task happen again and again without rewriting the code. We use a for loop when we know how many times to run, or when we want to do something for every item in a collection.
for i in range(5):
print("Number:", i) # from 0 to 4 (5 is not included)
Understanding range()
| Written | Result |
|---|---|
| range(5) | 0, 1, 2, 3, 4 |
| range(1, 6) | 1, 2, 3, 4, 5 (start included, stop not included) |
| range(0, 10, 2) | 0, 2, 4, 6, 8 (steps of 2) |
| range(5, 0, -1) | 5, 4, 3, 2, 1 (backwards) |
for i in range(1, 6):
print(i)
for i in range(10, 0, -3):
print(i) # 10, 7, 4, 1
Looping over a String and a List
for ch in "Ali":
print(ch) # A, l, i
cities = ["Karachi", "Lahore", "Quetta"]
for city in cities:
print("City:", city)
break, continue, pass
-
break: stop the loop immediately.
-
continue: skip the rest of the code this time and go to the next round.
-
pass: does nothing, just fills a place.
for i in range(1, 10):
if i == 5:
break # loop ends at 5
print(i) # 1 2 3 4
for i in range(1, 6):
if i == 3:
continue # skip 3
print(i) # 1 2 4 5
Nested Loops (a loop inside a loop)
for i in range(1, 4):
for j in range(1, 4):
print(i * j, end=" ")
print() # new line
# 1 2 3
# 2 4 6
# 3 6 9
2.7 while loop
A while loop keeps running as long as a condition stays True . It is used when you do not know in advance how many times it has to run.
count = 1
while count <= 5:
print("Count:", count)
count += 1 # do not forget this line!
while True and break
total = 0
numbers = [10, 20, -1, 30] # stop when -1 comes
i = 0
while True:
n = numbers[i]
if n == -1:
break
total += n
i += 1
print("Total:", total) # 30
COMMON MISTAKES
-
Infinite loop: forgetting to increase the counter in a while, so the loop never ends. (Press the stop button in Colab.)
-
Off-by-one: range(1, 5) does not include 5. If you want 1 to 5, write range(1, 6).
-
Wrong indentation of the lines inside a loop.
-
Changing a list while looping over it in a for. This gives strange results.
2.8 Hands-on Practice
Below are 8 exercises. Try on your own first , then look at the solution. The solution is only one way; your way can be different and still correct.
Exercise 1: Even or Odd
n = 14
if n % 2 == 0:
print(n, "is even")
else:
print(n, "is odd")
Exercise 2: Grade Calculator
Give a grade for marks: 90+ A+, 80+ A, 70+ B, 60+ C, 50+ D, otherwise F.
marks = 83
if marks >= 90:
grade = "A+"
elif marks >= 80:
grade = "A"
elif marks >= 70:
grade = "B"
elif marks >= 60:
grade = "C"
elif marks >= 50:
grade = "D"
else:
grade = "F"
print("Grade:", grade)
Exercise 3: Write a Multiplication Table
n = 7
for i in range(1, 11):
print(f"{n} x {i} = {n * i}")
Exercise 4: Sum from 1 to n
n = 10
total = 0
for i in range(1, n + 1):
total += i
print("Sum:", total) # 55
Exercise 5: Factorial
5! = 5 x 4 x 3 x 2 x 1 = 120
n = 5
fact = 1
for i in range(1, n + 1):
fact *= i
print(f"{n}! =", fact)
Exercise 6: Prime number check
A prime is a number that is divisible only by 1 and itself.
n = 29
is_prime = True
if n < 2:
is_prime = False
for i in range(2, n):
if n % i == 0:
is_prime = False
break
print(n, "is prime" if is_prime else "is not prime")
Exercise 7: FizzBuzz (a famous interview question)
From 1 to 15: if the number is a multiple of 3 print Fizz, if of 5 print Buzz, if of both print FizzBuzz, otherwise print the number.
for i in range(1, 16):
if i % 15 == 0:
print("FizzBuzz")
elif i % 3 == 0:
print("Fizz")
elif i % 5 == 0:
print("Buzz")
else:
print(i)
Exercise 8: Reverse the Digits of a Number
n = 1234
rev = 0
while n > 0:
digit = n % 10 # the last digit
rev = rev * 10 + digit
n = n // 10 # remove the last digit
print("Reverse:", rev) # 4321
Challenge: Change Exercise 6 to print all the prime numbers from 1 to 50 (use a nested loop).
KEY TAKEAWAYS
-
Variable = a named box. Use snake_case names and make them meaningful.
-
Data types: int, float, str, bool, None. Check with type(), convert with int()/float()/str().
-
input() always gives a string.
-
Operators: arithmetic (+ - * / // % **), comparison, logical (and or not), assignment, membership (in).
-
if / elif / else is for making decisions. Indentation and the colon are necessary.
-
Use a for loop when the count is known, a while loop when running depends on a condition.
-
break stops the loop, continue skips this round and goes to the next.