Lab 6: Loops in Python
Exercise 1:
Write a Python program that prints all even numbers from 2 to 20 using a for loop.
Expected Output:
2 4 6 8 10 12 14 16 18 20
for n in range(2,21,2):
print(n)
Exercise 2:
Write a for loop that prints numbers from 10 down to 1 in reverse order.
Expected Output:
10 9 8 7 6 5 4 3 2 1
for n in range(10,0,-1):
print(n)
Exercise 3:
There is an error in the following code. Identify and fix it.
for i in range(5, 1):
print(i)
Hint: The loop does not print anything.
Expected Output (After Fixing):
5432
for i in range(5,1,-1):
print(i)
Exercise 4:
Write a Python program that asks the user for a number and searches for it in the
given list using a for loop. If the number is found, print "Number found!". If not,
print "Number not found!".
numbers = [10, 25, 30, 45, 50, 60, 75]
Example Run 1:
Enter a number: 45
Number found!
Example Run 2:
Enter a number: 100
Number not found!
numbers=[10,25,30,45,50,60,75]
user_input=int(input(“Enter the number you are looking for:”))
found=False
for n in numbers:
if user_input==n:
found=True
break
if found:
print(“Number found!”)
else:
print(“Number not found!”)
Exercise 5
Write a for loop to find the largest number in the list:
numbers = [45, 67, 89, 23, 10]
Expected Output:
Largest number: 89
numbers=[45,67,89,23,10]
largest=numbers[0]
for n in numbers:
if n>largest:
largest=n
print(“Largest number:”,largest)
Exercise 4: What’s Wrong Here?
Identify the error and explain how to fix it:
i=1
while i <= 5
print(i)
i = i+ 1
i=1
while i <= 5:
print(i)
i = i+ 1
Exercise 5: Off-by-One Error
The program should print numbers from 1 to 5. Why does it stop early? How
would you fix it?
n=6
while n < 5:
print(n)
n=n+1
print("Done")
n=1
while n < 5:
print(n)
n=n+1
print("Done")
Exercise 6: Infinite Loop
What is missing? Why will this cause an infinite loop?
counter = 10
while counter > 0:
print(counter)
counter+=1
Exercise 7: Guess the Number Game
Fix the logic of this program:
secret = 7
guess = -1
while guess != secret:
guess=int(input("Guess the number: ")
print("You got it!")
Exercise 8: Countdown Timer
Fix any bugs so it counts down from a number to 0:
start = int(input("Enter a starting number: "))
while start >= 0:
print(start)
start = start- 1