0% found this document useful (0 votes)
17 views

Introduction To Python

This document discusses Python loops and control flow statements. It covers for, while, and nested loops as well as break, continue, else and pass statements. Examples and exercises are provided to illustrate different loop concepts.

Uploaded by

rojananth
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)
17 views

Introduction To Python

This document discusses Python loops and control flow statements. It covers for, while, and nested loops as well as break, continue, else and pass statements. Examples and exercises are provided to illustrate different loop concepts.

Uploaded by

rojananth
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
You are on page 1/ 24

Introduction to Python

Dr. Tharaka Ilayperuma

Dr. Tharaka Ilayperuma


Re-cap

From last week….

we looked at
- conditional structures: if statement and match statement
- iteration using for loop
- range() function for generating arithmetic progressions

Dr. Tharaka Ilayperuma


More on for loops ….

len() function
break, continue, and pass statements
Using else conditional statement with for loop in python

Dr. Tharaka Ilayperuma


The len() function (1)

len() function returns number of items an object


• E.g. if the object is a string, len() function returns the number of characters

output

Dr. Tharaka Ilayperuma


The len() function (2)
len() function can be used to iterate over an object to print its elements

• If we want to iterate over a list of elements, what information do we need?


• Size of the list
• How to get the size?
• we can use len()function to get the size and then use range() function to create
required arithmetic progression

• Example

employee = [“Russel”, “Chris”, “Euan”] List of employees

for i in range(len(employee))
print(employee[i])

Dr. Tharaka Ilayperuma


break, continue and pass Statements
We can use loops in Python to repeatedly execute a code block

What’s if we want to exit the loop completely, or skip an iteration?

We can use the following loop control statements change the normal execution flow
• break statement
• continue statement
• pass statement

Dr. Tharaka Ilayperuma


break Statement
break is used to exit a for loop or a while loop and pass the control to the statements that are
present after the break statement (if any)

Code block of the


while loop

Code block
immediately after
the while loop

Dr. Tharaka Ilayperuma


break Statement - Example

output

Dr. Tharaka Ilayperuma


continue Statement
continue is used to skip the current block, and forces to execute the next iteration of the loop

Code block of the


while loop

Code block
immediately after
the while loop

Dr. Tharaka Ilayperuma


continue Statement

Dr. Tharaka Ilayperuma


pass Statement

The pass statement in Python is used when a statement is required syntactically but you
do not want any command or code to execute
• E.g. it can be used to write empty loops

Dr. Tharaka Ilayperuma


for .. else
In Python, for loop can be combined with else statement

The else block just after for/while is executed only when the loop is NOT terminated by a
break statement

output

output Force to exit the loop

Dr. Tharaka Ilayperuma


while Statement

Dr. Tharaka Ilayperuma


while loop
The while loop can execute set of statements as long as an expression is true

Dr. Tharaka Ilayperuma


while loop - Examples

i = 1, emp = ["Chris", "John", "Sam"]


while i < 5: i = 0
print (i) while len(emp) > i:
i = i + 1 print(emp[i], len(emp[i]))
i += 1

With the break statement we can stop the loop even if the while condition is true:

i = 1,
while i < 5:
print (i)
if i == 3
break
i = i + 1

Exit the loop and execute the statements outside the loop

Dr. Tharaka Ilayperuma


Nested Loops (1)

Nested loops consist of an outer loop and one or more inner loops. Each time the outer
loop is repeated, the inner loops are re-entered and started anew.

Useful when you have to iterative over multidimensional data structures like dictionaries
in Python

Dr. Tharaka Ilayperuma


Nested loops (2)

If you have a block of code you want to run x number of times, within that a block of
code which you want to run y number of times, you use what is known as a "nested
loop"

Part of the output

Dr. Tharaka Ilayperuma


Exercise 1
Use a for loop to create a list of numbers based on user input and print the list

How to approach the solution?


1. Create an empty list (e.g. num = [])
2. Get the number of elements as a user input (e.g. num_ele)
3. Use a for loop to:
a. read each element and assign it to a temporary variable (e.g. tmp)
b. append the element to the list (use num.append(tmp))
# repeat the above steps from 3.a and 3.b until the list size

4. Print the list

Dr. Tharaka Ilayperuma


A solution

output

Dr. Tharaka Ilayperuma


Exercise 2

Display the elements in the following dictionary data structure as in the figure below

emp = {'Euan': {'pos':'L','sal':50000,'OT':0}, 'Jack': {'pos':'C','sal':30000,'OT':10}}

Dr. Tharaka Ilayperuma


Solution
emp = {'Euan': {'pos':'Lecturer','sal':50000,'OT':0}, 'Jack': {'pos':'Clerk','sal':30000,'OT':10}}
for keys, values in emp.items():
print (keys)
for key, value in values.items():
print(f'{key:10} ==> {value:10}')

items() method returns an object that contains the key-value pairs of the dictionary, as
tuples in a list

Dr. Tharaka Ilayperuma


Summary

We looked at:
• Iteration
• for loop
• while loop
• range() function
• len() function
• Using else statement with for and while loops
• break, continue, and pass statements
• Nested loops

Dr. Tharaka Ilayperuma


References

Head First Pytho- Brain Friendly Guide available at:


https://github.com/anzhihe/learning/blob/master/python/book/head%20first%20python.
pdf

Dr. Tharaka Ilayperuma


Questions?

Dr. Tharaka Ilayperuma

You might also like