Loops let us repeat actions in Python. We'll cover both for
and while
loops and learn when to use each one.
for
loops to iterate over ranges or listswhile
loops to repeat based on a conditionfor i in range(5):
print(i)
count = 0
while count < 5:
print(count)
count += 1
Create a program that asks the user to enter a number and then prints all numbers from 1 to that number using a for
loop.
Then add another part that uses a while
loop to count down from that number to 1.
# FOR LOOP
num = int(input("Enter a number: "))
for i in range(1, num + 1):
print(i)
# WHILE LOOP
count = num
while count > 0:
print(count)
count -= 1