This article mainly introduces how to use else and nested loop in the while loop of Python. It is the basic knowledge of getting started with Python. For more information, see
Loop using else statements
In python,... Else indicates this. The statements in for are no different from those in general. The statements in else are executed after the loop is executed normally (that is, the for statements are not interrupted by the break jump, while... The same is true for else.
#!/usr/bin/pythoncount = 0while count < 5: print count, " is less than 5" count = count + 1else: print count, " is not less than 5"
The output result of the above instance is:
0 is less than 51 is less than 52 is less than 53 is less than 54 is less than 55 is not less than 5
Simple statement Group
Similar to the if statement syntax, if your while LOOP body contains only one statement, you can write the statement and while statement in the same line, as shown below:
#!/usr/bin/pythonflag = 1while (flag): print 'Given flag is really true!'print "Good bye!"
Note: You can use CTRL + C to interrupt the loop.
Python loop nesting
The Python language allows you to embed another loop in a loop body.
Python for nested loop Syntax:
for iterating_var in sequence: for iterating_var in sequence: statements(s) statements(s)
Python while LOOP nested Syntax:
while expression: while expression: statement(s) statement(s)
You can embed other loop bodies in a loop. for example, you can embed a for Loop in a while loop. Otherwise, you can embed a while loop in a for loop.
Instance:
The following example uses nested loop output 2 ~ Prime number between 100 :#! /Usr/bin/python
#-*-Coding: UTF-8-*-I = 2 while (I <100): j = 2 while (j <= (I/j )): if not (I % j): breakj = j + 1if (j> I/j): print I, "Yes Prime Number" I = I + 1 print "Good bye! "
Output result of the above instance:
2 is prime number 3 is prime number 5 is prime number 7 is Prime Number 11 is prime number 13 is prime number 17 is prime number 19 is prime number 23 is prime number 29 is prime number 31 is prime number 37 is prime number 41 is prime number 43 is a prime number 47 is a prime number 53 is a prime number 59 is a prime number 61 is a prime number 67 is a prime number 71 is a prime number 73 is a prime number 79 is a prime number 83 is a prime number 89 is a prime number 97 is a prime number Good bye!