Newest Visitor Badge Earned!
Click to create an account and start competing today!
After Hours Programming
Show Tutorials


You (Level 0)
0/25
Last Badge Earned
Newest Visitor

Python While Loop Tutorial

Python While Loop

The Python While Loop tutorial explains the use of while loops in python.

While loops in Python can be extremely similar to the for loop if you really wanted them to be. Essentially, they both loop through for a given number of times, but a while loop can be more vague (I'll discuss this a little bit later). Generally, in a while loop you will have a conditional followed by some statements and then increment the variable in the condition. Let's take a peek at a while loop really quick:

Example a = 1
while a < 10:
print (a)
a+=1
Result 1
2
3
4
5
6
7
8
9

Fairly straightforward here, we have our conditional of a < 10 and a was previously declared and set equal to 1. So, our first item printed out was 1, which makes sense. Next, we increment a and ran the loop again. Of course, once a becomes equal to 10, we will no longer run through the loop.

The awesome part of a while loop is the fact that you can set it to a condition that is always satisfied like 1==1, which means the code will run forever! Why is that so cool? It's awesome because you create listeners or even games. Be warned though, you are creating an infinite loop, which will make any normal programmer very nervous.

Where's the do-while loop

Simple answer, it isn't in Python. You need to consider this before you are writing your loops. Not that a do-while loop is commonly used anyway, but Python doesn't have any support for it currently.

Try testing your code with the code simulator!

Let's move on to some more tutorials or the next section!



Previous Tutorial

For Loop

Next Tutorial

Strings







If you enjoyed this resource, support me by sharing this page with others.

Stumbleupon Facebook Twitter GooglePlus Reddit Delicious Digg


Comment or Suggestion?

Comments are a way to tell me about corrections or suggestions, what you thought about the resource, or providing additional information. Help feed the discussion!


Yes




Comments on Python While Loop

user
malek
September 21, 2014 10:20AM
a=1
b=2
while a<=b:
b+=1
code this one and see what will happen XD


user
halojen
September 11, 2014 09:19AM
@Jacobzone - no quotes in Line 3 - print(a) NOT print("a")


user
j2white
150
September 11, 2014 08:00AM
Burned up the browser by accident...


user
Jacobzone
200
September 10, 2014 06:52PM
This is my example (Gone Wrong?) I Need help xD

Python 3.2 (r32:88445, Feb 20 2011, 21:29:02) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> a = 1
>>> while a <30:
	print("a")
	a+=1

	
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
>>> 


user
Sajjad
125
September 7, 2014 11:42PM
print "MATRIX BY | SAJJAD ALI ANVER"
a=0
while a<918293810209381820809381092829387128371729837821312987398729139879812739871927397189273792831391278321731729838239721:
	a=a+1
	print a
	b=1
	while b<918293810209381820809381092829387128371729837821312987398729139879812739871927397189273792831391278321731729838239721:
		b=b+1
		print b
		c=2
		while c<918293810209381820809381092829387128371729837821312987398729139879812739871927397189273792831391278321731729838239721:
			c=c+1
			print c
			d=3
			while d<918293810209381820809381092829387128371729837821312987398729139879812739871927397189273792831391278321731729838239721:
				d=d+1
				print d
				e=4
				while e<918293810209381820809381092829387128371729837821312987398729139879812739871927397189273792831391278321731729838239721:
					e=e+1
					print e
					


user
Segismundo
150
September 2, 2014 12:31AM
Hello Ailish. Of course, I'm very happy to give you a hand.

Writing "a+=1" in Python is exactly the same as writing "a=a+1"... but more compact. So for example if a variable "a" has the value 3.3, and you do a+=1, it will end up having the value 4.3 (which is 3.3+1). Likewise, if "a" has the value 7 and you do a+=10 it will end up having the value 17 (which is 7+10); here, you could have done a=a+10 instead, but again a+=10 is more compact. Try the next code in the "Test Your code" tool in this same website (note: with the function "str" you transform anything, like a number, into a string, that can be used by the "print" function):

a=10
print("The current value of a is "+str(a))
a+=3
print("After doing a+=3, the current value of a is "+str(a))
a-=2.5
print("After doing a subtraction, the current value of a is "+str(a))

So, if instead of using "+=" you use "-=", it works exactly the same way; for example, doing a-=2.5 is exactly the same as doing a=a-2.5... it is always a way to update a variable's value from a past value.

Finally, you can also update a variable's name from its past value using "*=", "/=", "**=", etc. Every number operator can be combined this way. For example, imagine you have a variable "a" with the value 10.3, and you want to multiply it by 2, getting 20.6. So, instead of writing a=a*2, you can write a*=2. Imagine that have a variable with the value b=2, and you want to know the value of 2^8; instead of doing b=b**8, you can do b**=8. Try the next code:

a=10.3
print("Current value of a: "+str(a))
a*=2
print("a*2: "+str(a))
b=2
print("Current value of b: "+str(b))
b**=8
print("b^8: "+str(b))

I hope it helped. Good luck!


user
Ailish
100
August 31, 2014 11:33AM
Hello, I'm fairly new to programming and I'm a little bit confused at the usage of a+ =1. Please could someone explain it a little bit?


user
Segismundo
150
August 31, 2014 03:53AM
My conclusions about Python modules, part 1: Python modules are not explained in any of the Python tutorials in this website (probably because they don't work in the "Test Your code" tool, but they should work in your development environment). Despite of the fact that it is possible to work without them, they are pretty much essential in Python. Besides, some of the examples that I post in this tutorial (While Loop tutorial) use modules.

- In simple terms, a Python module is a file consisting of Python code (.py file) that you can import (we'll see later how) to your main source code file (.py file as well). So, imagine you have written a very powerful function of which you feel very proud of, and you want to reuse it in your present source code: You needn't rewrite the function's definition in your source code, instead you can write the function's definition in a module file and import the aforementioned module to your source code. Python modules are a way of saving space and time.

- What does import exactly mean? How is it related to the compiling process?: A Python interpreter/compiler is a program (usually integrated with a linker, a debugger, a text editor and some other programs in an Integrated Development Environment, aka IDE) that translates Python source code (source code is normally inside a .py file, but could be a .txt file as well) into an executable file that can be run by the CPU (through the Operating System). So when we import a module file to a main source code file we're telling the compiler to compile both the main file and the module file (along with any other .py necessary files such us libraries); once we have the executable files, the linker (another piece of software inside the IDE) joins them all together to form a final executable file which can be run by the CPU.

- A module can define (i.e. "have inside") submodules (a module inside a module; in this case the submodule is not a file, but a definition inside the main module file), functions, classes (studied later), variables and constants. It can have runnable (executable) code as well.

- There are 2 types of modules: those that you create and those that somebody else has already created. Let's study first those that you can create with the following example:
  * With a text editor, we create a file called module_example.py and save it in the same directory where the main source code file (for example main_code.py) is.
  * Inside module_example.py we write the following code (function defitions):
  def hello():
      print("Hello beautiful world")
  def goodbye():
      print("Goodbye cruel world")
  * In a Python interpreter, or in our main source code file main_code.py, we write:
  import module_example
  module_example.hello()
  * In the screen you will get the message "Hello world". So, once you've imported the module with the reserved Python word "import", you can access all its classes, functions, variables, constants and submodules by prefixing them with the module name and the "." operator.
  * The word "import" brings all the funtions, classes, etc. into your project and you need to use the module name and the "." operator as prefix. Nevertheless, you might want to import only parts of the module; in that case, you need to use the following code. Note that when this is done there is no need to use a prefix:
  from module_example import goodbye
  goodbye()
  * In the screen you will get the message "Goodbye cruel world". When you choose this way of programming, you have to be careful that in the present source code file there is no clash between names of functions, classes, etc. For example, if in main_code.py there is a function called "goodbye", errors will appear.
  * Finally, you might want to import everything from a module but perhaps you're tired of using prefixes continuously. Then, you do this (again, you have to be careful with name clashes):
  from module_example import *

- And finally we can work with modules that somebody else has created and are integrated in the standard Python libraries, or even can be installed. Some examples that are already integrated in Python 3.2 (I use Python 3.2.3 on Raspbian, which is a Linux distro) or can be installed are:
  * math: Mathematical functions with real numbers (not complex; if you want complex number support use the cmath module); it is always available, no need to install it. You can do factorials (with math.factorial(int x)-->int), absolute values (with math.fabs(float x)-->float), base-10 logarithms (with math.log10(float x)-->float), square roots (with math.sqrt(float x)-->float), trigonometric functions (sine, cosine, tangent, etc.), and many other things; these are all functions defined inside the module, they receive the type of data in brackets and return the type of data indicated after "-->"; for example, math.factorial receives an int number and returns an int number. Inside this module there are no submodules, classes or variables, but there are a couple of constants: module.pi (pi constant with available precision) and math.e (e constant with available precision). More information here (Python 3.2, but you can look for the other versions in the website I give you): https://docs.python.org/3.2/library/math.html.
  * random: This module is always available, and implements pseudo-random number generations; it is quite thoroughly explained in my next post, "My conclusions about Python modules, part 2".
  * turtle: This graphical module, always available, is a popular way for introducing programming to kids. More information here: https://docs.python.org/3.2/library/turtle.html.
  * time: This module, always available, provides various time-related functions. More information here: https://docs.python.org/3.2/library/time.html.
  * this: This module, always available, outputs some useful Python advice (The Zen of Python) when imported. Just type "import this" in your interpreter.
  * pygame: Installed in Python 2, but not in Python 3, so it needs to be installed. After installing it, we can use a powerful module to create games, draw things on the screen (fireballs, heroes...), and even control our camera. More information here: http://www.pygame.org/docs/.
  * minecraft: No comments need to be done (it needs to be installed)...
  * cv2: This is the OpenCV module (needs to be installed, only available, as far as I know, for Python 2, not for Python 3 yet); OpenCV is a extremely powerful computer vision a machine learning set of libraries. You can recognize faces, identify objects, follow eye movements, extract 3D models of objects, and a lot more cool stuff.
  * subprocess: This module, already installed, is the easiest way to interact with the underlying operating system using scripts. More information here: https://docs.python.org/3.2/library/subprocess.html.
  * sys: This module, already installed, provides access to some variables used or maintained by the interpreter and to functions that interact strongly with the interpreter. I mainly use the constant sys.path, which is a list of strings that specifies the search paths for modules (the strings tell you where the interpreter looks for the .py module files when it tries to import them). More information here: https://docs.python.org/3.2/library/sys.html.


user
Segismundo
150
August 30, 2014 02:36AM
My conclusions about repetitive structures (aka "for loops" and "while loops"), part 2: while loops (for loops are explained in the previous tutorial):

- Repetitive structures are a type of flow-control structures (together with conditional structures, aka if-elif-else statements). They are used to repeat the same block of instructions a number of times; each repetition is called a loop.

- While loops are used when the number of repetitions is not known in advance (and for loops are used when the number of repetitions is known in advance).

- Here there is no counter, no int variable used to count the number of times that the block has to be executed. Here there is a condition; in fact, while loops are often called condition-controlled repetitive structures, whilst for loops are often called counter-controlled repetitive structures, and as we already know if-elif-else statements are called conditional/selective structures. Before each iteration, if the condition is True the block is executed, and if the condition is False the program exits the loop. There is a big problem about the previous way of functioning, which is that if the condition is always True (i.e. if the condition is not changed inside or outside the loop) we enter an infinite loop.

- The syntax is as follow:
while condition:
    instruction_1
    instruction_2
    ...
    instruction_last

- So what really happens is explained in the next steps:
  * The while loop checks if the condition is True or False. If it is True, it executes the block of instructions; if it is False, the program exits the loop. That means that it is possible that a while loop is not executed, not even once (which might be interesting or useful for a program). Let's suppose that the condition is True.
  * After executing the block, the while loop checks again if the condition is True or False, and so on. If the condition does never become False we enter an infinite loop (that's why it is very convenient to change the condition inside the loop, unless we want to intentionally create an infinite loop, as in listener or game applications)

- All flow-control structures (if-elif-else, while, for) can be nested, i.e. we can include any kind of structure inside any other kind of structure: For loops can go inside if-elif-else statements, while loops can go inside for loops, etc. This is better understood with the examples I propose in this tutorial.


user
Segismundo
150
August 29, 2014 03:15AM
Hi ShafiShawon. I believe that your indentation is still incorrect. You shouldn't add 4 spaces in the line "while i>5:", as this line is not subordinated to "i=20". On the contrary, you should keep the 4 spaces in "print(i)" and "i=i-2", as both lines are indeed subordinated to "while i>5:". So the program would be (try it in the "Test Your code" tool in this website, it works):

i=20
while i>5:
    print(i)
    i=i-2


user
ShafiShawon
175
August 23, 2014 07:40AM
When I try this:
i=20
    while i>5:
    print(i)
    i=i-2

It shows ParseError: bad input on line2
Is there any syntax wrong. I have spaced 4 times correctly  


user
SquirrelHermit
100
August 11, 2014 02:14PM
SamWang,

You would need to tab or add your 4 spaces after the Print (a) and the a=a-1. the following is what it should look like::

a = 100
while a>5:
    print(a)
    a=a-1



user
SamWang
150
August 9, 2014 06:30PM
When I try
a = 100
while a>5:
print(a)
a=a-1

It output:
ParseError: bad input on line3

Should be a correct syntax...


user
tomecki
200
August 8, 2014 10:05AM
Naveen, !> is an invalid syntax in Python.


user
don22
125
August 5, 2014 12:52PM
Where is the code simulator?
don


user
farukh
100
August 1, 2014 01:44PM
can u do anything else with this code cause all it looks like you playing with numbers. in other words can we create a program or software


user
Naveen
100
July 5, 2014 02:43PM
How would you do  NOT Greater than in Python? 

This web based Interpreter does not do  
a = 1
while a !> 10:
print (a)
a+=1


user
MrMatrix
100
June 29, 2014 03:48PM
Ok guys im going try to explain in more detail what A+=1 is doing.
Equal sign gives a value to a Letter.
First you introduce A.         A = 5
To A im going to add 5. so  A += 5
After you introduce A to a value. Your next code line should be what you are adding to A. Type print(A) to check your answer .




user
Cosmo Sutherland McCook
450
June 23, 2014 11:41PM
a=1
while a ==1:
    print (a)
    a+=1


user
peterith
125
June 19, 2014 05:25PM
a=1
while a<10:
    print(a)
    a+=1


user
Arunkumar Ravikumar
100
May 30, 2014 11:46PM
Also i was surprised to see have the value of  variable "a" is used , good one
for a in range(1,10):
    print("Loop is running for "+str(a)+"th time")
    while a <= 10:
        print(a)
        a+=1
    print("=============")
        


user
Madasyn Caplin
100
May 26, 2014 12:14PM
Try this one:
b = 2
while b < 10:
    print(b)
b+=2

Its really cool! :{P


user
Luis Arce
100
May 23, 2014 05:26AM
What's with the a+=1? I see no explanation on this.


user
ABIN VARGHESE
April 24, 2014 05:10AM
This is really helpful.... Thanks a lot


user
Jamie
375
April 23, 2014 11:27PM
Thanks to Allen Prattis (March 24, 2014) for the tip.


user
Andy M
150
April 3, 2014 08:48PM
Could you possibly include a way to stop the code from running somehow? I'm sure I'm not the only one to have accidentally created an infinite loop...
Thanks!


user
Allen Prattis
March 24, 2014 04:59PM
Typing the following into Test Code works:

a = 1
while a <= 100:
    print (a)
    a+=1

Typing the following into Test Code seems to loop forever:

a = 1
while a <= 100:
    print (a)
a+=1 #No spaces before the line begin.





user
holy_sheep
March 7, 2014 07:22PM
how to understand the "Why is that so cool? It's awesome because you create listeners or even games"?I am new for programming.


user
Michael D
125
March 5, 2014 07:19PM
 Code simulator isn't working for me. Input
a=26
while a > 53:
    print (a)
    a+=26
Hit test code nothing appears. Fixes? Anybody else have problem?


user
rousbel_villar
150
March 5, 2014 05:24AM
Awesome this was very interesting , specially the condition a==x.