Python では、do while ループ用に定義された構造はありません。 Python ループには次のもののみが含まれます for ループ そして while ループ ただし、C++ や Java などの他の言語と同様に while ループが動作するように while ループを変更することはできます。
Python では、最初に条件が True である while ループを使用して do-while ループの動作をシミュレートし、目的の条件が満たされたときにループから抜け出すことができます。
whileループを実行します
Do while ループは、ループ内で指定された条件ステートメントが false になるまで任意のステートメントを実行できる制御ループ ステートメントの一種です。 do while ループでは、条件が false か true に関係なく、ステートメントが少なくとも 1 回実行されます。
do while ループの構文:
do{ // statement or // set of statements } while(condition)> C++ の do while ループの例
この例では、do while ループを使用して 2 の倍数を出力します。これで、do while ループの仕組みを理解できるようになります。
C++
#include> using> namespace> std;> > int> main() {> > >int> i=0;> >// Defining do while loop> >// to write multiple of 2> >do>{> >i++;> >cout<<>'2 x '>< '='<<2*i< }while(i<5); return 0; }> |
>
>
出力: 以下の出力では、5 が 5 未満ではないにもかかわらず、プログラムが 2 x 5=10 も出力していることが明確にわかります。
2 x 1=2 2 x 2=4 2 x 3=6 2 x 4=8 2 x 5=10>
Python での do while ループの例:
例 1:
インターネットとは何ですか
この例では、Python の while ループと if ステートメントを使用して Python で do-while ループを実装し、while ループと Python の do-while ループを比較します。
Python3
# defining list of strings> list1>=> [>'geeksforgeeks'>,>'C++'>,> >'Java'>,>'Python'>,>'C'>,>'MachineLearning'>]> > # initialises a variable> i>=> 0> > print>('Printing>list> items> >using>while> loop')> size>=> len>(list1)> # Implement while loop to print list items> while>(i print(list1[i]) i = i+1 i = 0 print('Printing list items using do while loop') # Implement do while loop to print list items while(True): print(list1[i]) i = i+1 if(i and len(list1[i]) <10): continue else: break> |
jsonファイルを読み取る方法
>
>
出力: その間、リスト内の項目が印刷されます。 Do while ループには 2 つの終了条件があります。
リストのポインタが最後 +1 の位置に到達しました そして 長さが 10 以上のリスト インデックスの任意の要素。このコード出力では、次のことがわかります。
Do While ループは終了します。 len(リスト1[5])<10 充実していない。
Printing list items using while loop geeksforgeeks C++ Java Python C MachineLearning Printing list items using do while loop geeksforgeeks C++ Java Python C>
例 2:
Python3
total>=> 0> # loop will run at least once> while> True>:> ># ask the user to enter a number> >num>=> int>(>input>(>'Enter a number (or 0 to exit): '>))> > ># exit the loop if the user enters 0> >if> num>=>=> 0>:> >break> >total>+>=> num> > # print the total> print>(>'Total:'>, total)> |
>
>
出力 : このコードでは、while ループが実行され、ユーザーからの入力を受け入れて追加していることがわかります。 0 を入力すると、ループから抜け出し、ユーザーによる入力を 0 の前に追加したすべての数値の合計が出力されます。
Enter a number (or 0 to exit): 1 Enter a number (or 0 to exit): 3 Enter a number (or 0 to exit): 2 Enter a number (or 0 to exit): 0 Total: 6>