0% found this document useful (0 votes)
7 views11 pages

Python Lesson 3a Notes - Updated 1

This document is a tutorial on using for loops in Python, explaining their syntax and providing examples. It covers the basic structure of a for loop, the use of an else block, and includes classwork exercises for practice. The document also introduces a scenario involving random integers to further illustrate the application of for loops.

Uploaded by

gigicho0815
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)
7 views11 pages

Python Lesson 3a Notes - Updated 1

This document is a tutorial on using for loops in Python, explaining their syntax and providing examples. It covers the basic structure of a for loop, the use of an else block, and includes classwork exercises for practice. The document also introduces a scenario involving random integers to further illustrate the application of for loops.

Uploaded by

gigicho0815
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

P.

1 of 11

Contents

Looping in Python – Part 2 ............................................................................................. 2


for loop example – print out from a list ................................................................. 2
Elaboration of forDemo.py ............................................................................ 4
else block of for loop...................................................................................... 5
Elaboration of forElse1.py ...................................................................... 6
Classwork 1 .................................................................................................... 8
Classwork 2 .................................................................................................. 10
P. 2 of 11

Looping in Python – Part 2


As you have got ideas about while loop, it’s high time going through another type of
loop in Python. It is for loop.

for loop example – print out from a list


for loop is a programming language statement, that is an iteration statement which
allows a code block to be repeated a certain number of times.

The Python for loop starts with the keyword "for" followed by an arbitrary variable
name which will hold the values of the following sequence object and then stepped
through. The items of the sequence object are assigned one after the other to the
loop variable. For each item the loop body is executed.

The general syntax of for loop looks like this:

for <variable> in <sequence>:

<statements>

else:

<statements>
P. 3 of 11

See the following code listing wich prints out each object from a list. (forDemo.py)

planguages=["Java", "PHP", "C", "C++", "Python"]

for i in planguages:
print (i)

#Pause the screen


ch = input('')

Here comes the output:

Below is a diagram that explains the list and the flow of the for loop:
P. 4 of 11

Elaboration of forDemo.py
1. List Creation:
planguages = ["Java", "PHP", "C", "C++", "Python"]

➢ The code creates a list named planguages that contains 5 programming


languages as its elements.
➢ A list is a collection of items in Python, and it can store strings, numbers, or
other data types.
➢ The elements in the list are indexed starting from 0.

2. for Loop:
for i in planguages:
print(i)

➢ The for loop is used to iterate over each element in the list planguages.
➢ During each iteration, the variable i takes the value of the current element in
the list.
➢ The body of the loop (print(i)) is executed for each element in the list.

3. print() Function:
➢ Inside the loop, the print(i) statement prints the value of i (i.e., the current
element of the list).
➢ Each element is printed on a new line because the print() function, by default,
adds a newline character after each call.
P. 5 of 11

else block of for loop


The else block in for loop is a bit special. Basically, it works exactly as the optional
else of a while loop. It will be executed only if the loop hasn't been "broken" by a
break statement. So it will only be executed, after all the items of the sequence have
been used.

If a break statement has to be executed in the program flow of the for loop, the loop
will be exited and the program flow will continue with the first statement following
the for loop, if there is any at all. Usually break statements are wrapped into
conditional statements. This logic can be elaborated in the following example:

forElse1.py

theType = ["ham", "spam","eggs","nuts"]

for y in theType:
if y=="spam":
print("Please don't spam!")
break
print("The taste of %s is good!" %y)
else:
print("So lucky, there is no spam!")

print("\nThat's it, just finished!")

#Pause the screen


ch = input('')

If you run the above, you will see the following output:
P. 6 of 11

Elaboration of forElse1.py

1. List Creation:
theType = ["ham", "spam", "eggs", "nuts"]

➢ The list theType contains 4 food types: "ham", "spam", "eggs", and "nuts".

2. for Loop:
for y in theType:

➢ The for loop iterates over each element of the list theType:
➢ During each iteration, the current element is assigned to the variable y.

3. Checking for "spam":


if y == "spam":
print("Please don't spam!")
break

➢ Inside the loop, there is an if condition that checks if the current element (y)
is equal to "spam".
➢ If "spam" is found:
✓ The program prints "Please don't spam!".
✓ The break statement terminates the loop immediately, skipping any
remaining elements in the list.

4. Printing Other Food Types:


print("The taste of %s is good!" % y)

➢ If the current element is not "spam", the program prints a message about the
food's taste.
➢ For instance, if y = "ham", it will print:
The taste of ham is good!
P. 7 of 11

5. else Block of the Loop:


else:
print("So lucky, there is no spam!")

➢ The else block of a for loop executes only if the loop is not terminated by a
break statement.
➢ If the loop iterates through the entire list without finding "spam", the
program will print:
So lucky, there is no spam!

6. Final Print Statement:


print("\nThat's it, just finished!")

➢ Regardless of whether the loop is terminated by break or not, the program


always prints this statement.
➢ This indicates the program has finished executing.
P. 8 of 11

Classwork 1
How about we remove the “spam” from the list, theType. That is:

forElse2.py

theType = ["ham", "eggs","nuts"]

for y in theType:
if y=="spam":
print("Please don't spam!")
break
print("The taste of %s is good!" %y)
else:
print("So lucky, there is no spam!")
print("\nThat's it, just finished!")

#Pause the screen


ch = input('')

Just like the above listing, what output do you expect to obtain?

Write your answers here:

***The answer is listed in next page. ***


P. 9 of 11

Answer: Output for code listing of forElse2.py


P. 10 of 11

Classwork 2
Try to write a Python program (forNegativeAndList.py) that contains a list with 5
random integers between -20 and 60. Then the program will use for loop to analyze
the list.

Scenario 1:
If a negative number is found in the list, the following output will be shown:

Scenario 2:
If the list only contains positive numbers, then the figure below will be shown:
P. 11 of 11

Part of the code listing in forNegativeAndList.py is provided as follows. Try to


complete the remaining code by yourself.

import random

# Create a list with 5 random and non-duplicate integers


randomNumbers = random.sample(range(-20, 61), 5)

# Print out the list for debug trace


print("This is the original list:")
print(randomNumbers)

#You may also print out the list manually


##for i in randomNumbers:
## print("%d" %i, end=" ")

print("\n--------------------------------")

# Write your code starting from here

#Pause the screen


ch = input('')

You might also like