KEMBAR78
Python - Control Structures | PDF
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

Python - Control Structures

  • 1.
    Python - ControlStructures 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 toControl 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 describescontrol 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 wantto 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 Foran 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 Theelse 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 Ifwe 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 == yequals 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. Indentationshows 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 whileloop 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 andcontinue 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 iin 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 canuse 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 canuse 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 Asweve 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 describescontrol 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