Solution: Repeat Yourself
Explore how to use for and while loops in Python to repeat actions and manage user input. Understand how to automate tasks with loop control structures and conditionals, enabling you to build interactive, efficient programs.
We'll cover the following...
Idea 1: Print your name 3 times
for i in range(3):print("YourName")
The
forloop 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:
YourNameYourNameYourName
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:
246810
Idea 3: Loop until the user types “stop”
text = ""while text != "stop":text = input("Type 'stop' to quit: ")
The
whileloop keeps running as long as the conditiontext != "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: helloType 'stop' to quit: againType '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: ")