Programming Essential Course
Iteration or Looping
● Most useful and powerful structure
● Allows the repetition of instructions
or statements for a certain number
of times in the loop body
Python Loops
Python has two primitive loop commands:
• while loop
• for loop
- In
- Range
while Loop
Syntax: Sentinel
initialization Parts of while loop
while condition:
statement(s)
incrementation/decrementation initialization – Assigning initial value to a
variable
i=1 condition – Statement evaluated to either
while i <= 5: true or false
print(i) incrementation – Increasing the value of the
i+=1 # i = i + 1 variable
Output decrementation – Decreasing the value of
the variable
i=1
Desk Check Table
while i <= 5:
print(i, end = “ ”) i i <= 5
i = i+1 1 True
2 True
Output 3 True
12345 4 True
5 True
Sentinel 6 False
The break Statement
The break statement can stop the loop
Desk Check Table
even if the while condition is true
i=1 i i <= 5 i == 3
while i <= 5: 1 true false
print(i) 2 true false
if i == 3: 3 True true
break
i = i+1
Output
1
2
3
The continue Statement
The continue statement can stop the current iteration,
Desk Check Table
and continue with the next
i=0 i i<5 i i == 3
while i < 5: 0 true 1 false
i = i+1 1 true 2 false
if i == 3: 2 true 3 true
continue 3 true 4 false
print(i) 4 true 5 false
5 false
Output
1
2
4
5
Day 2 Exercise
Write a program using while loop that displays the following output
on the screen:
5x1=5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50
s = int(input("Enter side: "))
i=1
while i <= (s*s):
if i%s==0:
print("*")
else:
print("*",end=" ")
i+=1
n = int(input("Enter side: "))
i=1
while i <= n:
j=1
while j <= n:
print("*",end=" ")
j+=1
print()
i+=1
Exercise
Write a program using while loop that will accept an integer
value. The program will compute the summation of the
consecutive numbers from 1 up to the inputted value.
Example Run:
Enter an integer: 5
Summation is 15
Computation: 1+2+3+4+5
Exercise
Write a program using while loop that will accept an integer
value. The program will compute the factorial of the
consecutive numbers from 1 up to the inputted value.
Example Run:
Enter an integer: 5
Factorial is
Computation: 1*2*3*4*5
n = int(input("Enter a number: ")) # example number = 5
i = 1 # counter variable i
s = 0 # summation variable
while i <= n:
s = s + i # accumulation statement
i = i + 1 # incrementation statement
print(f"Summation is {s}")
Exercise
Write a program using while loop that will accept an integer value. The
program will compute the factorial of the
consecutive numbers from 1 up to the inputted value. The program will also
employ indefinite loop .
Example Run:
---------------------------------------------------------------------------
Enter an integer: 5
Factorial is 120 ---- 1 * 2 * 3 * 4 * 5
Do you want to try it again?
---------------------------------------------------
if Y/y (Yes), the program will repeat the process asking the user to enter an integer
If N/n (No), the program will display thank you and will exit.
Exercise
Write a program that accepts two integers. The program should
determine if the sum of the two integers is even or odd.
1. The program will prompt the user to enter first integer and second integer
2. The program will display
“The sum of two integers is Even” or “The sum of two integers is Odd”
Example:
Enter first number: 3
Enter second number: 2
The sum of two integers is Odd
------------------------------------------------------------------------------------------------------------------
3. The program will ask if the user wants to try again. The user will input Y/y if Yes and
N/n if No
4. If Yes, it will repeat the process in Step 1.
5. If No, the program will display “Thank you!” and will exit.
Python Collections
- List is a collection which is ordered and changeable.
Allows duplicate members.
- Tuple is a collection which is ordered and unchangeable.
Allows duplicate members.
- Set is a collection which is unordered and unindexed.
No duplicate members.
- Dictionary is a collection which is unordered and changeable.
No duplicate members.
Python Lists
is a collection which is ordered and changeable. Allows
duplicate members.
Lists are used to store multiple items in a single
variable.
list = [ "chess", "basketball", "badminton“, 20, 30.45 ]
print(list)
list = [ "chess", "basketball", "badminton“, “chess” ]
print(list)
Defining a List
Use a list() constructor to create a list
Output
mylist = list() []
print(mylist)
mylist = list( (“ford”, “toyota”) ) [ ‘ford’ , ‘toyota’ ]
print(mylist)
mylist = list( “ford” )
[ ‘f’ , ‘o’ , ‘r’ , ‘d’ ]
print(mylist)
mylist = list(“a”) [ ‘a’]
print(mylist)
Accessing List items
list = [ "chess", "basketball", "badminton" ]
print( list[0] )
Output: chess
Negative Indexing
Negative indexing refers to the last item in the list
Example:
-1 refers to the last item, -2 refers to the second last item
list = ["apple", "grapes" , "banana", "avocado"] list = ["apple", "grapes" , "banana", "avocado"]
print( list[-1] ) print( list[-2] )
Output: avocado Output: banana
Appending an Item
Adding an item to the end of the list, use the append() method:
list = [ "chess", "basketball", "badminton" ]
list.append(“orange")
print( list )
Output:
[ "chess", "basketball" , "badminton" , “orange" ]
Inserting an Item
Inserting an item at the specified index, use the insert() method:
list = [ "chess", "basketball", "badminton" ]
list.insert(1,“orange")
print( list )
Output:
[ "chess", "orange" , "basketball" , "badminton" ]
Changing value in a list
male = [“John” , “Mike”]
male[0] = “Kenny”
print(male[0])
Output:
Kenny
Removing Specified Item
remove() method removes the specified item.
list = [ "chess", "basketball", "badminton" ]
list.remove(“chess")
print( list )
Output:
[ "basketball" , "badminton" ]
Removing Specified Index
pop() method removes the specified index.
list = [ "chess", "basketball", "badminton" ]
list.pop(2)
print( list )
Output:
[ "chess", "basketball" ]
Clearing the List
clear() method empties the list.
list = [ "chess", "basketball", "badminton" ]
list.clear()
print( list )
Output:
[]
Methods to control list and its objects
fruits = [
["apple","avocado","banana"],
["kiwi","cherry","grapes"]
]
print(fruits[0][1])
print(fruits[1][2])
Using reverse()
Arranging object in a list
numList = [20, 2, 33, 42, 25]
numList.reverse()
Using sort()
print(numList)
numList = [20, 2, 33, 42, 25] Output
[25, 42, 33, 2, 20]
numList.sort()
print(numList)
Using sort() and
reverse()
numList = [20, 2, 33, 42, 25]
Output in ascending order numList.sort()
[2, 20, 25, 33, 42]
numlist.reverse()
print(numList)
Output in descending order
[42, 33, 25, 20, 2]
for Loop
A for loop is used for iterating over a sequence
(list, tuple, dictionary, set, string).
fruits = ["apple", "banana", “avocado"]
for x in fruits:
print(x)
Output:
apple
banana
avocado
Looping through a String
for x in “apple”:
print(x, end=“ \t ”)
Output:
a p p l e
The range() Function
To loop through a set of code a specified number of times
for x in range(6): fruits = ['apple', 'banana', "orange"]
print(x, end=“ ”) for x in range(len(fruits)-1):
Output: print(fruits[x])
012345
Output:
for x in range(1, 6): apple
print(x) banana
Output:
1
2
3
4
5
Write a word bank program using Python List
1. The program should prompt the user to enter a word
2. The program will store the word in the list
3. The program will ask if the user wants to try again. The user will input Y/y if Yes and
N/n if No
4. If Yes, repeat the process in Step 1.
5. If No, Display the all the words in the list and the number of frequency of the last
item inside the list.
apple
Use these methods/ control structures cherry
word = list() banana
append() grapes
len() and count()
apple
for loop to iterate the list items or display all the items
while loop
kiwi
if/else apple
grapes orange apple
def delete(): #
global fruits
for f in fruits:
if f == item:
fruits.delete(item)
delete()
Tuple
Tuples are used to store multiple items in a single variable.
A tuple is a collection which is ordered and unchangeable.
Tuples are written with round brackets.
fruits = ("apple", "banana", “avocado") digit = (0, 1, 2, 3)
print(fruits) print(digit)
Output: Output:
('apple', 'banana', ‘avocado') (0, 1, 2, 3)
Defining a Tuple
Tuple items are indexed, unchangeable, and allow duplicate values.
Use a tuple() constructor to create a tuple.
Output
mytuple = tuple() ()
print(mytuple)
mytuple= tuple((“apple”, “banana”)) ( ‘apple’ , ‘banana’ )
print(mytuple)
mytuple = tuple(“apple”)
( ‘a’ , ‘p’ , ‘p’ , ‘l’ , ‘e’ )
print(mytuple)
mytuple = tuple(“a”) ( ‘a’)
print(mytuple)
Accessing Tuple items
tuple = ( "chess", "basketball", "badminton" )
print( tuple[0] )
Output: chess
Negative Indexing
Negative indexing refers to the last item in the list
Example:
-1 refers to the last item, -2 refers to the second last item
tuple = ("apple", "grapes" , "banana", "avocado”) tuple = ( "apple", "grapes" , "banana", "avocado" )
print( tuple[-1] ) print( tuple[-2] )
Output: avocado Output: banana
Useful Tuple Functions
Function name Description
len(t) Gives the total length of the tuple.
max(t) Returns item from the tuple with max value.
min(t) Returns item from the tuple with min value.
tuple(l) Converts a list into tuple.
list(t) Converts a tuple into list.
del t Delete tuple
+ Concatenate Tuple
in Checks if value exist in tuple
Python Set
Sets are used to store multiple items in a single variable.
A set is a collection which is both unordered and unindexed.
thisset = {"apple", "banana", “avocado"}
print(thisset)
Output:
{‘apple', 'banana', ‘avocado’}
{‘banana', ‘avocado’, ‘apple’}
Access Items
You cannot access items in a set by referring to an index
or a key.
thisset = {"apple", "banana", “avocado"}
for x in thisset:
print(x)
Output:
banana
apple
cherry
Add Items
Once a set is created, you cannot change its items, but you can
add new items.
thisset = {"apple", "banana", “avocado"}
thisset.add("orange")
print(thisset)
Output:
{'banana', 'orange', ‘avocado', 'apple'}
Remove Item
To remove an item in a set, use the remove(), or the discard() method.
thisset = {"apple", "banana", “orange"}
thisset.discard("banana")
print(thisset)
thisset = {"apple", "banana", “orange"}
thisset.remove("banana")
print(thisset)
Dictionary
Dictionaries are used to store data values in key:value pairs.
A dictionary is a collection which is unordered, changeable and does not
allow duplicates.
dict = {
"brand": “Toyota” ,
"model": “Fortuner”,
"year": 2020
}
print(dict)
Output:
{'brand': ‘Toyota', 'model': ‘Fortuner', 'year’: 2020}
Print the "brand" value of the dictionary:
dict = {
"brand": “Toyota",
"model": “Fortuner",
"year": 2020
}
print(dict["brand"])
Output:
Toyota
Duplicates Not Allowed
Dictionaries cannot have two items with the same key:
dict = {
"brand": “Toyota",
"model": “Fortuner",
"year": 2020,
"year": 2021
}
print(dict)
Output:
{'brand': ‘Toyota', 'model': ‘Fortuner', 'year': 2021}
Dictionary Length
To determine how many items a dictionary has, use the len() function:
dict = {
"brand": “Toyota",
"model": “Fortuner",
"year": 2020
}
print(len(dict))
Output:
3
Change Values
You can change the value of a specific item by referring to its key name:
dict = {
"brand": “Toyota",
"model": “Fortuner",
"year": 2020
}
dict["year"] = 2021
print(dict["year"])
Output:
2021
Update Dictionary
The update() method will update the dictionary with the
items from the given argument.
The argument must be a dictionary, or an iterable object
with key:value pairs.
dict = {
"brand": “Toyota",
"model": “Fortuner",
"year": 2020
}
dict.update( {"year": 2021} )
print(dict["year"])
Output:
2021
Adding Items
Adding an item to the dictionary is done by using a new index key and
assigning a value to it:
dict = {
"brand": “Toyota",
"model": “Fortuner",
"year": 2020
}
dict["color"] = “White"
print(dict)
Output:
{'brand': ‘Toyota', 'model': ‘Fortuner', 'year’: 2020, 'color’: ‘White'}
Removing Items
There are several methods to remove items from a dictionary:
pop()
del
dict = { dict = {
"brand": “Toyota", "brand": “Toyota",
"model": “Fortuner", "model": “Fortuner",
"year": 2020 "year": 2020
} }
dict.pop("model") del dict["model"]
print(dict) print(dict)
Output: Output:
{'brand': ‘Toyota', 'year’: 2020} {'brand': ‘Toyota', 'year’: 2020}
Loop Through a Dictionary
You can loop through a dictionary by using a for loop.
Print all key names in the dictionary, Print all values in the dictionary,
one by one: one by one:
dict = { dict = {
"brand": “Toyota", "brand": “Toyota",
"model": “Fortuner", "model": “Fortuner",
"year": 2020 "year": 2020
} }
for x in dict: for x in dict:
print(x) print(dict[x])
Output: Output:
brand Toyota
model Fortuner
year 2020
Function
- A function is a block of organized, reusable code that is used to perform a
single, related action.
No parameter(s)/argument(s), no returning value No parameter(s)/argument(s), with returning value
def sum():
def greeting():
s = 3+5
print("Hello")
return s
greeting() # function call
print( sum() )
With parameter(s)/argument(s), no returning value
def factorial(n): # n --- >parameter(receiver)
i=1
f=1
while i <= n:
f *= i
i += 1
print(f"Factorial of {n} is {f}")
factorial(5) # functional call ---> 4--->argument
With parameter(s)/argument(s), no returning value
def summation(n):
i=1
s=0
while i <= n:
s += i
i += 1
return s
number = int(input("Enter a number: "))
print(f"The summation of {number} is {summation(number)}")