在Python中执行while循环
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 = 1while True:print(count)count += 1# test conditionif count>10:breakOutput
輸出量
1 2 3 4 5 6 7 8 9 10Example 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 = 0while True:# input the number num = int(input("Enter a number: "))# break if num is 0if num==0:break # terminates inner loop# print the table count = 1while count<=10:print(num*count)count += 1# input choicechoice = int(input("press 1 to continue..."))if choice != 1:break # terminates outer loopprint("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
總結
以上是生活随笔為你收集整理的在Python中执行while循环的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java LinkedList bool
- 下一篇: math.fabs_带有Python示例