0% found this document useful (0 votes)
28 views21 pages

PAI Lecture 5

The document discusses loops in programming for artificial intelligence. It covers while loops, for loops, the range() function, nested loops, and using break and continue to alter program flow. While loops repeat an expression as long as a condition is true. For loops iterate over each item in a sequence. The range() function generates integer sequences for use in for loops. Nested loops contain loops within other loops.

Uploaded by

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

PAI Lecture 5

The document discusses loops in programming for artificial intelligence. It covers while loops, for loops, the range() function, nested loops, and using break and continue to alter program flow. While loops repeat an expression as long as a condition is true. For loops iterate over each item in a sequence. The range() function generates integer sequences for use in for loops. Nested loops contain loops within other loops.

Uploaded by

Arul Johanna
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 21

Official (Closed) - Non Sensitive

PAI

W
E Loops
[ Play Slide Show to view the animations and listen to the narration.
E Such slides have an Audio icon on the top right corner. ]
K
PROGRAMMING FOR AI (PAI)
Oct 2022
5
Objectives
Official (Closed) - Non Sensitive

 At the end of this lesson, you will be able to:


 Code using while and for loop
 Understand the range() function
 Code nested loops
 Able to alter program flow using break and continue
 Use list comprehension to create new lists

Lecture 5
Slide 2
Topics
Official (Closed) - Non Sensitive

 while loop
 for loop
 range()
 Nested loop
 break
 continue

Lecture 5
Slide 3
Recap if-elif-else
Official (Closed) - Non Sensitive

 When executed, only goes through construct only once!


One-transaction-ATM
if-elif-else structure
z = int( input('Enter a number: ' ) )
if z % 2 == 0 :
print('z is divisible by 2')
elif z % 3 == 0 :
print('z is divisible by 3')
else :
print('z is neither divisible by 2 or 3')
https://vectortoons.com/products/a-man-getting-money-and-r
eceipt-from-the-atm

Lecture 5
Slide 4
while loop – 1
Official (Closed) - Non Sensitive

Sequence of execution:
while loop structure Line No. Action
while condition : Output: 1 error set to 20
expression 6.666666666666667 2 condition is True
2.222222222222223 3 error = 6.66…
 Repeating expression 0.740740740740740
as long as 4 condition is
prints error
end 2 condition is True
True
3 error = 2.22…
 Example: 4 prints error
1: error = 20
 Error starts at 20 2: while error > 1 :
2 condition is True
3 error = 0.74…
 Divide error by 3 on every iteration 3: error = error / 3
4 prints error
 Continue until error no longer > 1 4: print(error)
2 condition is False
5: print('end')
5 prints end
Lecture 5
Slide 5
while loop – 2
Official (Closed) - Non Sensitive

while loop structure


while condition_is_True :
do_something

 Be careful to ensure condition eventually terminates the loop


 Example:
 code below runs 'forever', interrupt the Python Kernel to stop the run.
1: error = 20
2: while error > 1 :
3: # error = error / 3
4: print(error)
5: print('end')
Lecture 5
Slide 6
for loop – 1
Official (Closed) - Non Sensitive

 Definition:
for loop structure
for var in seq :
expression
 for each var in seq, execute expression
 Interpretation:

for loop structure


for each_thing in a_group_of_things :
do_something

Lecture 5
Slide 7
for loop – 2
Official (Closed) - Non Sensitive

 Recall list:
family_height = [ 1.72, 1.58, 1.69, 1.79 ] Output:
print(family_height) [ 1.72, 1.58, 1.69, 1.79 ]

 How to print each value on a line by itself?


family_height = [ 1.72, 1.58, 1.69, 1.79 ] Output:
print(family_height[0]) 1.72
1.58
print(family_height[1])
1.69
print(family_height[2]) 1.79
print(family_height[3])
 Is there an easier way?

Lecture 5
Slide 8
for loop – 3
Official (Closed) - Non Sensitive

for loop structure


for each_thing in a_group_of_things :
 Use for loop do_something

family_height = [ 1.72, 1.58, 1.69, 1.79 ]


for height in family_height :
print(height)
Output:
 First iteration, height has value 1.72, prints height 1.72
 Second iteration, height has value 1.58, prints height 1.58
1.69
 Third iteration, height has value 1.69, prints height 1.79
 Fourth and last iteration, height has value 1.79, prints height
 End of list
 No more access to height after the iterations.

Lecture 5
Slide 9
range() – 1
Official (Closed) - Non Sensitive

 range is an immutable (non-modifiable) sequence type (list is also a


sequence type) that represents arithmetic progression
 To generate the range sequence, range() is called.
 range is especially useful to iterate over a sequence of numbers in
loops

Lecture 5
Slide 10
range() – 2
Official (Closed) - Non Sensitive

range(stop)
range(start,
range(start, stop)
stop)
range(start, stop, step)
range(start, stop, step)
 start: Starting number of the sequence
 stop: Generate numbers up to, but not including this number
 step: Difference between each number

 Parameters can be passed in range() to determine the range of


sequence generated
 All parameters must be integers
 All parameters can be positive or negative
Lecture 5
Slide 11
range() – 3
Official (Closed) - Non Sensitive

 Examples:
for x in range(5) : for x in range(3, 6) : for x in range(3 , 8, 2) :
print(x) print(x) print(x)

Output: Output: Output:


0 3 3
1 4 5
2 5 7
3
4
list1 = list( range(1, 6) )
list1
Output:
[1, 2, 3, 4, 5 ]

Lecture 5
Slide 12
range() – 4
Official (Closed) - Non Sensitive

 How to print the index AND the item in a list?


family_height = [ 1.72, 1.58, 1.69, 1.79 ] Output:
??? index 0: 1.72
index 1: 1.58
index 2: 1.69
index 3: 1.79

 Loop over a range() index values of the list.


 Example:
family_height = [ 1.72, 1.58, 1.69, 1.79 ]
for i in range(0, len(family_height)) :
print(f'index {i}: {family_height[i]}')

Is there an easier way?


Lecture 5
Slide 13
for loop enumerate
Official (Closed) - Non Sensitive

for loop enumerate structure


for index, each_thing in enumerate(a_group_of_things) :
do_something

 Use enumerate to loop over a collection while keeping track of the index
in a variable:
family_height = [ 1.72, 1.58, 1.69, 1.79 ] Output:
index 0: 1.72
for index, height in enumerate(family_height) index 1: 1.58
print(f'index {index}: {height}') index 2: 1.69
index 3: 1.79

Lecture 5
Slide 14
Loop over string
Official (Closed) - Non Sensitive

 Same syntax: for loop structure


for each_thing in a_group_of_things :
for letter in 'family' : do_something
print(letter.capitalize())
Output:
F
A
M
I
L
Y

Lecture 5
Slide 15
Nested Loop
Official (Closed) - Non Sensitive

 A loop can contain any statements.


 Nested loop is a loop that contains another loop
 For every iteration of the outer loop, the inner loop is repeated
 Nested loop created using any of the repetitions structure
 May use different loop for the inner and outer loops
for item1 in list1: while expression:
for item2 in list2: while expression:
statement(s) statement(s)
statement(s) statement(s)

for item in list: while expression:


while expression: for item in list:
statement(s) statement(s)
statement(s) statement(s)
Lecture 5
Slide 16
Nested Loop – Example 1
Official (Closed) - Non Sensitive

 Write a nested loop to display the following pattern:


=======
=======
=======

for i in range(3):
outer loop
for j in range(7):
print('=', end='')
inner loop
print()

Lecture 5
Slide 17
Nested Loop – Example 2
Official (Closed) - Non Sensitive

 Write a nested loop to display the following pattern:


1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

for row in range(1, 6):


outer loop
for col in range(1, row+1):
print(col, end='')
inner loop
print()

Lecture 5
Slide 18
break statement
Official (Closed) - Non Sensitive

 break # Example 2
 To exit a loop completely when a var = 10
condition is True while var > 0 :
print('Current variable value: ', var)
 Resumes execution at next statement
var = var – 1
after loop
if var == 5 :
 Examples: # Example 1 break
for letter in 'Python' : print('Good bye!')
if letter == 'h' :
Output:
break Current variable value: 10
print('Current letter: ', letter) Current variable value: 9
Current variable value: 8
Output:
Current variable value: 7
Current letter: P
Current variable value: 6
Current letter: y
Good bye! Lecture 5
Current letter: t Slide 19
continue statement
Official (Closed) - Non Sensitive

# Example 2
var = 10
 continue while var > 0 :
var = var – 1
 To skip all remaining statements in loop
if var == 5 :
and start next iteration continue
 Control goes to beginning of loop print('Current variable value: ', var)
print('Good bye!‘)
# Example 1
for letter in 'Python' : Output:
if letter == 'h' : Current variable value: 10
Current variable value: 9
continue Current variable value: 8
print('Current letter: ', letter) Output:
Current variable value: 7
Current letter: P
Current variable value: 6
Current letter: y
Current variable value: 4
Current letter: t
Current variable value: 3
Current letter: o
Current variable value: 2
Current letter: n
Current variable value: 1 Lecture 5
Good bye! Slide 20
Summary
Official (Closed) - Non Sensitive

 while loop
 a loop that executes the statements as long as the condition is True
 for loop
 a loop used for iterating over values in a sequence eg. list, etc.
 range()
 to specify a range of values that can be used in a loop
 Nested loop
 Outer loop that has a inner loop
 break
 to skip the rest of the statements in the loop and terminate the loop
 continue
 to skip the rest of the statements in the loop and continue from the beginning of the loop
Lecture 5
Slide 21

You might also like