Lab Exercise: Learning while Loop in Python
Objective:
Learn to use while loops in Python to perform repetitive tasks.
1. Example 1: Simple Counter
Description:
Use a while loop to print numbers from 1 to 5.
Code Sample:
count = 1
while count <= 5:
print(count)
count += 1
Explanation:
• Initialization: count is initialized to 1.
• Condition: The loop runs as long as count is less than or equal to 5.
• Update: count is incremented by 1 in each iteration.
2. Example 2: Sum of Natural Numbers
Description:
Use a while loop to calculate the sum of the first 10 natural numbers.
Code Sample:
n = 10
sum = 0
i=1
while i <= n:
sum += i
i += 1
print(f"The sum of the first {n} natural numbers is: {sum}")
Explanation:
• Initialization: sum is initialized to 0 and i to 1.
• Condition: The loop runs until i is greater than n.
• Update: i is incremented by 1 and added to sum in each iteration.
3. Example 3: Factorial Calculation
Description:
Use a while loop to calculate the factorial of a given number.
Code Sample:
num = 5
factorial = 1
i=1
while i <= num:
factorial *= i
i += 1
print(f"The factorial of {num} is: {factorial}")
Explanation:
• Initialization: factorial is initialized to 1 and i to 1.
• Condition: The loop runs until i is greater than num.
• Update: i is incremented by 1 and multiplied with factorial in each iteration.
4. Example 4: User Input Validation
Description:
Use a while loop to repeatedly ask for user input until a valid number is entered.
Code Sample:
while True:
num = input("Enter a number: ")
try:
num = int(num)
break
except ValueError:
print("Invalid input. Please enter a valid number.")
print(f"You entered the number: {num}")
Explanation:
• Condition: The loop runs indefinitely (while True).
• Input & Validation: The input is attempted to be converted to an integer. If successful, the l
oop breaks. Otherwise, an error message is printed.
5. Example 5: Guess the Number Game
Description:
Use a while loop to create a simple number-
guessing game where the user has to guess a randomly generated number.
Code Sample:
import random
target = random.randint(1, 100)
guess = None
while guess != target:
guess = int(input("Guess the number (between 1 and 100): "))
if guess < target:
print("Too low!")
elif guess > target:
print("Too high!")
else:
print("Congratulations! You guessed the number.")
Explanation:
• Initialization: target is set to a random number between 1 and 100, guess starts as None.
• Condition: The loop runs until guess equals target.
• Feedback: The user is prompted to guess, and feedback is provided on whether the guess i
s too low, too high, or correct.
Summary:
These examples should help you get comfortable with while loops in Python, ranging from simple c
ounting to more interactive programs. Practice these exercises, and you'll master the while loop in n
o time!
Lab Exercise: Learning for Loop in Python
Objective:
Learn to use for loops in Python to iterate over sequences and perform repetitive tasks.
1. Example 1: Iterating Over a List
Description:
Use a for loop to iterate over a list of numbers and print each number.
Code Sample:
numbers = [1, 2, 3, 4, 5]
for number in numbers:
print(number)
Explanation:
• List: numbers is a list containing five integers.
• Loop: The for loop iterates over each element in the list and prints it.
2. Example 2: Summing Elements in a List
Description:
Use a for loop to calculate the sum of all elements in a list of numbers.
Code Sample:
numbers = [1, 2, 3, 4, 5]
total = 0
for number in numbers:
total += number
print(f"The sum of the numbers is: {total}")
Explanation:
• Initialization: total is initialized to 0.
• Loop: The for loop iterates over each element in the list, adding it to total.
3. Example 3: Iterating Over a String
Description:
Use a for loop to iterate over each character in a string and print it.
Code Sample:
text = "Hello, world!"
for char in text:
print(char)
Explanation:
• String: text is a string containing the phrase "Hello, world!".
• Loop: The for loop iterates over each character in the string and prints it.
4. Example 4: Generating a Range of Numbers
Description:
Use a for loop with the range function to print numbers from 0 to 9.
Code Sample:
for i in range(10):
print(i)
Explanation:
• Range: range(10) generates numbers from 0 to 9.
• Loop: The for loop iterates over the range, printing each number.
5. Example 5: Nested for Loops to Create a Multiplication Table
Description:
Use nested for loops to print a multiplication table for numbers 1 through 5.
Code Sample:
for i in range(1, 6):
for j in range(1, 6):
print(f"{i * j}\t", end="")
print() # Newline after each row
Explanation:
• Outer Loop: Iterates over numbers 1 to 5.
• Inner Loop: Iterates over numbers 1 to 5 for each iteration of the outer loop.
• Multiplication: Calculates the product of i and j and prints it with a tab space.
• Newline: print() with no arguments creates a new line after each row of the multiplication ta
ble.
Summary:
These examples should help you get comfortable with for loops in Python, ranging from simple itera
tion over lists to creating nested loops for more complex tasks. Practice these exercises to solidify y
our understanding of for loops!