Python Lesson 4a Notes - Updated 1
Python Lesson 4a Notes - Updated 1
1 of 27
Contents
range(n) generates an iterator to progress the integer numbers starting with 0 and
ending with (n -1).
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:
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")
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:
➢ 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:
➢ 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.
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("")
validation.py
1. Boolean Variable flag
flag = False
2. while Loop
while not flag:
➢ 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.
➢ If the user enters a number greater than 10, the program displays an
error message and skips to the next iteration of the loop.
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
➢ 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.
➢ 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
print("")
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 = []
printListInReport.py
for x in range(0,len(list1)):
print(list1[x])
print("")
print("")
print()
print()
print()
print()
If you run the above program, you should get output as follows:
P. 22 of 27
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.
➢ 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.
➢ Output:
✓ The loop prints each element of the list:
P. 24 of 27
➢ What is list2:
✓ list2 is a nested list (a list containing other lists as elements):
[
["Muteki", "Engineer", 31],
["Bibi", "Programmer", 28]
]
➢ 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.
➢ 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