CS111 2020 Lab12 Loop
CS111 2020 Lab12 Loop
Labs Manual
2017/2018 Cairo University, Faculty of Computers
and Information
Lab 10 - Loops
For Loop:
While Loop:
x = 1
while True:
print ("To infinity and beyond! We're getting
close, on ", x)
x += 1
the while loop theoretically runs forever (though you can set a stopping condition)
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
Page 1 of 4
CS111: Fundamentals of CS
Labs Manual
2017/2018 Cairo University, Faculty of Computers
and Information
Loop on Lists/Strings:
For statement can be used to iterate over the elements of a sequence (such as a string, tuple or list).
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!")
Page 2 of 4
CS111: Fundamentals of CS
Labs Manual
2017/2018 Cairo University, Faculty of Computers
and Information
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:
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())
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())
count = 0
for element in array:
count = count +1
print count
Page 3 of 4
CS111: Fundamentals of CS
Labs Manual
2017/2018 Cairo University, Faculty of Computers
and Information
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)
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
Page 4 of 4