0% found this document useful (0 votes)
2 views27 pages

Python Lesson 4a Notes - Updated 1

This document provides an overview of looping in Python, focusing on the 'for' loop and the 'range()' function, along with practical examples and classwork assignments. It also covers the creation and manipulation of lists, including simple and nested lists, and demonstrates how to iterate through them. The document includes elaborations on specific Python scripts that illustrate these concepts in action.

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)
2 views27 pages

Python Lesson 4a Notes - Updated 1

This document provides an overview of looping in Python, focusing on the 'for' loop and the 'range()' function, along with practical examples and classwork assignments. It also covers the creation and manipulation of lists, including simple and nested lists, and demonstrates how to iterate through them. The document includes elaborations on specific Python scripts that illustrate these concepts in action.

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
You are on page 1/ 27

P.

1 of 27

Contents

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


for loop example – relate to the range() function ................................................. 2
Elaboration of forAndrange.py ...................................................................... 5
Classwork 1 ............................................................................................................ 7
Classwork 2 ............................................................................................................ 8
Classwork 3 ............................................................................................................ 9
Elaboration of forAsteriskFromUser - with boolean validation.py .............. 12
Python List.................................................................................................................... 15
Elaboration of simpleList.py ................................................................................. 17
List with different type of items ........................................................................... 19
Elaborate list by diagram ............................................................................. 22
Elaboration of printListInReport.py ............................................................. 23
P. 2 of 27

Looping in Python – Part 2a


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 – relate to the range()


function
The built-in function range() is the right function to iterate over a sequence of
numbers. It generates an iterator of arithmetic progressions.

range(n) generates an iterator to progress the integer numbers starting with 0 and
ending with (n -1).

range() can also be called with 2 arguments:

range(begin,end)

The above call produces the list iterator of numbers starting with begin (inclusive)
and ending with 1 less than the number "end".

The above calling of range() has set increment as 1 by default. We, however, can
specify a different increment with a third argument. The increment is called the
"step". It can be both negative and positive, but not zero. That is:

range(begin, end, step)


P. 3 of 27

With a view to further elaborate the 3 kinds of usage about range( ) function, you
can refer to the program (forAndrange.py) as shown below:

for x in range(8):
print(" %d" %x)

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

for y in range(1,8):
print(" %d" %y)

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

for z in range(1,8, 3):


print(" %d" %z)

#Pause the screen


ch = input('')
P. 4 of 27

The output of the program should be:


P. 5 of 27

Elaboration of forAndrange.py
1. First for Loop
for x in range(8):
print(" %d" % x)

➢ range(8):
✓ Generates numbers from 0 to 7 (exclusive of 8).
✓ Sequence: [0, 1, 2, 3, 4, 5, 6, 7].

➢ The loop iterates over these numbers, and each number is printed with two
spaces of indentation.

Output:

2. Second for Loop


for y in range(1, 8):
print(" %d" % y)

➢ range(1, 8):
✓ Generates numbers from 1 to 7 (exclusive of 8).
✓ Sequence: [1, 2, 3, 4, 5, 6, 7].

➢ The loop iterates over this sequence, printing each number with two spaces of
indentation.
P. 6 of 27

Output:

3. Third for Loop


for z in range(1, 8, 3):
print(" %d" % z)

➢ range(1, 8, 3):
✓ Generates numbers starting from 1, stopping before 8, with a step size of 3.
✓ Sequence: [1, 4, 7].

➢ The loop iterates over this sequence, printing each number with two spaces of
indentation.

Output:
P. 7 of 27

Classwork 1
Try to use for loop and range( ) function to write a Python program
(forAndrangeCW1.py) so that it can produce the following output on the console:
P. 8 of 27

Classwork 2
Try to write a Python prgram (forAsteriskFromUser.py) that will request user to input
a number as row number of printing asterisks(*) on screen.

The mode of printing is print 1 asterisk on row 1 and 2 asterisks on row 2 and so forth.
Please refer to the following figure for reference:
P. 9 of 27

Classwork 3
This time, modify the above program to forAsteriskFromUser - with normal
validation.py. In this program, you have to apply the following 3 rules of validation
before printing the asterisks on SHELL.

1. User should not input 0 as row number


2. User should not input a negative number as row number
3. User should not input a row number larger than 10

You may take the figure below for your reference:


P. 10 of 27

As a matter of fact, we can further modify program forAsteriskFromUser - with


normal validation.py to forAsteriskFromUser - with boolean validation.py.

Refer to the code of forAsteriskFromUser - with boolean validation.py, it produces


the same output as forAsteriskFromUser - with normal validation.py. The only
difference is using Boolean type variable in conditional statement will make the logic
present in a more semantic way.

Code listing of forAsteriskFromUser - with boolean validation.py:

# flag is a variable of Boolean type


# A boolean type variable can only take True or False as its value
flag=False

while not flag:


rows=int(input("Please tell me the no. of rows you would like to print
-> "))

if rows==0:
print("Sorry, you cannot input 0 as row number !\n")
continue

elif rows<0:
print("Sorry, you cannot input negative integer as row number !\n")
continue

elif rows>10:
print("Sorry, you cannot input a row number bigger than 10 !\n")
continue

flag=True

print()
P. 11 of 27

else:
for x in range(1, rows+1):
for y in range(1, x+1):
print ("*", end="")
print("")

#Pause the screen


ch = input('')
P. 12 of 27

Elaboration of forAsteriskFromUser - with boolean

validation.py
1. Boolean Variable flag
flag = False

➢ The variable flag is initialized to False:


➢ This variable controls the execution of the while loop.
➢ The loop continues to execute as long as flag is False.

2. while Loop
while not flag:

➢ The while loop runs until flag is set to True.


➢ The condition not flag evaluates to True because flag is initially False.

3. Input for Number of Rows


rows = int(input("Please tell me the no. of rows you would
like to print -> "))

➢ The program prompts the user to input the number of rows (rows) they want
to print.
➢ The input() function collects the user input as a string, and int() converts it
into an integer.
P. 13 of 27

4. Input Validation
The program validates the user input with a series of if-elif conditions:
I. If rows == 0:

if rows == 0:
print("Sorry, you cannot input 0 as row number !\n")
continue

➢ If the user enters 0, the program displays an error message and skips
to the next iteration of the loop using continue.

II. If rows < 0:

elif rows < 0:


print("Sorry, you cannot input negative integer as row
number !\n")
continue

➢ If the user enters a negative number, the program displays an error


message and skips to the next iteration of the loop.

III. If rows > 10:

elif rows > 10:


print("Sorry, you cannot input a row number bigger than 10 !\n")
continue

➢ If the user enters a number greater than 10, the program displays an
error message and skips to the next iteration of the loop.

IV. If Input is Valid:

flag = True

➢ If the user's input passes all the conditions (i.e., rows is between 1 and
10), the program sets flag = True, which terminates the loop.
P. 14 of 27

5. else Block of the while Loop


else:
for x in range(1, rows + 1):
for y in range(1, x + 1):
print("*", end="")
print("")

➢ The else block of the while loop executes only when the loop terminates
normally (i.e., without a break statement).

6. Printing a Pattern
Inside the else block, a nested for loop is used to print a triangular pattern of stars
(*):

I. Outer Loop:
for x in range(1, rows + 1):

➢ The outer loop iterates over row numbers from 1 to rows (inclusive).
➢ For example, if rows = 3, x will take the values 1, 2, and 3.

II. Inner Loop:


for y in range(1, x + 1):
print("*", end="")

➢ The inner loop controls how many stars (*) are printed in each row.
➢ For each row x, the inner loop runs from 1 to x (inclusive), printing x
stars.

III. Newline:
print("")

➢ After printing all stars in a row, a newline (\n) is printed to move to the
next row.
P. 15 of 27

Python List
Lists are very similar to arrays. They can contain any type of variable, and contain as
many variables as you wish. Lists can also be iterated over in a very simple manner.
Here is an example of how to build a list with number 10, 15 and 20 as its items.

simpleList.py

# Create an empty list first


theList =[]

# Create the list by using function append()


theList.append(10)
theList.append(15)
theList.append(20)

# Print out the list by using index


print("Print the list by using index:")
print(theList[0])
print(theList[1])
print(theList[2])

print("")

# Print out the list by using for loop


print("Print the list by using for loop:")
for x in theList:
print(x)

# Pause the screen


ch = input('')
P. 16 of 27

The output will be like this:

You may refer to the following diagram for better understanding of list.

theList
index 0 1 2
value 10 15 20

print(x)
P. 17 of 27

Elaboration of simpleList.py
1. Create an Empty List
theList = []

➢ The variable theList is initialized as an empty list.


➢ Lists in Python are mutable, meaning you can add, remove, or modify
elements after creation.
➢ At this point, theList contains no elements:

2. Add Elements to the List Using append()


theList.append(10)
theList.append(15)
theList.append(20)

➢ append() Method: Adds a new element to the end of the list.


➢ The following elements are added to theList in sequence:
✓ 10
✓ 15
✓ 20
➢ After these operations, the list becomes:
theList = [10, 15, 20]

3. Print the List Using Indexing


print("Print the list by using index:")
print(theList[0])
print(theList[1])
print(theList[2])

➢ Indexing: Access individual elements in the list using their index.


✓ Indexing in Python starts at 0.
✓ theList[0] → First element (10)
✓ theList[1] → Second element (15)
✓ theList[2] → Third element (20)
P. 18 of 27

➢ The program prints each element using its index.

4. Print the List Using a for Loop


print("Print the list by using for loop:")
for x in theList:
print(x)

➢ for Loop: Iterates over each element in the list.


➢ The variable x takes the value of each element in theList during each
iteration:
✓ First iteration: x = 10
✓ Second iteration: x = 15
✓ Third iteration: x = 20
➢ The program prints each element as it is iterated:
P. 19 of 27

List with different type of items


Sometimes, a list can be written by adding comma-separated values (items) between
square brackets. Another good news is that items in a list need not all have the same
type.

On top of this, we may also see the following example…

printListInReport.py

list1=["Muteki", "Engineer", 31]

for x in range(0,len(list1)):
print(list1[x])

print("")

#This is a complex list


list2=[["Muteki", "Engineer", 31], ["Bibi", "Programmer", 28]]

print("")

for y in range(0, len(list2)):


print(list2[y])

print()
print()

print("******* Print the list in report mode: *******\n")

print()
print()

print("There are %d persons data in the list.\n" %len(list2))


P. 20 of 27

for k in range(0, len(list2)):


i=0
print("Person ", k+1)
print("\tName: ", list2[k][i])
i+=1
print("\tOccupation: ", list2[k][i])
i+=1
print("\tAge: ", list2[k][i])
print("")

#Pause the screen


ch = input('')
P. 21 of 27

If you run the above program, you should get output as follows:
P. 22 of 27

Elaborate list by diagram


Sometimes, you may draw some simple diagrams to help yourself get easy to realize
the structure of list.

For example, the diagrams below illustrate the structure of the lists defined in the
above Python program.

list1
index 0 1 2
value “Muteki” “Engineer” 31

list2
k 0 1
“Muteki” “Engineer” 31 “Bibi” “Programmer” 28
i 0 1 2 0 1 2
P. 23 of 27

Elaboration of printListInReport.py
This Python code demonstrates working with lists in Python, including simple lists,
nested lists, and how to extract and display data from such structures.

1. Simple List Iteration


list1 = ["Muteki", "Engineer", 31]

for x in range(0, len(list1)):


print(list1[x])

➢ What is list1:
✓ list1 is a simple list containing three elements:
 "Muteki": String representing a name.
 "Engineer": String representing an occupation.
 31: Integer representing an age.

➢ How the Loop Works:


✓ The for loop iterates over the indices of list1 using range(0, len(list1)).
✓ len(list1) is 3, so the loop runs from 0 to 2.

➢ Output:
✓ The loop prints each element of the list:
P. 24 of 27

2. Printing a Complex (Nested) List


list2 = [["Muteki", "Engineer", 31], ["Bibi", "Programmer",
28]]

for y in range(0, len(list2)):


print(list2[y])

➢ What is list2:
✓ list2 is a nested list (a list containing other lists as elements):

[
["Muteki", "Engineer", 31],
["Bibi", "Programmer", 28]
]

✓ Each sublist represents a person's data:


 First sublist: ["Muteki", "Engineer", 31] (Name, Occupation,
Age)
 Second sublist: ["Bibi", "Programmer", 28] (Name, Occupation,
Age)

➢ How the Loop Works:


✓ The for loop iterates over the indices of list2 using range(0, len(list2)).
✓ len(list2) is 2, so the loop runs from 0 to 1.

➢ Output:
✓ Each sublist is printed as a whole:
P. 25 of 27

3. Report Mode
print("******* Print the list in report mode: *******\n")

➢ This section organizes and prints the data from list2 in a structured "report"
format.

4. Reporting the Total Number of Persons


print("There are %d persons data in the list.\n" % len(list2))

➢ len(list2):
✓ Calculates the number of sublists in list2, which corresponds to the
number of persons.
✓ For list2 = [["Muteki", "Engineer", 31], ["Bibi", "Programmer", 28]],
len(list2) is 2.
➢ Output:
P. 26 of 27

5. Printing Each Person's Data

for k in range(0, len(list2)):


i = 0
print("Person ", k+1)
print("\tName: ", list2[k][i])
i += 1
print("\tOccupation: ", list2[k][i])
i += 1
print("\tAge: ", list2[k][i])
print("")

➢ How the Outer Loop Works:


✓ The for loop iterates over the indices of list2 (0 to len(list2)-1).
✓ k represents the index of the current person in the list.

➢ How the Inner Logic Works:


✓ Accessing Sublist:
list2[k]

 Retrieves the sublist at index k (e.g., list2[0] is ["Muteki",


"Engineer", 31]).

✓ Accessing Individual Data:


 list2[k][i] retrieves elements from the sublist based on the
index i:
 i = 0 → Name
 i = 1 → Occupation
 i = 2 → Age
 The variable i is incremented after each piece of data is
printed.
P. 27 of 27

➢ Output (Formatted Report):


✓ The data for each person is printed in a structured format:

You might also like