Day - 03 More On Conditional Statements
Day - 03 More On Conditional Statements
Programming
in Python
Conditional
Statements
Senait D.
▪if---else statement
▪while statement
Objectives ▪for statement
▪break and continue
▪match ---case
Control Statements
▪Python provides 3 selection statements that execute code based on a condition
that evaluates to either True or False:
The for statement repeats an action (or a group of actions) for every item
in a sequence of items.
if Statement
>>> grade = 90
>>> if grade >= 50:
print(‘passed!’)
output: passed!
The condition grade >= 50 is True, so the indented print statement in the if’s suite
displays 'Passed!’.
age = 19
if age >= 18:
print(“You’re old enough to vote”)
else:
print(“Sorry, you’re too young.”)
if…else and if…elif…else statements
grade1.py grade2.py
grade = 40 grade = 40
if grade >= 50: if grade >= 50:
print(‘Passed!’) result = ‘Passed!’
else: else:
print(‘Failed!’) result = ‘Failed!’
print(‘Take course print(result)
again’)
output: Failed!
output:
Failed!
Take course again
if…else with user input
rollercoaster.py
x = int(input(“What’s x? ”))
y = int(input(“What’s y? ”))
if x < y :
print(“x is less than y”)
if x > y :
print(“x is greater than y”)
if x == y :
print(“x is equal to y”)
Many ifs vs. if---elif--else
x = int(input(“What’s x? ”))
y = int(input(“What’s y? ”))
if x < y :
print(“x is less than y”)
elif x > y :
print(“x is greater than y”)
elif x == y : #same as else:
print(“x is equal to y”)
Challenge 1: friendship_park.py
▪Say Freindship park in Addis charges different rates for different age groups
Admission for anyone under age 10 is free.
Admission for anyone between the ages 10 and 18 is 100 Birr
Admission for anyone age 18 or older is 300 Birr
>>> x = 5
>>> x = x + 1
>>> print(x)
output: 6
>>> x = 5
>>> x += 1 //x = x +
1
>>> print(x)
output: 6
while statement
A while loop statement repeatedly executes a target statement as long as a given
condition is true
Syntax
while expression:
statement(s)
Syntax:
range(start, stop, step)
nums = range(3,6)
for n in nums:
print(n)
for loop
▪for loops are used when you have a block of code which you want to repeat a
fixed number of times.
▪The for-loop is always used in combination with an iterable object, like a list or a
range.
for i in range(3):
for j in range(2):
print(i, j)
Sum of numbers from 1 to 10
Using while loop Using while for
n = 1 sum = 0
sum = 0 for n in range(1,11):
while n <= 10: sum += n
sum = sum + n print(sum)
n = n + 1
print(sum)
// sum += n
Output: 55
Output: 55
Challenge
class_average.py
for n in range(100):
if n == 10:
break
print(n)
Output: 10,9,8,7,6,5
//Alternative
print(n)
n -= 1
If n ==4:
break
continue
▪Executing a continue statement in a while or for loop skips the remainder of
the loop’s suite.
▪In a while, the condition is then tested to determine whether the loop should
continue executing.
In a for, the loop processes the next item in the sequence (if any)
n = -1
for n in range(10): while n <= 10:
if n == 4: n += 1
continue if n == 4:
print(n) continue
print(n)
0 1 2 3 5 6 7 8 9 0 1 2 3 5 6 7 8 9
Flow chart of continue statement
n = 10
while n > 0:
n -= 1
if n == 4:
continue
print(n)
Output: 10,9,8,7,6,5,3,2,1
match ... case statement
▪ Used to write pattern matching in Python.
▪It allows you to match a value against multiple patterns and execute
corresponding code blocks.
age.py
age = int(input("What's your age? "))
match age:
case 0:
print("You're a newborn.")
case n if n < 18:
print("You're a minor.")
case n if n >= 18 and n < 65: # 18 <= n < 65
print("You're an adult.")
case _:
print("You're a senior citizen.")
even_odd.py
num = int(input("Enter value: "))
if num % 2 == 0:
output = True
else:
output = False
match output:
case True:
print("Even.")
case _:
print("Odd.")
days.py
day = input("Enter the day: ")
match day:
case "Mon" | "Tue" | "Wed" | "Thu" | "Fri":
print("It's a weekday")
case "Sat" | "Sun":
print("It's a weekend")
case _:
print("Invalid day")
sign.py
num = int(input("Enter value: "))
match num:
case n if n < 0:
print(f"{n} is negative")
case n if n > 0:
print(f"{n} is positive")
case _:
print(f"{n} is zero")
operator.py
num1 = int(input("Enter num1: "))
num2 = int(input("Enter num2: "))
match character:
case 'A' | 'Z':
print("character is A or Z")
case 'B' | 'D':
print("character is B or D")
case 'C' | 'M':
print("character is C or M")
case _:
print("Unknown character given")
Exercises
Pyramid pattern Examples
Example
n = 5
for i in range(1, n + 1):
print('*' * i)
Right-angled Triangle Pattern using for
loop:
n = 5
for i in range(1, n + 1):
for j in range(1, i + 1):
print("*", end = ' ‘)
print()
Inverted Right-angled Triangle Pattern
using for loop:
n = 5
for i in range(n, 0, -1):
for j in range(1, i + 1):
print('*', end = ' ‘)
print()
Equilateral Triangle Pattern using for loop:
n = 5
for i in range(1, n + 1):
print(' ' * (n - i), end = ‘’)
print('* ' * i)
Example
n = 5
for i in range(1, n + 1):
for k in range(1, i + 1):
print('*', end = ' ‘)
print()