3-Python-Flow-Control-Loops.pptx
3-Python-Flow-Control-Loops.pptx
False
END
Using loop to not terminate
• Another use of loop is to make a written
program not terminate immediately after
doing its job.
• It can be done by putting a part of the code
inside a loop block.
• However, if the condition is always True, it will
never terminate as the condition will never
become false.
while loop example
>>> while True:
... varC = input(“Input a number: ”)
... varF = int(varC) * 9 / 5 + 32
... print(f”{varC} Celsius is {varF} Fahrenheit.”)
Input a number: 95
95 Celsius is 203.0 Fahrenheit.
Input a number: 32
32 Celsius is 89.6 Fahrenheit.
Input a number:
Using loop to not terminate
• To solve this issue there are 3 keywords to
alter the flow of the loop even without
changing the condition’s value.
– break
– continue
– else
break statement
• This statement is used to stop the loop
immediately even if the while condition is
still True.
• Regardless of what’s going on inside the
loop, once python sees this statement, it
will immediately end the loop.
break example
>>> counter = 0
>>> while counter != 10:
... if counter == 2:
... break
... print(f”{counter} is not equal to 3”)
... counter += 1
...
0 is not equal to 3
1 is not equal to 3
>>>
break example
>>> while True:
... varC = input(“Input a number: ”)
... if varC.lower() == “exit”:
... break
... varF = int(varC) * 9 / 5 + 32
... print(f”{varC} Celsius is {varF} Fahrenheit.”)
Input a number: 95
95 Celsius is 203.0 Fahrenheit.
Input a number: exit
>>>
continue statement
• This statement is used to stop the current
iteration and continue to the next
iteration.
• Regardless of what’s going on inside the
loop, once python sees this statement, it
will stop the current iteration and proceed
itself to the next iteration.
continue example
>>> counter = 0
>>> while counter != 3:
... if counter == 1:
... counter += 1
... continue
... print(f”{counter} is not equal to 3”)
... counter += 1
...
0 is not equal to 3
2 is not equal to 3
>>>
continue example
>>> while True:
... varC = input(“Input a number: ”)
... if varC.isnumeric() == False:
... continue
... varF = int(varC) * 9 / 5 + 32
... print(f”{varC} Celsius is {varF} Fahrenheit.”)
Input a number: 95
95 Celsius is 203.0 Fahrenheit.
Input a number: asdasd
Input a number:
else statement
• else statement in loop executes once the
condition of the loop becomes False.
• This does not run if the loop was
terminated because of break statement.
else example
>>> counter = 0
>>> while counter != 3:
... print(f”{counter} is not equal to 3”)
... counter += 1
... else:
... print(f”{counter} is equal to 3”)
...
0 is not equal to 3
1 is not equal to 3
2 is not equal to 3
3 is equal to 3
Sample Problem
• The sum of the squares of the first ten natural
numbers is:
– 1^2 + 2^2 + 3^2 + .... + 10^2 = 385
• The square of the sum of the first ten natural
numbers is:
– (1+2+3+...+10)^2 = 55^2 = 3025
• Find the difference the square of the sum and
sum of the squares of the first one hundred
natural numbers.
Sample Problem
• Set a variable named password with a value of “cpe 202l”
• Create a program that checks if the input password is
correct.
• Count the number of attempts the user has entered the
password and display the count when the user has entered
the password correctly
• Give the user a warning that the account will be locked after
4 wrong attempts.
• At 5th wrong attempt, tell the user that the account is locked
and to contact the administrator to unlock it.
For loop syntax
>>> for varName in sequence:
... #block of codes to repeat
... #block of codes to repeat
... #block of codes to repeat
>>>
For loop example
>>> message = “Hello”
>>> for character in message:
... print(character)
...
H
e
l
l
o
>>>
Python Data Types
• Text Data Type: • Mapping Type:
– String (str) – Dictionary {dict}
• Numeric Data Type: • Set Types:
– Integer (int) – Set {set}
– Float (float)
– Frozen Set (frozenset)
– Complex (complex)
• Boolean Type: • Binary Types:
– Boolean (bool) – Bytes (bytes)
• Sequence Types: – Byte Array (bytearray)
– List [list] – Memory View (memoryview)
– Tuple (tuple) • None Type:
– Range (range) – None (None)
Range Data Type
• In python, range is a sequence data type
used to generate a sequence of numbers.
• range() is a built-in function to create a
range object.
• range object is often used together with
For loop.
Range Data Type
• range() function has three arguments that can
be used inside. range(start,end,step)
– start 🡪 determines where does the range
sequence start. Optional, defaults to 0
– end 🡪 determines where the range sequence
ends. Required.
– step 🡪 determines the step size between each
number in the sequence. Optional, defaults to 1
range() syntax
• It can be used in three ways with these
arguments.
– range(end)
– range(start, end)
– range(start, end, step)
range(end)
>>> for number in range(5):
... print(number)
...
0
1
2
3
4
>>>
range(start,end)
>>> for number in range(2,7):
... print(number)
...
2
3
4
5
6
>>>
range(start,end,step)
>>> for number in range(1,9,2):
... print(number)
...
1
3
5
7
>>>
Sample Problem
• If we all list all the positive integers below
10 that are multiples of 3 or 5, we will get
3,5,6,9.
• The sum of these numbers is 23.
• Find the sum of all the multiples of 3 or 5
below 1000.
Sample Problem
• Generate a Fibonacci sequence from 1st
number to the input nth number.
• Fibonacci sequence starts from 0 and 1.
• The next number is the sum of the two
previous number.
• 0,1,1,2,3,5,8,13,….
Sample Problem
•
Sample Problem
• The user will enter a number.
• The program will output the answer to its
factorial.
• 5! = 5 x 4 x 3 x 2 x 1
Sample Problem
• Given an input of a positive integer with 4
digits or above.
• Print the sum of each digit of the number.
• The program will only end if the user enter
the value of zero.
Nested Loop
• Like the if statement, it is possible to do a
loop within a loop.
• It is useful if there are elements that are
part of a larger set of element.
Nested Loop Example
>>> for hour in range(12):
... for minute in range(0,60,15):
... print(f”{hour} : {minute}”)
...
0 : 0
0 : 15
0 : 30
0 : 45
1 : 0
1 : 15
Sample Problem
• Display a multiplication table from 1 to the
user input.
• The table will only display the
multiplication from 0 to 10.
Sample Problem
• Given an input of a positive integer.
• Print all the prime numbers from 0 to the
input.