0% found this document useful (0 votes)
6 views35 pages

Python Lesson 4 - Control Structures

This document provides an overview of control structures in Python, including conditional statements (if...elif...else), loops (for and while), and the match-case structure. It explains how to use these structures for decision making and iteration, along with examples and exercises for practice. Additionally, it covers the use of iterators and the range function, as well as practical exercises to reinforce learning.

Uploaded by

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

Python Lesson 4 - Control Structures

This document provides an overview of control structures in Python, including conditional statements (if...elif...else), loops (for and while), and the match-case structure. It explains how to use these structures for decision making and iteration, along with examples and exercises for practice. Additionally, it covers the use of iterators and the range function, as well as practical exercises to reinforce learning.

Uploaded by

aliawad18931893
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Data Handling & Decision Making

Madhusha (Maddy) Nanayakkara


PYTHON 3.11
FOR
Cybersecurity
Lesson 4
Control
Structures
• if… elif… else: The Conditional control flow structure that
determines which statements to be executed depending
Iimportant on the criteria specified.
• for loop: The control flow structure that is useful for
Control iterating over a sequence (that is either a list, a tuple, a
Structures in dictionary, a set, or a string).
• while loop: The control flow structure that allows you to
Python execute a set of statements until the specified condition is
validated as false.
• match…case: The control flow structure that enables
direct structural pattern matching. It allows you to more
easily control the flow of your programs by executing
certain parts of code if conditions (or cases) are met.
if…elif…else
• An "if statement" is written by using the if keyword.
• elif is an optional block that evaluates a given condition "if the
previous conditions were not true".
• else is an optional block that catches any condition that has been not
addressed by preceding conditions.

if <condition 1>:
<do something?
.
.
elif <condition 2>:
<do something>
if…elif…else .
.
elif <condition n>:
<do something>
.
.
else:
<do something>
.
.
x = 233
y = 12
if x > y:
print("x is greater than y")
if…elif…else elif x == y:
print("x and y are equal")
else:
print("y is greater than x")
• If there is only one statement to execute, it can be placed on
the same line as the if statement.
x = 233
y = 12
if x > y: print("x is greater than y")
Short Hand if
and • If there is only one statement to execute, one for if, and one
if…else for else, they can all be on the same line.
print("X") if x > y else print("Y")

• Multiple else statements can also be included in on the same


line.
print("X") if x > y else
print("X=Y") if x == y else print("Y")
Working
with Python
Operators
Working
with Python
Operators
• if statements cannot be empty, but if you for some reason
have an if statement with no content, put in the pass
statement to avoid getting an error.
The pass
Statement x = 323
y = 30

if x > y:
pass
for Loop
for Loop
Python For loop is used for sequential traversal i.e. it is
used for iterating over an iterable like String, Tuple, List,
Set or Dictionary.
In Python, there is no C style for loop, i.e., for (i=0; i<n;
i++). There is “for” loop which is similar to each loop in
other languages. Let us learn how to use for in loop for
sequential traversals.

for var in iterable:


# statements

students = ["Steve", "Ron", "Ken"]


for x in students:
print(x)

myNums = [1,2,5,7]
for x in myNums :
print(x*65)
• An iterator is an object that contains a countable number
of values/items.
• An iterator is an object that can be iterated upon, meaning
that you can traverse through all the values.
• A Python iterator is an object which implements the
iterator protocol, which consist of the methods __iter__()
Iterators and __next__().
• Lists, tuples, dictionaries, and sets are all iterable objects.
They are iterable containers which you can get an iterator
from.
• Even strings are iterable objects, and can return an
iterator.
• Any iterable object can be used in a for loop.
myNums = [1,2,5,7]
for x in myNums :
print(x*65)

myName = "Steve"
counter = 1
for x in myName :
print(x + ":", counter)
counter += 1
Iterators
• Any iterable object can be converted into an iterator that can be
manipulated using the next() method.
myit = iter(myName)

print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
• break: the break statement stops the loop and prevents it from
looping through the remaining iterations.
myNums = [1,2,5,7]

for x in myNums :
print(x)
if x == 5:
break
Break and print(x)

Continue • continue : the continue statement stops the current iteration of the
loop and allows it to continue with the next.
myNums = [1,2,5,7]

for x in myNums :
print(x)
if x == 5:
continue
print(x)
range(start, stop, step)
Parameter Description
start Optional. An integer number specifying at which position to start. Default is 0
stop Required. An integer number specifying at which position to stop (not included).
step Optional. An integer number specifying the incrementation. Default is 1

• range(): The range() function returns a sequence of numbers, starting


from 0 by default, and increments by 1 (by default), and ends at a
specified number. This, therefore, can be used in a for loop effectively.

for loop extras x = range(3, 50, 3)


for n in x:
print(n)

x = range(10) #10 numbers starting at 0 incremented by 1


for n in x:
print(n)
• The else keyword in a for loop specifies a block of code to be executed
when the loop is finished.
for x in range(10):
print(x)
else:
print(“Loop Ended!")

else in for for x in range(8):


Loop if x == 5: break
print(x)
else:
print("Loop ended by the break!")

• for loops cannot be empty, but if you for some reason have a for loop
with no content, put in the pass statement to avoid getting an error.
for x in [0, 1, 2]:
pass
• A: Given a positive integer list, that is called "numbers“, e.g. numbers = [10, 2, 4, 1, 6, 18], what are the two values, whose sum
becomes the maximum in the list? (Please write the function that returns the two values.)
• B: Generate a list of random integer numbers, with 20 numbers. Find the sum of all even numbers and odd numbers
separately from the generated list using a for loop. Assign the values to two variables and print them.
C: You have data about students who learned some chosen subjects and have the score according to the completed
course. The director wants to know the average score of students who have completed math subject. Use a for-loop to
complete this task. Provide the answer in two decimal places. P.S. average score of math subject only! It should be equal to
Exercise 1

84.67. "Python"], "score": [90, 95]},


{"id": 2, "first_name": "John", "last_name": "Quick", "subjects": ["English", "Python"], "score": [87, 93]},
{"id": 3, "first_name": "Paul", "last_name": "Kenedy", "subjects": ["English", "C++", "Math"], "score": [85, 76, 90]},
{"id": 4, "first_name": "Ricki", "last_name": "Morty", "subjects": ["C++", "Math"], "score": [67, 74]}]
• D: write a program to print the multiplication table of a given number. Example: if it is 2 then the output will be
2,4,6,8,10,12,14,16,18,20.
• E: Write a program to print a table of 5 numbers entered by the user using a while loop.
• F: Write a program to display only those numbers from a list that satisfy the following conditions
• The number must be divisible by five.
• If the number is greater than 150, then skip it and move to the next number
• If the number is greater than 500, then stop the loop.
• numbers = [12, 75, 150, 180, 145, 525, 50]
• G: An automobile manufacturer has been producing a specific model of convertible cars since the year 2000. Represent the
sales price of each model by year using a dictionary. What is the average price of the models built between 2005 and 2010?
• H: Create a dictionary of students marks. - Write a function with a loop to sort this dictionary In descending order , and return
a sorted list of tuples.
• I: In this list “fruits” make a loop to jump banana. fruits = ["apple", "banana", "cherry"]
while Loop
while Loop

the while loop we can execute a set of


statements until the condition specified is
evaluated false.

while expression:
statement(s)

i = 4
while i < 12:
print(i)
i += 2
“””Prints numbers starting at 10 and by
incrementing the number by 3 in each iteration. If
the number becomes 25, then stops the loop.”””
i = 10
while with while i < 60:
print(i)
break, if i == 25:
break
continue, else, i += 3

and pass “””Prints odd numbers starting at 10 and by


incrementing the number by 3 in each iteration.”””
i = 10
while i < 60:
i += 3
if i % 2 == 0:
continue
print(i)
match…case
• A match-case statement is a statement that evaluates an expression
against a case and then executes the block of enclosed code.
• The case other is equivalent to else in an if-elif-else statement and can
be more simply written as case _.

match <param to match>:


case <case 1>:
<do something>
match…case case <case 2>:
<do something>
case <case n>:
<do something>
case other:
<do something when others don’t match>
#matching the cases of an integer variable
user_input = 50
match user_input:
case 20:
print("You selected 20!")
match…case case 30:

Example 1 case 40:


print("You selected 30!")

print("You selected 40!")


case 50:
print("You selected 50!")
#matching the cases of a string variable
user_input = "exit"
match user_input:
case "run":
match…case print("The code is running.")

Example 2 case "pause":


print("Code execution is paused.")
case "exit":
print(“The code is exiting")
#matching the cases of an integer variable with the pipe operator to
combine multiple matches
user_input = 30
match user_input:

match…case case 20:


print("You selected 20!")

Example 3 case 30 | 40:


print("You selected 30 or 40!")
case 50:
print("You selected 50!")
#matching the partial cases of an integer variable and including a
default case.
user_input = 400
match int(str(user_input)[0]):
case 2:

match…case case 3:
print("You selected 20!")

Example 4 case 4:
print("You selected 30!")

print("You selected 40!")


case _:
print("You selected an invalid input!")
#matching the structure of collection with match-case.
collection1 = [7, 8, 9, 10]
match collection1:

match…case case [a]:


print("Only one item:", [a])

Example 4 case [a,b]:


print("Two items:",[a,b])
case [a,b, *rest]:
print(“More than two items:", [a,b, rest])
#matching the data type.
value = 400
match value:
case int() | float() as value:

match…case print("numeric")
case str() as value :
Example 5 print("String")
case _:
print("Unacceptable Data Type")
#match-case guarded with if.
student = {'name': 'Kate', 'grade':90,
'courses':16}
match student:
case {'name': name, 'courses': courses,
'grade': grade} if courses > 15 and grade >= 90:
match…case print(name , "Exceptional")

Example 6 case {'name': name, 'courses': courses,


'grade': grade} if grade >= 90:
print(name , "Good")
case _ :
print(name , "No current award")
Exercise 2
• In a cricket match, a standard “over” has 6 balls. For each ball, the player can score up to 6 points just by batting (ignoring the extras).
Generate a list of 5 overs (a list of lists) of random scores.
• Generate the ideal list (with perfect scores). What is the total score for each over based on your numbers? What is the total possible
score for all 5 overs?
• Write a function (cricSummary) to do the following:
• Accept two parameters: one Cricket list (scores - a list of 5 overs/lists) and one character value (opts) that instruct the function
what to do.
• Check “opts” for the value; It must match. If these are not the values of opt, then the function must STOP its operations and exit
wwith “Average”, “AverageByOver”, “Sum”, “SumByOver”ith the message “Invalid Operation!”.
• If opt is Average, then return the average of all 5 overs.
• If opt is AverageByOver, then return the average of each over (as a list).
• If opt is Sum, then return the sum of all 5 overs.
• If opt is SumByOver, then return the sum of each over (as a list).

[
[6, 5, 4, 4, 2, 1],
[6, 1, 1, 4, 3, 1],
[3, 5, 2, 6, 1, 1],
[2, 3, 4, 2, 2, 1],
[1, 5, 4, 3, 2, 1]
]

You might also like