๐ Loops & Conditions
Control the flow of your Python programs
๐บ๏ธ What You'll Learn
๐ Same topic in the course notebook
Session_3 Loops and Conditions has the same ideas: if/elif/else, for, while, break, continue. Run the notebook cells to practice.
Think of It Like Driving!
Conditions check situations, loops repeat actions!
๐ Comparison Operators
โ๏ธ Comparing Values
Comparison operators compare two values and return True or False. They're the foundation of decision-making in code!
๐ฏ All Comparison Operators
| Operator | Meaning | Example | Result |
|---|---|---|---|
== |
Equal to | 5 == 5 | True |
!= |
Not equal to | 5 != 3 | True |
> |
Greater than | 7 > 3 | True |
< |
Less than | 2 < 5 | True |
>= |
Greater than or equal | 5 >= 5 | True |
<= |
Less than or equal | 3 <= 5 | True |
# Comparison operators from Session 3
a = 10
b = 5
# Equal and not equal
print(a == b) # False (10 is not equal to 5)
print(a != b) # True (10 is not equal to 5)
# Greater and less than
print(a > b) # True (10 is greater than 5)
print(a < b) # False (10 is not less than 5)
# Greater/less than or equal
print(a >= 10) # True (10 is equal to 10)
print(b <= 5) # True (5 is equal to 5)
False True True False True True
= is for assignment: x = 5 (put 5 in x)
== is for comparison: x == 5 (is x equal to 5?)
๐ง Logical Operators
๐ Combining Conditions
Logical operators let you combine multiple conditions together!
๐ฏ The Three Logical Operators
AND ๐ค โ Both conditions must be True
"I need coffee AND breakfast"
OR ๐คท โ At least one condition must be True
"I'll have tea OR coffee"
NOT ๐ซ โ Flips True to False, False to True
"I do NOT want spam"
# Logical operators from Session 3
age = 25
has_license = True
is_tired = False
# AND - Both must be True
can_drive = age >= 18 and has_license
print("Can drive:", can_drive) # True
# OR - At least one must be True
needs_rest = is_tired or age > 60
print("Needs rest:", needs_rest) # False
# NOT - Reverses the boolean
is_awake = not is_tired
print("Is awake:", is_awake) # True
# Complex combinations
x = 15
print(x > 10 and x < 20) # True (x is between 10 and 20)
print(x < 5 or x > 10) # True (x is greater than 10)
Can drive: True Needs rest: False Is awake: True True True
๐ค Conditional Statements (if/elif/else)
๐ฆ The if Statement
The if statement runs code only when a condition is True. It's like a guard at a door!
๐ช How IF Works
START
โ
โผ
โโโโโโโโโโโโโโโโโ
โ Condition โ
โ True? โ
โโโโโโโโโฌโโโโโโโโ
Yes โ No
โผ โฒ
โโโโโโโโโโโโโ โฒ
โ Run Code โ โ
โโโโโโโโโโโโโ โ
โ โ
โผ โ
END
# Simple if statement from Session 3
temperature = 35
if temperature > 30:
print("It's hot outside! ๐ฅ")
print("Stay hydrated!")
# This code runs regardless of the condition
print("Have a nice day!")
It's hot outside! ๐ฅ Stay hydrated! Have a nice day!
Python uses indentation (spaces/tabs) to group code. Everything indented after if belongs to that if block. Use 4 spaces consistently!
โ๏ธ The if-else Statement
The else block runs when the if condition is False. It's the "otherwise" option!
๐ The Fork in the Road
Is it raining? ๐ง๏ธ
โ
โโโโYesโโดโโโNoโโโโ
โผ โผ
Take umbrella โ๏ธ Wear sunglasses ๐
# if-else from Session 3
age = 16
if age >= 18:
print("You can vote! ๐ณ๏ธ")
else:
print("Sorry, you're too young to vote.")
years_left = 18 - age
print(f"Wait {years_left} more years.")
Sorry, you're too young to vote. Wait 2 more years.
๐ข The if-elif-else Chain
When you have multiple conditions to check, use elif (short for "else if"). Python checks each condition in order and runs the first one that's True!
๐ข The Decision Waterfall
score = 85
โ
โโโโโโผโโโโโ
โ >= 90? โโโYesโโโ "A" ๐
โโโโโโฌโโโโโ
โ No
โโโโโโผโโโโโ
โ >= 80? โโโYesโโโ "B" โจ โ (This runs!)
โโโโโโฌโโโโโ
โ No
โโโโโโผโโโโโ
โ >= 70? โโโYesโโโ "C" ๐
โโโโโโฌโโโโโ
โ No
โผ
"F" ๐ข
# Grade calculator from Session 3
score = 85
if score >= 90:
grade = "A"
print("Excellent! ๐")
elif score >= 80:
grade = "B"
print("Good job! โจ")
elif score >= 70:
grade = "C"
print("Not bad! ๐")
elif score >= 60:
grade = "D"
print("Need improvement ๐")
else:
grade = "F"
print("Please see the teacher ๐ข")
print(f"Your grade: {grade}")
Good job! โจ Your grade: B
๐ช Nested if Statements
You can put if statements inside other if statements - like Russian nesting dolls!
# Nested if from Session 3
age = 25
has_ticket = True
is_vip = False
if age >= 18:
print("Age verified โ")
if has_ticket:
print("Ticket verified โ")
if is_vip:
print("Welcome to the VIP section! ๐")
else:
print("Welcome to the general section! ๐")
else:
print("Please buy a ticket first ๐ซ")
else:
print("Sorry, this event is for adults only ๐")
Age verified โ Ticket verified โ Welcome to the general section! ๐
๐ For Loops
๐ Iterating Through Items
A for loop repeats code for each item in a sequence. Think of it like a assembly line in a factory - each item gets processed!
๐ญ The For Loop Assembly Line
Items: [๐, ๐, ๐, ๐]
โ โ โ โ
โผ โผ โผ โผ
โโโโโโโโโโโโโโโ
โ Process โ โ Same operation
โ Each Item โ on each item
โโโโโโโโโโโโโโโ
โ โ โ โ
โผ โผ โผ โผ
Output: ๐โ ๐โ ๐โ ๐โ
# Basic for loop from Session 3
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(f"I love {fruit}s! ๐ฝ๏ธ")
I love apples! ๐ฝ๏ธ I love bananas! ๐ฝ๏ธ I love cherrys! ๐ฝ๏ธ
๐ค Looping Through Strings
# Loop through each character
word = "Python"
for letter in word:
print(letter, end=" โ ")
print("Done!")
P โ y โ t โ h โ o โ n โ Done!
๐ฏ The range() Function
range() generates a sequence of numbers. It's perfect when you want to loop a specific number of times!
๐ข Understanding range()
range(5) โ 0, 1, 2, 3, 4 (starts at 0, stops BEFORE 5)
range(2, 6) โ 2, 3, 4, 5 (starts at 2, stops BEFORE 6)
range(0, 10, 2) โ 0, 2, 4, 6, 8 (step by 2)
range(5, 0, -1) โ 5, 4, 3, 2, 1 (countdown!)
๐ฏ Remember: The end number is NOT included!
# range() examples from Session 3
# Basic range - prints 0 to 4
print("range(5):")
for i in range(5):
print(i, end=" ")
print()
# Range with start and end
print("range(2, 7):")
for i in range(2, 7):
print(i, end=" ")
print()
# Range with step
print("range(0, 10, 2) - even numbers:")
for i in range(0, 10, 2):
print(i, end=" ")
print()
# Countdown
print("Countdown:")
for i in range(5, 0, -1):
print(i, end="... ")
print("Blast off! ๐")
range(5): 0 1 2 3 4 range(2, 7): 2 3 4 5 6 range(0, 10, 2) - even numbers: 0 2 4 6 8 Countdown: 5... 4... 3... 2... 1... Blast off! ๐
๐ Practical Example: Sum of Numbers
# Calculate sum of 1 to 10
total = 0
for num in range(1, 11): # 1 to 10
total = total + num
print(f"Added {num}, total is now {total}")
print(f"\\nFinal sum: {total}")
Added 1, total is now 1 Added 2, total is now 3 Added 3, total is now 6 ... Final sum: 55
โพ๏ธ While Loops
๐ Repeat While Condition is True
A while loop keeps running as long as a condition is True. It's like saying "keep doing this until..."
๐ก The While Loop Ferris Wheel
โโโโโโโโโโโโโโโโโโโ
โ Is condition โโโโโโโโ
โ True? โ โ
โโโโโโโโโโฌโโโโโโโโโ โ
โ โ
Yes โ No โ
โผ โ
โโโโโโโโโโโโโโโโโโโ โ
โ Run the code โโโโโโโโ
โโโโโโโโโโโโโโโโโโโ
โ
โ No
โผ
EXIT
# Basic while loop from Session 3
count = 1
while count <= 5:
print(f"Count is: {count}")
count = count + 1 # IMPORTANT: Update the condition!
print("Loop finished!")
Count is: 1 Count is: 2 Count is: 3 Count is: 4 Count is: 5 Loop finished!
Always make sure your condition will eventually become False, otherwise your program will run forever!
while True: # This runs FOREVER! โพ๏ธ
๐ฎ Practical Example: Guessing Game
# Simulated guessing game from Session 3
secret = 7
guess = 0
attempts = 0
guesses = [3, 5, 7] # Simulated user guesses
while guess != secret:
guess = guesses[attempts]
attempts = attempts + 1
if guess < secret:
print(f"Guess {guess}: Too low! โฌ๏ธ")
elif guess > secret:
print(f"Guess {guess}: Too high! โฌ๏ธ")
print(f"๐ Correct! The number was {secret}")
print(f"You got it in {attempts} attempts!")
Guess 3: Too low! โฌ๏ธ Guess 5: Too low! โฌ๏ธ ๐ Correct! The number was 7 You got it in 3 attempts!
โน๏ธ Loop Control Statements
๐ break, continue, and pass
These special keywords give you more control over how loops behave!
๐ฎ Loop Control Remote
๐ break โ STOP the loop completely
(Emergency exit!)
โญ๏ธ continue โ SKIP to next iteration
(Skip this one, do the next)
โธ๏ธ pass โ Do NOTHING
(Placeholder, move along)
๐ The break Statement
# break example from Session 3
# Find the first number divisible by both 3 and 7
for num in range(1, 100):
if num % 3 == 0 and num % 7 == 0:
print(f"Found it: {num}")
break # Exit the loop immediately
print(f"Checking {num}...")
print("Search complete!")
Checking 1... Checking 2... ... Checking 20... Found it: 21 Search complete!
โญ๏ธ The continue Statement
# continue example from Session 3
# Print only odd numbers
print("Odd numbers from 1-10:")
for num in range(1, 11):
if num % 2 == 0: # If even
continue # Skip this iteration
print(num, end=" ")
Odd numbers from 1-10: 1 3 5 7 9
โธ๏ธ The pass Statement
# pass example from Session 3
# Use pass as a placeholder
for i in range(5):
if i == 2:
pass # TODO: Handle this case later
else:
print(f"Processing {i}")
# pass is useful for empty functions too
def future_feature():
pass # Will implement later
Processing 0 Processing 1 Processing 3 Processing 4
๐ช Nested Loops
๐๐ Loops Inside Loops
You can put a loop inside another loop! The inner loop runs completely for each iteration of the outer loop.
๐ฆ Nested Loops = Rows and Columns
Outer loop (rows): i = 1, 2, 3
โ
โโโโโโโโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโโโโโโโ
โ โ โ
โผ โผ โผ
Inner loop: j = 1,2,3 j = 1,2,3
(columns) for i=1 for i=2
Result: (1,1) (1,2) (1,3) โ (2,1) (2,2) (2,3) โ ...
# Nested loops from Session 3
# Multiplication table
for i in range(1, 4): # Outer loop: 1, 2, 3
for j in range(1, 4): # Inner loop: 1, 2, 3
product = i * j
print(f"{i} ร {j} = {product}", end="\\t")
print() # New line after each row
1 ร 1 = 1 1 ร 2 = 2 1 ร 3 = 3 2 ร 1 = 2 2 ร 2 = 4 2 ร 3 = 6 3 ร 1 = 3 3 ร 2 = 6 3 ร 3 = 9
โญ Creating a Pattern
# Star pattern from Session 3
rows = 5
for i in range(1, rows + 1):
for j in range(i):
print("โญ", end="")
print() # New line
โญ โญโญ โญโญโญ โญโญโญโญ โญโญโญโญโญ
๐ฏ Practical Examples
๐ผ Real-World Applications
๐ข FizzBuzz Challenge
# Classic FizzBuzz from Session 3
for num in range(1, 16):
if num % 3 == 0 and num % 5 == 0:
print("FizzBuzz")
elif num % 3 == 0:
print("Fizz")
elif num % 5 == 0:
print("Buzz")
else:
print(num)
๐ Finding Prime Numbers
# Check for prime numbers from Session 3
for num in range(2, 20):
is_prime = True
for divisor in range(2, num):
if num % divisor == 0:
is_prime = False
break
if is_prime:
print(f"{num} is prime! โญ")
2 is prime! โญ 3 is prime! โญ 5 is prime! โญ 7 is prime! โญ 11 is prime! โญ 13 is prime! โญ 17 is prime! โญ 19 is prime! โญ
๐ซ Common Mistakes (Loops & Conditions)
- Using = instead of == in conditions โ
if x = 5assigns and is wrong; useif x == 5to compare. - Infinite while loop โ Make sure the condition can become False; update the variable you're checking (e.g. increment a counter).
- Forgetting the colon after if/for/while โ Python requires a colon and then an indented block; no curly braces.
๐ญ Short reflection
In one sentence: when would you choose a while loop instead of a for loop?
โ CORE (Must know)
- if / elif / else; comparison and logical operators.
- for:
for x in sequence,range(); while: repeat until condition false. - break (exit loop), continue (skip to next iteration).
๐ NON-CORE (Good to know)
- else on loops; enumerate(); nested loops.
๐ Session Summary
| Concept | Syntax | Use When |
|---|---|---|
if |
if condition: | Run code only if condition is True |
elif |
elif condition: | Check another condition if previous was False |
else |
else: | Run if all previous conditions are False |
for |
for item in sequence: | Iterate through each item |
while |
while condition: | Repeat until condition becomes False |
range() |
range(start, stop, step) | Generate number sequences |
break |
break | Exit loop immediately |
continue |
continue | Skip to next iteration |
Complete code from course notebook: 3_loops_and_conditions_(1) (1).ipynb
Every line of code from the course notebook (verbatim).
# --- Code cell 1 ---
---last session
1.data types--numerical data types
2.Type casting
# --- Code cell 5 ---
11//3
# --- Code cell 6 ---
11%3
# --- Code cell 7 ---
4**3
# --- Code cell 8 ---
# '**' : Exponentiation/power โ 2 ** 3 = 8
# --- Code cell 9 ---
56/3
# --- Code cell 10 ---
56//3
# --- Code cell 11 ---
d=344%33
d
# --- Code cell 12 ---
3**4
# --- Code cell 13 ---
# Boolean data types are just True or False
# --- Code cell 15 ---
a==5
# --- Code cell 16 ---
#= ------is assiging a value
#== ------to equal a value
# --- Code cell 17 ---
t=4
# --- Code cell 18 ---
3!=t
# --- Code cell 19 ---
t>=4
# --- Code cell 21 ---
a=12
a=a+6 #a+=6
a
# --- Code cell 22 ---
t=23
t*=2 # t=t*2
t
# --- Code cell 23 ---
r=56
r-=30 #r=r-30
r
# --- Code cell 25 ---
(55>31) & (100>14) # and
# --- Code cell 26 ---
(55>31) | (10>14) # or
# --- Code cell 27 ---
not (5>50)
# --- Code cell 28 ---
x=True
y=False
print(not y) # not
# --- Code cell 29 ---
(5 > 10)
# --- Code cell 31 ---
# Example 1: Using 'is'
x = [1, 2, 3]
y = [3,4,5]
z = y
print(x is y) # True โ y refers to the same object as x
print(y is z) # False โ z has the same content, but is a different object
# Example 2: Using 'is not'
#print(x is not z) # True
# --- Code cell 32 ---
id(x)
# --- Code cell 33 ---
id(y)
# --- Code cell 34 ---
id(z)
# --- Code cell 36 ---
d=[3,4,5,6]
3 not in d
# --- Code cell 37 ---
d.index(6)
# --- Code cell 41 ---
if condition:
Block of code # space called as indendation
# --- Code cell 42 ---
x = 1
if x > 5:
print("x is greater than 5")
# --- Code cell 44 ---
x = 3
if x > 5:
print("x is greater than 5")
else:
print("x is not greater than 5")
# --- Code cell 46 ---
x =3
if x > 5:
print("x is greater than 5")
elif x == 5:
print("x is equal to 5")
else:
print("x is less than 5")
# --- Code cell 47 ---
x = 283
y = 410
if x > y: # False
print("b is greater than a")
else:
print("anything")
# --- Code cell 48 ---
x = 2835
y = 283
if x == y: # True
x = x + 1
print(x)
else:
print("anything")
# --- Code cell 50 ---
#indentation
x = 283
y = 410
if x > y:#False
print("b is greater than a")
# --- Code cell 51 ---
x = 601
y = 610
if x > y:
print("x is greater than y")
elif x == y:
print("x is equal to y")
else:
print("y is greater than x")
# --- Code cell 53 ---
x = 136
y = 228
z = 532
if z > y & y > x:
print("Both conditions are True. x is smallest number")
else:
print("anything")
# --- Code cell 54 ---
x = 136
y = 228
z = 132
if ( z > y and y > x ) | z>x: # You can add brackets for deciding order of execution
print("Both conditions are True. x is smallest number")
x = x + 1
print(x)
# --- Code cell 56 ---
x = 136
y = 228
z = 532
if z > y and y > x and z>x: # Multiple conditions
print("All conditions are True. x is smallest number")
# --- Code cell 57 ---
x = 136
y = 228
z = 532
if z < y or y < x:# False
print("Atleast one condition is True")
# --- Code cell 58 ---
x = 136
y = 228
z = 532
if (z > y or y < x) and z>=x:
print("Both condition are True")
# --- Code cell 59 ---
x = 136
y = 228
z = 532
if z > y or y < x and z>=x: # order of conditions is important - left to right execution
print("Both condition are True")
# --- Code cell 60 ---
x = 136
y = 228
z = 532
if z > y and y < x or z<=x: # order of conditions is important - left to right execution
print("Both condition are True")
# --- Code cell 61 ---
x = 1366
y = 228
if not x > y: # x<y
print("x is NOT greater than y")
# --- Code cell 64 ---
x = 136
y = 228
if not x > y: #any condition
# --- Code cell 65 ---
x = 136
y = 228
if not x > y: #any condition
pass # PASS wont work in capitals
# --- Code cell 68 ---
for variable in iterable:
block of code
# --- Code cell 69 ---
name="aravind"
for i in range(10):
print(name)
# --- Code cell 70 ---
student_marks = [85, 88, 67, 65, 88, 99, 49, 100,111]
for x in student_marks:
print(x)
# --- Code cell 71 ---
college_name = "New College Name!"
for aravind in college_name:
print(aravind)
# --- Code cell 72 ---
college_name = "New College Name"
college_name[3]
# --- Code cell 75 ---
student_marks = [85, 88, 67, 65, 88, 99, 49, 100]
for z in student_marks:
print(z)
if(z==99):
print('loop broke at z=', z)
break
# --- Code cell 77 ---
student_marks = [85, 88, 67, 65, 88, 99, 49, 100]
for z in student_marks:
if(z>90):
print("hello")
continue
print(z)
# --- Code cell 78 ---
student_marks = [85, 88, 67, 65, 88, 99, 49, 100]
for z in student_marks:
if(z>90):
pass
print(z)
# --- Code cell 79 ---
student_marks = [85, 88, 67, 65, 88, 99, 49, 100]
for z in student_marks:
if(z<120):
break
print(z)
# --- Code cell 82 ---
list(range(0,12,1))
# --- Code cell 83 ---
for k in range(10):
print(k)
# --- Code cell 84 ---
## range(start_number, end_number, increment_size)
for k in range(0,21,2):
print(k)
# --- Code cell 85 ---
#nested loops
# --- Code cell 86 ---
student_marks = [85, 88, 67, 65, 88, 99, 49, 100]
number = [1,2,3,4,5]
for i in student_marks:
for j in number:
print(i, j)
# --- Code cell 87 ---
data = [1, 2, 3, 4, 2.5]
# write a code such that it prints values less than 3
# --- Code cell 88 ---
for i in data:
if (i<3):
print(i)
# --- Code cell 89 ---
student_marks = [85, 88, 67, 65, 88, 99, 49, 100]
len(student_marks)
# --- Code cell 90 ---
range(8)
# --- Code cell 91 ---
for i in range(len(student_marks)):
print(i)
print(student_marks[i])
# --- Code cell 92 ---
student_marks = [85, 88, 67, 65, 88, 99, 49, 100]
number = [1,2,3,4,5]
for i in range(len(student_marks)):
for j in range(len(number)):
print(student_marks[i], number[j])
# --- Code cell 93 ---
len(student_marks)
# --- Code cell 94 ---
for x in student_marks:
# --- Code cell 95 ---
for x in student_marks:
pass
# --- Code cell 97 ---
student_marks = [85, 88, 67, 65, 88, 99, 49, 100]
# --- Code cell 98 ---
student_marks[0]
# --- Code cell 99 ---
len(student_marks)
# --- Code cell 100 ---
student_marks = [85, 88, 67, 65, 88, 99, 49, 100]
i = 1
while i < len(student_marks):
print(student_marks[i])
i = i+1
# --- Code cell 101 ---
count =6 # initalize a variable
while count <= 10: #conditional check
print(count)
count += 1 # increase count by 1 each time
# --- Code cell 102 ---
len(student_marks)
# --- Code cell 103 ---
student_marks = [85, 88, 67, 65, 88, 99, 49, 100]
i = 0
while i < 4:
print(student_marks[i])
print("value of i", i)
i = i+1