Python tutorial- while loop


Python Loops

while loop

The while loop can be used in a more general purpose. It executes a block code again and again while the condition is true. The following code will continue to execute while the user enter a number greater than

0. It will terminate when a negative number is entered.


choice=1


while choice>=0:

       print 'Your number is: %d',choice

      choice=int(raw_input('Enter your number:'))

 

Using break and continue keywords

Sometimes, you want to let a loop terminate when it is executing or you want it to continue. To stop a loop wherever you need, you can use break keyword. To continue it, use continue keyword.

>>> for x in range(1,11):

            print '%d' % x,

            if x>4:

                        break

1 2 3 4 5

>> >x=1

>>> while x<=11:

           print '%d' % x,

           x=x+1

            if x>5:

                   continue


1 2 3 4 5 6 7 8 9 10

>>> 




Comments




This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.