Sep. 28, 2012

Using While Loop in Python

Overview

In this post, I will write about While loops in Python. 

If you have read earlier posts "For and While Loops" you will probably recognize alot of this. 

Count from 0 to 9

This small script will count from 0 to 9. 
i = 0
while i < 10:
    print i
    i = i + 1

What does it do?

Between while and the colon, there is a value that first is True but will later beFalse. 

As long as the statement is True , the rest of the code will run. 

The code that will be run has to be in the indented block. 

The i = i + 1 adds 1 to the i value for every time it runs. 

Be careful to not make an eternal loop, which is when the loop continues until youpress Ctrl+C. 
while True:
    print "Hello World"

This loop means that the while loop will always be True and will forever print
Hello World.

Recommended Python Training – DataCamp

For Python training, our top recommendation is DataCamp.

Datacamp provides online interactive courses that combine interactive coding challenges with videos from top instructors in the field.

Datacamp has beginner to advanced Python training that programmers of all levels benefit from.

 



Read more about:
Disclosure of Material Connection: Some of the links in the post above are “affiliate links.” This means if you click on the link and purchase the item, I will receive an affiliate commission. Regardless, PythonForBeginners.com only recommend products or services that we try personally and believe will add value to our readers.