while loop and exercises
Python programming while statement for executing a program loop, i.e., under certain conditions, implementation of certain program loop, the same processing task needs to repeat the process. In its basic form is: while judgment conditions: ...... execute statement execution statement or statements may be a single block. Determination condition can be any expression, in any non-zero value, or a non-empty (null) are true.
When the determination condition false false, the cycle ends.
Example:
count = 0
while (count < 9): print ('The count is:', count) count = count + 1 print("Good bye!")
operation result:
The count is: 0
The count is: 1
The count is: 2 The count is: 3 The count is: 4 The count is: 5 The count is: 6 The count is: 7 The count is: 8 Good bye!
continue and break usage
When there are two other important while statement command continue, break the cycle skip, continue for skipping the cycle, break it is used to exit the loop, in addition to "determination condition" may also be a constant, indicates the cycle must establishment, are used as follows:
i = 1
while i < 10:
i += 1
if i%2 > 0: # 非双数时跳过输出 continue print(i) # 输出双数2、4、6、8、10
operation result:
2
4
6
8
10
i = 1
while 1: # 循环条件为1必定成立 print(i) # 输出1~10 i += 1 if i > 10: # 当i大于10时跳出循环 break
operation result:
1
2
3
4
5 6 7 8 9 10
Infinite loop
If the conditional statement is always true, infinite loop will execute it, the following examples:
var = 1
while var == 1 : # 该条件永远为true,循环将无限执行下去 num = input("Enter a number :") print ("You entered: ", num) print ("Good bye!")
Enter a number :3
You entered: 3
Enter a number :4 You entered: 4 Enter a number :5 You entered: 5 Enter a number :6 You entered: 6 Enter a number :7 You entered: 7 Enter a number :8 You entered: 8 Enter a number :100 You entered: 100 Enter a number :Traceback (most recent call last): File "c:/1.py", line 76, in <module> # num = input("Enter a number :") KeyboardInterrupt
Note: The above infinite loop you can use CTRL + C to interrupt the cycle.
Recycled else statement
In python, while ... else else block executed in the loop when the condition is false:
count = 0
while count < 5: print (count, " is less than 5") count = count + 1 else: print (count, " is not less than 5")
operation result:
0 is less than 5
1 is less than 5
2 is less than 5 3 is less than 5 4 is less than 5 5 is not less than 5
Related exercises
1. Output 1,2,3,4,5,6,8,9,10
count = 1
while count <= 10: if count == 7: pass else: print(count) count = count + 1
2. Output 1-100 numbers and all
n = 1
m = 0
while n < 101:
m = m + n
n = n + 1 print(m)
3. Output 100 within all odd
n = 1
while n < 101:
temp = n % 2
if temp == 0: print(n) else: pass n = n +1
4. Output + 3-4 + 1-2 ..... 99 5 and the number of all
n = 1
m = 0
while n < 100:
temp = n % 2 if temp == 0: m = m - n else: m = m + n n = n + 1 print(m)
References:
1.Python While loop | Rookie Tutorial: https://www.runoob.com/python/python-while-loop.html