5.1 Intro To Loops + While Loops

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

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.

For example:

x = 8
while x < 13:
	print("x is still less than 13")
	x += 1

View code on GitHub.

This loop checks if x is less than 13. If it is, then 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, but 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 classes@code4tomorrow.org for inquiries.