Day 10: Exercises for both ‘for’ and ‘while’ loops.
Janet Oluwadunsin Ogunleye
Building Data-Driven Solutions| Mental Well-being | Women in STEM| Mentorship
Objective: You'll get the chance to experiment with loops, solve problems, and witness their magic firsthand.
Loops are your trusty companions in programming, and mastering them opens doors to endless possibilities. So, let's embark on this loop adventure together!
Here are exercises for both for and while loops:
Exercise 1: for Loop - Counting
Objective: Use a for loop to count from 1 to 10 and print each number.
# Exercise: Use a 'for' loop to count from 1 to 10 and print each number.
for number in range(1, 11):
print(number)
Exercise 2: for Loop - Summing Numbers
Objective: Use a for loop to calculate the sum of all numbers from 1 to 100.
# Exercise: Use a 'for' loop to calculate the sum of all numbers from 1 to 100.
sum_numbers = 0
for number in range(1, 101):
sum_numbers += number
print("The sum of numbers from 1 to 100 is:", sum_numbers)
Exercise 3: while Loop - Countdown
领英推è
Objective: Use a while loop to count down from 10 to 1 and print each number.
# Exercise: Use a 'while' loop to count down from 10 to 1 and print each number.
count = 10
while count >= 1:
print(count)
count -= 1
Exercise 4: while Loop - Password Prompt
Objective: Use a while loop to repeatedly ask the user for a password until they enter the correct password ('python123').
# Exercise: Use a 'while' loop to prompt the user for a password until they enter the correct one.
correct_password = 'python123'
password = input("Enter the password: ")
while password != correct_password:
print("Incorrect password. Try again.")
password = input("Enter the password: ")
print("Access granted!")
I encourage you to try different examples.
Keep the curiosity alive, and stay ready to tackle new challenges!
Happy coding,
Oluwadunsin