0% found this document useful (0 votes)
8 views

Lab Exercise - While Loop and For Loop

Python

Uploaded by

Momina Afzal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Lab Exercise - While Loop and For Loop

Python

Uploaded by

Momina Afzal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

Python Lab Exercise: Loops (While Loop and For Loop)

Objective:

In this lab, you will practice using two types of loops in Python: the while loop and the for loop. By
the end of the exercise, you should be comfortable writing loops to handle repetitive tasks.

Part 1: While Loop

A while loop continues to execute as long as a specified condition is True. It is commonly used
when you do not know beforehand how many iterations are required.

Example 1: Basic while loop

# Initialize counter

count = 0

# Loop until count reaches 5

while count < 5:

print("Count is:", count)

count += 1 # Increment count by 1

Explanation: This simple loop prints the value of count until it reaches 5.

Example 2: while loop with user input

# User input based while loop

password = ""

while password != "1234":

password = input("Enter the correct password: ")

print("Access granted.")

Explanation: The loop continues to prompt the user for the correct password until they enter
"1234".
Example 3: Infinite while loop (with break)

# Infinite loop with break statement

while True:

answer = input("Type 'exit' to stop: ")

if answer == "exit":

break # Exit the loop

print("Loop has stopped.")

Explanation: The loop will continue indefinitely until the user types "exit", at which point the loop
terminates using break.

Example 4: Using continue in a while loop

# Loop that skips even numbers

number = 0

while number < 10:

number += 1

if number % 2 == 0:

continue # Skip the rest of the loop for even numbers

print("Odd number:", number)

Explanation: The loop increments the number and skips over even numbers, printing only odd
numbers.

Example 5: Using a counter to limit iterations

# Loop with counter to perform a task limited times

counter = 0

while counter < 5:

print("This message will print 5 times")

counter += 1

Explanation: The loop executes exactly 5 times by controlling the counter.


Example 6: Nested while loop

# Nested while loops

i=1

while i <= 3:

j=1

while j <= 2:

print(f"i = {i}, j = {j}")

j += 1

i += 1

Explanation: This loop prints a combination of i and j values by using nested loops.

Example 7: Countdown using a while loop

# Countdown from 10 to 1

n = 10

while n > 0:

print(n)

n -= 1

print("Liftoff!")

Explanation: The loop counts down from 10 to 1, then prints "Liftoff!".

Example 8: Calculating the sum of numbers using while loop

# Sum of first 10 natural numbers

n = 10

sum_of_numbers = 0

while n > 0:

sum_of_numbers += n

n -= 1

print("Sum is:", sum_of_numbers)

Explanation: This loop calculates the sum of numbers from 1 to 10.


Example 9: while loop with a flag

# Use of a flag to stop the loop

keep_running = True

while keep_running:

choice = input("Continue? (yes/no): ")

if choice == "no":

keep_running = False

print("Loop ended.")

Explanation: A flag keep_running controls whether the loop continues or stops based on user
input.

Example 10: while loop with multiple conditions

# While loop with multiple conditions

x=0

y=5

while x < 5 and y > 0:

print(f"x = {x}, y = {y}")

x += 1

y -= 1

Explanation: The loop runs as long as both conditions (x < 5 and y > 0) are True.

Part 2: For Loop

A for loop is used to iterate over a sequence (like a list, tuple, or string) or other iterable objects.

Example 1: Basic for loop with a range

# Loop over a range of numbers

for i in range(5):

print("Number:", i)

Explanation: This loop prints numbers from 0 to 4 using the range() function.
Example 2: Iterating over a list

# List iteration

fruits = ["apple", "banana", "cherry"]

for fruit in fruits:

print(fruit)

Explanation: This loop iterates over a list of fruits and prints each one.

Example 3: Iterating over a string

# Loop over characters in a string

for char in "Python":

print(char)

Explanation: The loop prints each character in the string "Python".

Example 4: Iterating with index using enumerate()

# Loop with index

colors = ["red", "green", "blue"]

for index, color in enumerate(colors):

print(f"Color {index} is {color}")

Explanation: enumerate() provides both the index and the value of the list elements.

Example 5: Looping through a dictionary

# Dictionary iteration

ages = {"John": 25, "Jane": 30, "Doe": 22}

for name, age in ages.items():

print(f"{name} is {age} years old")

Explanation: This loop iterates over the key-value pairs of a dictionary.


Example 6: Using break in a for loop

# Break example

for number in range(1, 10):

if number == 5:

break # Exit the loop when number is 5

print(number)

Explanation: The loop stops when the number reaches 5 due to the break statement.

Example 7: Using continue in a for loop

# Continue example

for number in range(1, 10):

if number % 2 == 0:

continue # Skip even numbers

print(number)

Explanation: The loop skips even numbers and prints only the odd ones.

Example 8: Nested for loop

# Nested for loops to print multiplication table

for i in range(1, 4):

for j in range(1, 4):

print(f"{i} * {j} = {i * j}")

Explanation: This nested loop prints the multiplication table for numbers 1 through 3.

Example 9: Looping over a range with a step

# Loop with step

for i in range(0, 10, 2):

print(i)

Explanation: The loop prints numbers from 0 to 8 with a step of 2.


Example 10: List comprehension (advanced)

# List comprehension to square numbers

squares = [x ** 2 for x in range(1, 6)]

print(squares)

Explanation: This uses a for loop in list comprehension to generate a list of squares of numbers
from 1 to 5.

Summary:

• While Loops: Use when the number of iterations is not known beforehand or depends on a
condition.

• For Loops: Use to iterate over sequences or when the number of iterations is known.

This lab provides you with several examples, ranging from beginner to intermediate level, allowing
you to understand loops in various contexts. Feel free to modify the examples and experiment with
different conditions.

You might also like