SlideShare a Scribd company logo
1 of 24
Download to read offline
Python - Control Structures
Lasith Niroshan
University of Colombo School of Computing
lasithniro.online@gmail.com
July 17, 2018
Lasith Niroshan (UCSC) python-III July 17, 2018 1 / 24
Overview
1 Introduction to Control Structure
2 Conditional Statements
the if statement
if-else statement
if-elif-else statement
3 Loops
while
break and continue
for
4 Usage of loops
Lasith Niroshan (UCSC) python-III July 17, 2018 2 / 24
Learning Outcomes
Briefly describes control structures
Lists and briefly describes the types of control structures
Uses control structures appropriately in programming
Applies nested control structures in programs
Lasith Niroshan (UCSC) python-III July 17, 2018 3 / 24
Introduction
Sometimes we want to execute statements,
only under certain conditions (if)
repeatedly: loops (for, while)
repeated part of the code in another part of the program (functions)
Lasith Niroshan (UCSC) python-III July 17, 2018 4 / 24
The if statement
For an if statement, a condition (e.g., x > 0) is evaluated to either True
(run the code) or False (dont run it, or move on to the else block).
Example (if.py)
if (x>0):
print("x is greater than zero")
print(’number checking program in over.’)
Note:
Conditions (e.g., x ¡ 4) can be put in parentheses, but do not need to
be.
0 and ”” (the empty string) evaluate to False.
A block consists of one or more statements
Lasith Niroshan (UCSC) python-III July 17, 2018 5 / 24
The if-else statement
The else part will execute, when if condition is failed.
Example (if else.py)
if (x>0):
print("x is greater than zero")
else:
print("x is lower than 0)
print(’number checking program in over.’)
Lasith Niroshan (UCSC) python-III July 17, 2018 6 / 24
The if-else-elif statement
If we have more than one conditions to check we have to use elif
command.
else + if = elif
Example (if elif.py)
if (x>0):
print("x is greater than zero")
elif(x<0):
print("x is lower than zero")
else:
print("x must equal to 0")
print(’number checking program in over.’)
Lasith Niroshan (UCSC) python-III July 17, 2018 7 / 24
Tests
x == y equals y
x < y is less than y
x > y is greater than y
x >= y is greater than or equal to y
x <= y is less than or equal to y
x! = y is not equal to y
x is y is the same object as y
x is not y is not the same object as y
x in y is a member of y
x not in y is not a member of y
Caution: = and == are different.
Lasith Niroshan (UCSC) python-III July 17, 2018 8 / 24
Indentation
Spaces are important.
Indentation shows structure of code.
Lasith Niroshan (UCSC) python-III July 17, 2018 9 / 24
Exercise 1: if, else and Blocks
What are the values of a, b and c after executing the following piece of
code?
Example (while.py)
a = b = 2;c = False
if not c:
if b < a:
b += 5
a = b-1
elif a < b:
c = True
else:
if a+b < 4:
c = False
a = 11
b = 2.2
print(a, b, c)
Lasith Niroshan (UCSC) python-III July 17, 2018 10 / 24
Loops: while
A while loop does a similar condition check, but then runs a block of code
as long as that condition evaluates to True.
Example (while.py)
i = 1
while i < 10:
print (str(i) + " is my friend.")
i += 1
Run the block of indented code 10 times.
Each time, the variable i has a new value.
Lasith Niroshan (UCSC) python-III July 17, 2018 11 / 24
Output
Lasith Niroshan (UCSC) python-III July 17, 2018 12 / 24
Loops: break and continue Statements
Example (get text.py)
#!/usr/bin/python3
while expr_1:
if expr_2:
block_1
continue
block_2
if expr_3:
break
block_3
break : break out of the loop.
continue : continue with the next iteration.
Lasith Niroshan (UCSC) python-III July 17, 2018 13 / 24
Loops: Example
continue.py
for i in range(5):
if (i == 3):
continue
print(i)
break.py
for i in range(5):
if (i > 2):
break
print(i)
Lasith Niroshan (UCSC) python-III July 17, 2018 14 / 24
Loops: Exercise 2 - continue & break with while loop
What is the output after executing the following piece of code?
exercise2.py
#!/usr/bin/python3
i=0
while ( i < 5 ):
i = i + 1
if (i == 3):
continue
if (i > 4):
break
print(i)
Lasith Niroshan (UCSC) python-III July 17, 2018 15 / 24
Loops: for
We can use for loops when we know the limitations.
Example (for.py)
for i in range(0, 10):
print (str(i) + " is my friend.")
For now, you can imagine that range(0,5) creates a list:
[0, 1, 2, 3, 4]
range(start, end, step) : All arguments must be integers.
range(0,10,2) returns [0, 2, 4, 6, 8]
range(10,0,-2) returns [10, 8, 6, 4, 2]
range() does not actually return lists - if you want get lists (e.g. for
printing):
x = list(range(0,2)) print(x)
Lasith Niroshan (UCSC) python-III July 17, 2018 16 / 24
Loops: for
We can use for loops when we know the limitations.
Example (for.py)
weekdays = [’Mon’, ’Tues’, ’Fri’]
for day in weekdays:
print("Today is a..."+day)
Python executes the block of the loop once per item of the list.
The list item is assigned to the variable, here day .
Lasith Niroshan (UCSC) python-III July 17, 2018 17 / 24
Loops: Exercise 3 - nested for loop
What is the output of the following program?
exercise3.py
#!/usr/bin/python3
fruits = [”apple”, ”banana”, ”melon”]
for i in range(2, 6, 2):
for f in fruits:
print(str(i) + ” ” + f + ”s”)
Lasith Niroshan (UCSC) python-III July 17, 2018 18 / 24
Loops: Exercise 4 - Factorial
The factorial of a number n is defined as follows: n! = Πn
k=1k
Example
0! = 1
1! = 1
2! = 2 ∗ 1 = 2
3! = 3 ∗ 2 ∗ 1 = 6
4! = 4 ∗ 3 ∗ 2 ∗ 1 = 24
...
Write a Python program that computes the factorial of 14.
The result should be 87178291200.
Lasith Niroshan (UCSC) python-III July 17, 2018 19 / 24
Use #1: iteration
As weve just seen, while loops can be used to iterate over a sequence.
This is most commonly done by iterating over integers, because
integers easily count how many times you do something.
You can change the way you iterate-e.g., i += 2 or i -= 1 or
whatever.
Lasith Niroshan (UCSC) python-III July 17, 2018 20 / 24
Use #2: until
Another, subtly different use is to perform the same actions until a certain
condition is reached.
Example (get text.py)
#!/usr/bin/python3
user_input = ""
while len(user_input) < 10:
user_input = input("Please enter a long string: ")
print ("Thank you for entering a long enough string!")
Lasith Niroshan (UCSC) python-III July 17, 2018 21 / 24
A Common Mistake : infinite loops
One common mistake when using while loops is to forget to iterate a
variable, such as i;
Example (infinite loop.py)
i = 0
while (i < 10):
print i
# infinite loop b/c i is not iterated
If your code doesnt stop:
Kill it (Ctrl-C on Unix, Ctrl-Z on Windows)
Examine your while loop and make sure the value is changing as you
expect it to
In general, this is a good way to debug your code
Lasith Niroshan (UCSC) python-III July 17, 2018 22 / 24
Learning Outcomes
Briefly describes control structures
Lists and briefly describes the types of control structures
Uses control structures appropriately in programming
Applies nested control structures in programs
Lasith Niroshan (UCSC) python-III July 17, 2018 23 / 24
The End
Lasith Niroshan (UCSC) python-III July 17, 2018 24 / 24

More Related Content

What's hot

Unit2 control statements
Unit2 control statementsUnit2 control statements
Unit2 control statementsdeepak kumbhar
 
Control and conditional statements
Control and conditional statementsControl and conditional statements
Control and conditional statementsrajshreemuthiah
 
FLOWOFCONTROL-IF..ELSE PYTHON
FLOWOFCONTROL-IF..ELSE PYTHONFLOWOFCONTROL-IF..ELSE PYTHON
FLOWOFCONTROL-IF..ELSE PYTHONvikram mahendra
 
COM1407: Program Control Structures – Decision Making & Branching
COM1407: Program Control Structures – Decision Making & BranchingCOM1407: Program Control Structures – Decision Making & Branching
COM1407: Program Control Structures – Decision Making & BranchingHemantha Kulathilake
 
Learning C programming - from lynxbee.com
Learning C programming - from lynxbee.comLearning C programming - from lynxbee.com
Learning C programming - from lynxbee.comGreen Ecosystem
 
Conditional Control in MATLAB Scripts
Conditional Control in MATLAB ScriptsConditional Control in MATLAB Scripts
Conditional Control in MATLAB ScriptsShameer Ahmed Koya
 
Claguage 110226222227-phpapp02
Claguage 110226222227-phpapp02Claguage 110226222227-phpapp02
Claguage 110226222227-phpapp02CIMAP
 
Control structure of c
Control structure of cControl structure of c
Control structure of cKomal Kotak
 
Python for Machine Learning
Python for Machine LearningPython for Machine Learning
Python for Machine LearningStudent
 
Structure in programming in c or c++ or c# or java
Structure in programming  in c or c++ or c# or javaStructure in programming  in c or c++ or c# or java
Structure in programming in c or c++ or c# or javaSamsil Arefin
 
Programming fundamental 02
Programming fundamental 02Programming fundamental 02
Programming fundamental 02Suhail Akraam
 
Decision statements in c language
Decision statements in c languageDecision statements in c language
Decision statements in c languagetanmaymodi4
 
Operators and expressions in c language
Operators and expressions in c languageOperators and expressions in c language
Operators and expressions in c languagetanmaymodi4
 

What's hot (18)

Unit2 control statements
Unit2 control statementsUnit2 control statements
Unit2 control statements
 
Control and conditional statements
Control and conditional statementsControl and conditional statements
Control and conditional statements
 
FLOWOFCONTROL-IF..ELSE PYTHON
FLOWOFCONTROL-IF..ELSE PYTHONFLOWOFCONTROL-IF..ELSE PYTHON
FLOWOFCONTROL-IF..ELSE PYTHON
 
COM1407: Program Control Structures – Decision Making & Branching
COM1407: Program Control Structures – Decision Making & BranchingCOM1407: Program Control Structures – Decision Making & Branching
COM1407: Program Control Structures – Decision Making & Branching
 
Learning C programming - from lynxbee.com
Learning C programming - from lynxbee.comLearning C programming - from lynxbee.com
Learning C programming - from lynxbee.com
 
Introduction to Python
Introduction to Python  Introduction to Python
Introduction to Python
 
Conditional Control in MATLAB Scripts
Conditional Control in MATLAB ScriptsConditional Control in MATLAB Scripts
Conditional Control in MATLAB Scripts
 
Python Lecture 2
Python Lecture 2Python Lecture 2
Python Lecture 2
 
Claguage 110226222227-phpapp02
Claguage 110226222227-phpapp02Claguage 110226222227-phpapp02
Claguage 110226222227-phpapp02
 
Control structure in c
Control structure in cControl structure in c
Control structure in c
 
Control structure of c
Control structure of cControl structure of c
Control structure of c
 
Ch3 selection
Ch3 selectionCh3 selection
Ch3 selection
 
Python for Machine Learning
Python for Machine LearningPython for Machine Learning
Python for Machine Learning
 
Structure in programming in c or c++ or c# or java
Structure in programming  in c or c++ or c# or javaStructure in programming  in c or c++ or c# or java
Structure in programming in c or c++ or c# or java
 
Programming fundamental 02
Programming fundamental 02Programming fundamental 02
Programming fundamental 02
 
Matlab Script - Loop Control
Matlab Script - Loop ControlMatlab Script - Loop Control
Matlab Script - Loop Control
 
Decision statements in c language
Decision statements in c languageDecision statements in c language
Decision statements in c language
 
Operators and expressions in c language
Operators and expressions in c languageOperators and expressions in c language
Operators and expressions in c language
 

Similar to Python - Control Structures

Matlab and Python: Basic Operations
Matlab and Python: Basic OperationsMatlab and Python: Basic Operations
Matlab and Python: Basic OperationsWai Nwe Tun
 
SFSCON23 - Emily Bourne Yaman Güçlü - Pyccel write Python code, get Fortran ...
SFSCON23 - Emily Bourne Yaman Güçlü - Pyccel  write Python code, get Fortran ...SFSCON23 - Emily Bourne Yaman Güçlü - Pyccel  write Python code, get Fortran ...
SFSCON23 - Emily Bourne Yaman Güçlü - Pyccel write Python code, get Fortran ...South Tyrol Free Software Conference
 
These questions will be a bit advanced level 2
These questions will be a bit advanced level 2These questions will be a bit advanced level 2
These questions will be a bit advanced level 2sadhana312471
 
Network Analysis with networkX : Real-World Example-1
Network Analysis with networkX : Real-World Example-1Network Analysis with networkX : Real-World Example-1
Network Analysis with networkX : Real-World Example-1Kyunghoon Kim
 
Basic_C++ Notes with problema from Preethi arora and suneetha arora.pdf
Basic_C++ Notes with problema from Preethi arora and suneetha arora.pdfBasic_C++ Notes with problema from Preethi arora and suneetha arora.pdf
Basic_C++ Notes with problema from Preethi arora and suneetha arora.pdfComputer Programmer
 
Data Handling.pdf
Data Handling.pdfData Handling.pdf
Data Handling.pdfMILANOP1
 
Intro to Python Programming Language
Intro to Python Programming LanguageIntro to Python Programming Language
Intro to Python Programming LanguageDipankar Achinta
 
Python programing
Python programingPython programing
Python programinghamzagame
 
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...DRVaibhavmeshram1
 
FUNDAMENTALS OF PYTHON LANGUAGE
 FUNDAMENTALS OF PYTHON LANGUAGE  FUNDAMENTALS OF PYTHON LANGUAGE
FUNDAMENTALS OF PYTHON LANGUAGE Saraswathi Murugan
 
02. Data Types and variables
02. Data Types and variables02. Data Types and variables
02. Data Types and variablesIntro C# Book
 
introduction to python in english presentation file
introduction to python in english presentation fileintroduction to python in english presentation file
introduction to python in english presentation fileRujanTimsina1
 
Python for Scientific Computing
Python for Scientific ComputingPython for Scientific Computing
Python for Scientific ComputingAlbert DeFusco
 

Similar to Python - Control Structures (20)

Matlab and Python: Basic Operations
Matlab and Python: Basic OperationsMatlab and Python: Basic Operations
Matlab and Python: Basic Operations
 
SFSCON23 - Emily Bourne Yaman Güçlü - Pyccel write Python code, get Fortran ...
SFSCON23 - Emily Bourne Yaman Güçlü - Pyccel  write Python code, get Fortran ...SFSCON23 - Emily Bourne Yaman Güçlü - Pyccel  write Python code, get Fortran ...
SFSCON23 - Emily Bourne Yaman Güçlü - Pyccel write Python code, get Fortran ...
 
pythonQuick.pdf
pythonQuick.pdfpythonQuick.pdf
pythonQuick.pdf
 
python notes.pdf
python notes.pdfpython notes.pdf
python notes.pdf
 
python 34💭.pdf
python 34💭.pdfpython 34💭.pdf
python 34💭.pdf
 
Python.pptx
Python.pptxPython.pptx
Python.pptx
 
These questions will be a bit advanced level 2
These questions will be a bit advanced level 2These questions will be a bit advanced level 2
These questions will be a bit advanced level 2
 
Network Analysis with networkX : Real-World Example-1
Network Analysis with networkX : Real-World Example-1Network Analysis with networkX : Real-World Example-1
Network Analysis with networkX : Real-World Example-1
 
Basic_C++ Notes with problema from Preethi arora and suneetha arora.pdf
Basic_C++ Notes with problema from Preethi arora and suneetha arora.pdfBasic_C++ Notes with problema from Preethi arora and suneetha arora.pdf
Basic_C++ Notes with problema from Preethi arora and suneetha arora.pdf
 
Data Handling.pdf
Data Handling.pdfData Handling.pdf
Data Handling.pdf
 
Intro to Python Programming Language
Intro to Python Programming LanguageIntro to Python Programming Language
Intro to Python Programming Language
 
Python programing
Python programingPython programing
Python programing
 
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
 
Pythonppt28 11-18
Pythonppt28 11-18Pythonppt28 11-18
Pythonppt28 11-18
 
FUNDAMENTALS OF PYTHON LANGUAGE
 FUNDAMENTALS OF PYTHON LANGUAGE  FUNDAMENTALS OF PYTHON LANGUAGE
FUNDAMENTALS OF PYTHON LANGUAGE
 
02. Data Types and variables
02. Data Types and variables02. Data Types and variables
02. Data Types and variables
 
Unit - 2 CAP.pptx
Unit - 2 CAP.pptxUnit - 2 CAP.pptx
Unit - 2 CAP.pptx
 
introduction to python in english presentation file
introduction to python in english presentation fileintroduction to python in english presentation file
introduction to python in english presentation file
 
Python 3.pptx
Python 3.pptxPython 3.pptx
Python 3.pptx
 
Python for Scientific Computing
Python for Scientific ComputingPython for Scientific Computing
Python for Scientific Computing
 

Recently uploaded

Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningVitsRangannavar
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?Watsoo Telematics
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyFrank van der Linden
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...aditisharan08
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 

Recently uploaded (20)

Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learning
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The Ugly
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 

Python - Control Structures

  • 1. Python - Control Structures Lasith Niroshan University of Colombo School of Computing lasithniro.online@gmail.com July 17, 2018 Lasith Niroshan (UCSC) python-III July 17, 2018 1 / 24
  • 2. Overview 1 Introduction to Control Structure 2 Conditional Statements the if statement if-else statement if-elif-else statement 3 Loops while break and continue for 4 Usage of loops Lasith Niroshan (UCSC) python-III July 17, 2018 2 / 24
  • 3. Learning Outcomes Briefly describes control structures Lists and briefly describes the types of control structures Uses control structures appropriately in programming Applies nested control structures in programs Lasith Niroshan (UCSC) python-III July 17, 2018 3 / 24
  • 4. Introduction Sometimes we want to execute statements, only under certain conditions (if) repeatedly: loops (for, while) repeated part of the code in another part of the program (functions) Lasith Niroshan (UCSC) python-III July 17, 2018 4 / 24
  • 5. The if statement For an if statement, a condition (e.g., x > 0) is evaluated to either True (run the code) or False (dont run it, or move on to the else block). Example (if.py) if (x>0): print("x is greater than zero") print(’number checking program in over.’) Note: Conditions (e.g., x ¡ 4) can be put in parentheses, but do not need to be. 0 and ”” (the empty string) evaluate to False. A block consists of one or more statements Lasith Niroshan (UCSC) python-III July 17, 2018 5 / 24
  • 6. The if-else statement The else part will execute, when if condition is failed. Example (if else.py) if (x>0): print("x is greater than zero") else: print("x is lower than 0) print(’number checking program in over.’) Lasith Niroshan (UCSC) python-III July 17, 2018 6 / 24
  • 7. The if-else-elif statement If we have more than one conditions to check we have to use elif command. else + if = elif Example (if elif.py) if (x>0): print("x is greater than zero") elif(x<0): print("x is lower than zero") else: print("x must equal to 0") print(’number checking program in over.’) Lasith Niroshan (UCSC) python-III July 17, 2018 7 / 24
  • 8. Tests x == y equals y x < y is less than y x > y is greater than y x >= y is greater than or equal to y x <= y is less than or equal to y x! = y is not equal to y x is y is the same object as y x is not y is not the same object as y x in y is a member of y x not in y is not a member of y Caution: = and == are different. Lasith Niroshan (UCSC) python-III July 17, 2018 8 / 24
  • 9. Indentation Spaces are important. Indentation shows structure of code. Lasith Niroshan (UCSC) python-III July 17, 2018 9 / 24
  • 10. Exercise 1: if, else and Blocks What are the values of a, b and c after executing the following piece of code? Example (while.py) a = b = 2;c = False if not c: if b < a: b += 5 a = b-1 elif a < b: c = True else: if a+b < 4: c = False a = 11 b = 2.2 print(a, b, c) Lasith Niroshan (UCSC) python-III July 17, 2018 10 / 24
  • 11. Loops: while A while loop does a similar condition check, but then runs a block of code as long as that condition evaluates to True. Example (while.py) i = 1 while i < 10: print (str(i) + " is my friend.") i += 1 Run the block of indented code 10 times. Each time, the variable i has a new value. Lasith Niroshan (UCSC) python-III July 17, 2018 11 / 24
  • 12. Output Lasith Niroshan (UCSC) python-III July 17, 2018 12 / 24
  • 13. Loops: break and continue Statements Example (get text.py) #!/usr/bin/python3 while expr_1: if expr_2: block_1 continue block_2 if expr_3: break block_3 break : break out of the loop. continue : continue with the next iteration. Lasith Niroshan (UCSC) python-III July 17, 2018 13 / 24
  • 14. Loops: Example continue.py for i in range(5): if (i == 3): continue print(i) break.py for i in range(5): if (i > 2): break print(i) Lasith Niroshan (UCSC) python-III July 17, 2018 14 / 24
  • 15. Loops: Exercise 2 - continue & break with while loop What is the output after executing the following piece of code? exercise2.py #!/usr/bin/python3 i=0 while ( i < 5 ): i = i + 1 if (i == 3): continue if (i > 4): break print(i) Lasith Niroshan (UCSC) python-III July 17, 2018 15 / 24
  • 16. Loops: for We can use for loops when we know the limitations. Example (for.py) for i in range(0, 10): print (str(i) + " is my friend.") For now, you can imagine that range(0,5) creates a list: [0, 1, 2, 3, 4] range(start, end, step) : All arguments must be integers. range(0,10,2) returns [0, 2, 4, 6, 8] range(10,0,-2) returns [10, 8, 6, 4, 2] range() does not actually return lists - if you want get lists (e.g. for printing): x = list(range(0,2)) print(x) Lasith Niroshan (UCSC) python-III July 17, 2018 16 / 24
  • 17. Loops: for We can use for loops when we know the limitations. Example (for.py) weekdays = [’Mon’, ’Tues’, ’Fri’] for day in weekdays: print("Today is a..."+day) Python executes the block of the loop once per item of the list. The list item is assigned to the variable, here day . Lasith Niroshan (UCSC) python-III July 17, 2018 17 / 24
  • 18. Loops: Exercise 3 - nested for loop What is the output of the following program? exercise3.py #!/usr/bin/python3 fruits = [”apple”, ”banana”, ”melon”] for i in range(2, 6, 2): for f in fruits: print(str(i) + ” ” + f + ”s”) Lasith Niroshan (UCSC) python-III July 17, 2018 18 / 24
  • 19. Loops: Exercise 4 - Factorial The factorial of a number n is defined as follows: n! = Πn k=1k Example 0! = 1 1! = 1 2! = 2 ∗ 1 = 2 3! = 3 ∗ 2 ∗ 1 = 6 4! = 4 ∗ 3 ∗ 2 ∗ 1 = 24 ... Write a Python program that computes the factorial of 14. The result should be 87178291200. Lasith Niroshan (UCSC) python-III July 17, 2018 19 / 24
  • 20. Use #1: iteration As weve just seen, while loops can be used to iterate over a sequence. This is most commonly done by iterating over integers, because integers easily count how many times you do something. You can change the way you iterate-e.g., i += 2 or i -= 1 or whatever. Lasith Niroshan (UCSC) python-III July 17, 2018 20 / 24
  • 21. Use #2: until Another, subtly different use is to perform the same actions until a certain condition is reached. Example (get text.py) #!/usr/bin/python3 user_input = "" while len(user_input) < 10: user_input = input("Please enter a long string: ") print ("Thank you for entering a long enough string!") Lasith Niroshan (UCSC) python-III July 17, 2018 21 / 24
  • 22. A Common Mistake : infinite loops One common mistake when using while loops is to forget to iterate a variable, such as i; Example (infinite loop.py) i = 0 while (i < 10): print i # infinite loop b/c i is not iterated If your code doesnt stop: Kill it (Ctrl-C on Unix, Ctrl-Z on Windows) Examine your while loop and make sure the value is changing as you expect it to In general, this is a good way to debug your code Lasith Niroshan (UCSC) python-III July 17, 2018 22 / 24
  • 23. Learning Outcomes Briefly describes control structures Lists and briefly describes the types of control structures Uses control structures appropriately in programming Applies nested control structures in programs Lasith Niroshan (UCSC) python-III July 17, 2018 23 / 24
  • 24. The End Lasith Niroshan (UCSC) python-III July 17, 2018 24 / 24