Intro to Loops
Loops are repeated programs that you can tell a computer to run. The point of loops is to tell a computer to do something again and again until you achieve a goal. This is called iteration.
While Loops are loops that do something while a condition is met, and you can code that something to change again and again until the condition is no longer met.
In general, a while loop follows this basic outline:
while condition: # do stuff # (make sure to have this indented)
x = 8 while x < 13: print("x is still less than 13") x += 1
View code on GitHub.
The condition for this loop is
x < 13. So, this loop checks if x is less than 13. If it is, then it executes the indented code. It prints “x is still less than 13”. Then, it'll add one to x and repeat the process (check x, print, and add one to x). The loop keeps on going until at one point x is no longer less than 13. In total, it'll print "x is still less than 13" 5 times because that's how many times the computer ran through the loop
In the above example, the computer prints when x is 8, 9, 10, 11, and 12. This is why it'll print "x is still less than 13" 5 times
Pretend you just got a 50 on your test, and your mom says you can't watch TV until you get above an 80. (HINT: use comparison operators). You increase your test score by 10 points per day (iterations). Write a program that tells you how many days you're going to need before you can watch TV.
Up 2 Fifty
Write a program that takes a number from the user and adds 2 to it until it reaches 50 or more, then prints out how many times 2 was added. If the number is already greater than 50, then print out "Already there!"
Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact email@example.com for inquiries.