Python While Loops

2-28-2021

While loops are perfect for when you don't necessarily know how many times you need something to be repeated. You may need something to run as long as a variable is equal to something specific, or while even run continously until a value is reached.


While True


While loops will continue running a set of tasks as long as a certain condition is true. In this way, they can be seen as similar to if statements that run more than once. For example:


while True:
    print("Hello World")

In this example, we have a while loop that prints "Hello World" as long as True is true. Since the value True is always true, this program will actually continuously print out the message until it is stopped. Lets look at an example with a mor explicit conditional.


while 3>2:
    print("Hello World")

In this example, the condition the while loop is checking is if 3>2 is true. Well, 3>2 is always true, so this loop will also continuously print the message until stopped.


While Loops with Variables


While loops are also commonly used with variables in their conditions. For example:


num=1

while num<5:
    print("Hello World")
    num+=1

In this example, the while loop evaluates the statement "num<5" before executing it's tasks every time. Since the while loop has num+=1 inside of it, this while loop will repeat 4 times before reaching the statement of "num<5" where num is 5. 5 is not less than 5, so the while loop stops running.


Conclusion


While loops are the go to method for repeating things when the number of iterations necessary is unknown. This proves to be useful in all kinds of situations. Try making a program that uses them yourself!