CS111: Fundamentals of CS
Labs Manual
2022/2023
Lab 6 – Loops and Problem Solving
For / While Loops:
● For loops are traditionally used when you have a piece of code which you want to repeat n number of
times. As an alternative, there is the While Loop, however, while is used when a condition is to be met,
or if you want a piece of code to repeat forever, for example
For Loop:
for x in range(0, 3):
print ("We're on ", x)
● The for loop runs for a fixed amount - in this case, 3
● Note that the index of the loop "x" goes from 0 to 2 to count its 3 times)
While Loop:
x = 1
while True:
print ("To infinity and beyond! We're getting close, on ", x)
x += 1
● The while loop runs as long as a condition is valid (true)
● Example: Invent a loop that prints all numbers starting from
certain positive integer until it reaches zero
x = 5
while x > 0:
print (x)
x = x – 1
Loop on Lists/Strings:
● For statement can be used to iterate over the elements of a
sequence (such as a string, tuple or list).
string = "Hello World"
for x in string:
print (x)
● Example: Invent a loop that calculates the summation of a list of integers
5 of 1 Page
CS111: Fundamentals of CS
Labs Manual
2022/2023
myList = [1, 1, 2, 3, 5, 8, 13, 21]
sum = 0
for element in myList:
sum = sum + element
print (sum)
Early Exit:
● Python includes statements to exit a loop (for/ while). To exit a loop, use the break statement.
for x in range(3):
print (x)
if x == 1:
break
● Example: Invent a loop that will search a list until it finds a certain number then print "found",
otherwise it prints " Not found"
myList = [5, 2, 10, 3, 70]
target = 10
found = False
for num in myList:
if num == target:
found = True
break
if found:
print ("Target found!")
else:
print ("Target not found!")
Continue Statement:
● The continue statement continues with the next iteration of the loop. It can be used for both (for/while)
loops
● Example: This loop will print only the even numbers in a list of integers:
myList = [5, 2, 10, 3, 70]
for num in myList:
if num % 2 == 1: # if the number is odd just continue to
continue # the next number
print (num) # else print the even number
Functions:
● A function is an independent algorithm that is implemented and given a name
5 of 2 Page
CS111: Fundamentals of CS
Labs Manual
2022/2023
● Example of Python library functions are: randint and sqrt
● To use Python library (Ready-made) functions, you need to import the library where the function is
defined, e.g. this code will print 10 random numbers between 1 and 10. You need to understand how
many parameters and of what type a function needs. For example randint needs to integer values
representing the range that you want random numbers in. Writing randint(1, 3.5) is wrong.
import random
for i in range (11):
print (random.randint(1,10))
● Using def keyword, you can also define your own function that makes a specific task define how many
and what parameters you like to pass to the function and what value you expect the function to return.
For example, this is a user-defined function that return true if a number is even.
def isEven (n):
if n % 2 == 0:
return True
else:
return False
● Now you can use this function in your program as follows:
n = int(input("Pls enter a number to check if even or odd: "))
print ("It is even = ", isEven (n))
● The program using the function is responsible of sending the correct number and correct order and tyes
of parameters needed by the function. For example, these calls will be wrong:
print (isEven("Not number"))
print (isEven([1,2,3]))
5 of 3 Page
CS111: Fundamentals of CS
Labs Manual
2022/2023
Problems:
1- Write a program that counts the number of positive numbers and the number of even numbers in a list.
Input: [2, 1, -9, 5, 6, -3, 8] Output:
Number of positive numbers = 5
Number of even numbers = 3
array = list(input()) or array=[int(x) for x in input().split()]
positiveCount = 0
evenCount = 0
for element in array:
if element%2 == 0:
evenCount = evenCount+1
if element > 0:
positiveCount = positiveCount+1
print evenCount
print positiveCount
2- Write a program that prints the length of a list without using the len() function.
Input: [2, 1, -9, 0, 6, -3, 8] Output: length = 7
array = list(input()) or array=[int(x) for x in input().split()]
count = 0
for element in array:
count = count +1
print count
3- Extend Last lab practice of students' grades to print the grade of N students, where you will get N from the
user.
n = input()
while n > 0:
score = int(input("Enter Your Grade"))
if score >= 90:
letter = 'A'
elif score >= 80:
letter = 'B'
elif score >= 70:
letter = 'C'
elif score >= 60:
letter = 'D'
else:
letter = 'F'
print (letter)
5 of 4 Page
CS111: Fundamentals of CS
Labs Manual
2022/2023
n -= 1
4- Given a string and a non-negative int n, return a larger string that is n copies of the original string
n = input()
str = input()
count = 0
result = ""
while count < n:
result += str
count += 1
print result
5- Define and test a function to calculate the first n Fibonacci numbers, where the first two numbers are 0 and
1 and each next number is the sum of the previous two. So, the first 10 Fibonacci numbers are: 0, 1, 1, 2, 3,
5, 8, 13, 21, 34.
def fib(n): # write the first n Fibonacci numbers
a, b = 0, 1 # local variables
for i in range (n + 1):
print(a, end = ' ')
a, b = b, a + b
print()
6- Define and test a function that takes a list and prints the maximum value in this list. Do not use any build-in
or ready-made functions.
def max_list (lst):
m = lst[0]
for i in lst:
if i > m:
m = i
print ("max is ", m)
max_list ([1,4,2,45,3,5,35,533])
5 of 5 Page