Search⌘ K
AI Features

Solution: Repeat Yourself

Explore how to use for loops to repeat actions a set number of times and while loops to continue based on conditions. Learn practical examples like printing a name multiple times, counting by steps, and looping until user input stops the program.

Idea 1: Print your name 3 times

for i in range(3):
print("YourName")
  • The for loop repeats the code inside it a certain number of times.

  • range(3) means the loop will run 3 times (counting 0, 1, 2).

  • Each time the loop runs, it prints "YourName".

  • Output:

YourName
YourName
YourName

Idea 2: Count by 2s

for i in range(2, 11, 2):
print(i)
  • The range(2, 11, 2) function counts starting from 2, up to (but not including) 11, increasing by 2 each time.

  • The loop prints each value of i: 2, 4, 6, 8, 10.

  • Output:

2
4
6
8
10

Idea 3: Loop until the user types “stop”

text = ""
while text != "stop":
text = input("Type 'stop' to quit: ")
  • The while loop keeps running as long as the condition text != "stop" is true.

  • It repeatedly asks the user to type something.

  • When the user types "stop", the condition becomes false, and the loop ends.

  • Output:

Type 'stop' to quit: hello
Type 'stop' to quit: again
Type 'stop' to quit: stop
# Code for idea 1: Print your name 3 times.
for i in range(3):
    print("YourName")

# Code for idea 2: Count by 2s.
for i in range(2, 11, 2):
    print(i)

# Code for idea 3: Make a loop that runs until the user types “stop.”

text = ""
while text != "stop":
    text = input("Type 'stop' to quit: ")
The code keeps asking for input until we type “stop”