Python执行while循环 (Python do while loop)
Like other programming languages, do while loop is an exit controlled loop – which validates the test condition after executing the loop statements (loop body).
像其他编程语言一样, do while循环是退出控制的循环-在执行循环语句(循环主体)后验证测试条件。
In Python programming language, there is no such loop i.e. python does not have a do while loop that can validate the test condition after executing the loop statement. But, we can implement a similar approach like a do while loop using while loop by checking using True instead of a test condition and test condition can be placed in the loop statement, and break the loop's execution using break statement – if the test condition is not true.
在Python编程语言中,没有这样的循环,即python没有do while循环可以在执行loop语句后验证测试条件。 但是,我们可以通过使用True而不是测试条件进行检查,从而实现类似while循环的do while循环方法,方法是使用True而不是测试条件进行检查,并且可以在循环语句中放置测试条件,并使用break语句中断循环的执行-如果测试条件为不对。
Logic to implement an approach like a do while loop
实现类似do while循环的方法的逻辑
Use while loop with True as test condition (i.e. an infinite loop)
在测试条件为True的情况下使用while循环 (即无限循环)
Write statements of loop body within the scope of while loop
在while循环范围内编写循环主体的语句
Place the condition to be validated (test condition) in the loop body
将要验证的条件(测试条件)放在循环体内
break the loop statement – if test condition is false
中断循环语句 –如果测试条件为假
使用while循环实现do while循环的Python代码 (Python code to implement a do while loop using while loop)
Example 1: Print the numbers from 1 to 10
示例1:打印从1到10的数字
# print numbers from 1 to 10
count = 1
while True:
print(count)
count += 1
# test condition
if count>10:
break
Output
输出量
1
2
3
4
5
6
7
8
9
10
Example 2: Input a number and print its table and ask for user's choice to continue/exit
示例2:输入数字并打印其表格,然后要求用户选择继续/退出
# python example of to print tables
count = 1
num = 0
choice = 0
while True:
# input the number
num = int(input("Enter a number: "))
# break if num is 0
if num==0:
break # terminates inner loop
# print the table
count = 1
while count<=10:
print(num*count)
count += 1
# input choice
choice = int(input("press 1 to continue..."))
if choice != 1:
break # terminates outer loop
print("bye bye!!!")
Output
输出量
Enter a number: 3
3
6
9
12
15
18
21
24
27
30
press 1 to continue...1
Enter a number: 19
19
38
57
76
95
114
133
152
171
190
press 1 to continue...0
bye bye!!!
翻译自: https://www.includehelp.com/python/do-while-loop.aspx