0% found this document useful (0 votes)
23 views50 pages

Day - 03 More On Conditional Statements

The document provides an introduction to programming in Python, focusing on conditional and control statements such as if, else, and while loops. It explains how to use these statements for decision-making and iteration, along with examples and syntax. Additionally, it covers advanced topics like the match-case statement and various programming challenges.

Uploaded by

Senait Desalegn
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views50 pages

Day - 03 More On Conditional Statements

The document provides an introduction to programming in Python, focusing on conditional and control statements such as if, else, and while loops. It explains how to use these statements for decision-making and iteration, along with examples and syntax. Additionally, it covers advanced topics like the match-case statement and various programming challenges.

Uploaded by

Senait Desalegn
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 50

Introduction to

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 if statement performs an action if a condition is True or skips the


action if the condition is False.

The if…else statement performs an action if a condition is True or performs a


different action if the condition is False.

The if…elif…else statement performs one of many different actions,


depending on the truth or falsity of several conditions.
Iteration Statements
▪Python provides two iteration statements—while and for:

The while statement repeats an action (or a group of actions) as long as


a condition remains True.

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!’.

NB. Indentation Matters. And the colon (:) is important.


Don’t confuse ==(equality operator) with =(assignment operator)
Voting.py
age = 19
if age >= 18:
print(“You’re old enough to vote”)

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

height = input(‘How tall are you in inches?’)


if int(height) >= 36:
print(“You’re tall enough to ride!”)
else:
print(“You’ll be able to ride when you’re a little
older”)
Check if a number is odd or even
Use Modulo Operator
even_or_odd.py

num = input(“Enter a number: ”)


if int(num) % 2 == 0:
print(str(num) + “ is even number”)
else:
print(“It’s odd number”)
if…elif…else example
grade = 77 The first condition—grade >= 90—is
if grade >= 90: False, so print('A') is skipped.
print(‘A’) The second condition—grade >= 80—
elif grade >= 80: also is False, so print('B') is
skipped.
print(‘B’)
elif grade >= 70: The third condition—grade >= 70—is
print(‘C’) True, so print('C') executes.
elif grade >= 60:
print(‘D’) Then all the remaining code in the
if…elif…else statement is skipped.
else: An if…elif…else is faster than
print(‘F’) separate if statements, because
output: C condition testing stops as soon as
a condition is True.
Indentation Matters!
x = 10
if x % 2 == 0:
print(x, ‘ is even’)
if x % 5 == 0:
print(x, ‘ is divisible by 5’)
print(‘Output only when x is divisible by both 2 & 5’)
else:
print(x, ‘is not divisible by 5’)
print(‘Output only when x is divisible by 2, not by
5’)
else:
print(x, ‘is odd’)
print(‘No Indentation. Output in all cases’)
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”)
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

How can we use an if statement to determine a person’s admission rate? Use


user input from keyboard along with an if-elif-else statement.
Python Assignment Operators (Revisited)

>>> 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)

▪Here, statement(s) may be a single statement or a block of statements. The


condition may be any expression, and true is any non-zero value. The loop
iterates while the condition is true.
▪When the condition becomes false, program control passes to the line
immediately following the loop
while loop flow diagram
i = 1
while i <= 4:
print(i)
i=i + 1
print(“Done”)

When the above code is executed, it produces:


1
2
3
4
Done
while statement
The while statement allows you to repeat one or more actions while a condition
remains True. power_of_three.py
Example: // find the first power of 3
larger than 50
i = 1
while i <= 5: num = 3
print(i) while num <= 50:
i=i+1 num = num * 3
print(“Done”) print(num)
Output:
9
27
81
while loop control flow
while <condition>:
<expression>
<expression>
...
▪<condition> evaluates to a Boolean if <condition> is True, do all the steps inside
the while code block.
▪Check <condition> again
▪Repeat until <condition> is False.
Membership Operators (Revisited)
Python's in operator lets you loop through all the members of a collection(such
as a list or a tuple) and check if there's a member in the list that's equal to the
given item.
>>> list = (1,2,3)
>>> 3 in list
Output: True

>>> 35 not in list


Output: True
Python range() function
▪The range() function returns a sequence of numbers, starting from 0 by default,
and increments by 1 (by default), and stops before a specified number.

Syntax:
range(start, stop, step)

Example: print numbers from 3 to 5

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 loop from 0 to 2, therefore running 3 times.


n = 0
for n in range(0,3):
while n < 3:
print(n)
print(n)
n = n + 1
for loop
for n in range(1,10,3): //printing with step
print(n)

for n in range(3): //same as range(0,3)


print(n)

for n in range(30,3,-2): //using negative range


print(n)
▪ for statement repeats an action (or a group of actions) for every item in a sequence of
items
▪while statement repeats an action (or a group of actions) as long as a condition
remains True
Discuss the following code: you have 3 minutes

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

▪Consider the following requirements statement:


A class of ten students took a quiz. Their grades (integers in the range 0 – 100)
are
98, 76, 71, 87, 83, 90, 57, 79, 82, 94.
Determine the class average on the quiz.
class_average.py
sum = 0 // sum of grades
counter = 0 // grade counter
grades = (98, 76, 71, 87, 83, 90, 57, 79, 82, 94)

for grade in grades:


sum = sum + grade
counter += 1
print(“Average is: “, sum/counter)
break
▪Executing a break statement in a while or for immediately exits that statement.
In the following code, range produces the integer sequence 0–99, but the loop
terminates when number is 10:

for n in range(100):
if n == 10:
break
print(n)

▪The break statement terminates the loop containing it.


▪Control of the program flows to the statement immediately after the body
of the loop
Flow chart of break statement
n = 10
while n > 0:
if n == 4:
break
print(n)
n -= 1

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: "))

op = (input("Enter operator: "))


match op:
case '+':
print(f'{num1} + {num2} = ', num1 + num2)
case '-':
print(f'{num1} - {num2} = ', num1 - num2)
case '*':
print(f'{num1} * {num2} = ', num1 * num2)
case '/':
print(f'{num1} / {num2} = ', num1 / num2)
case _:
print("Invalid")
match ---case
# First, ask the player about their CPU
cpuModel = str.lower(input("Please enter your CPU model: "))

# The match statement evaluates the variable's value


match cpuModel:
case "celeron": # We test for different values and print different messages
print ("Forget about it and play Minesweeper instead...")
case "core i3":
print ("Good luck with that ;)")
case "core i5":
print ("Yeah, you should be fine.")
case "core i7":
print ("Have fun!")
case _: # the underscore character is used as a catch-all.
print ("Is that even a thing?")
character = 'V'

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()

for i in range(n - 1, 0, -1):


for k in range(1, i + 1):
print('*', end = ' ‘)
print()
Diamond pattern
n = 5
for i in range(1, n + 1):
#print leading spaces
for j in range(n - i):
print(' ', end = ‘’)
#print asterisks
for k in range(i):
print('*', end = ' ‘)
print()

# print the bottom half


for i in range(n - 1, 0, -1):
#print leading spaces
for j in range(n - i):
print(' ', end = ‘’)
for k in range(i):
print('*', end = ' ‘)
print()
Example
n = 5
for i in range(n * 2 - 1):
# Print leading spaces
for j in range(abs(n - i - 1)):
print(' ', end=‘’)
# Print asterisks
for k in range(n - abs(n - i - 1)):
print('*', end=‘’)
print()
References
▪https://python.land/introduction-to-python
▪https://www.learnpython.org/en/Variables_and_Types
▪https://www.w3schools.com/python/default.asp

You might also like