logo

Python Do While 루프

Python에는 do while 루프에 대해 정의된 구문이 없습니다. Python 루프에는 다음만 포함됩니다. for 루프 그리고 while 루프 그러나 C++ 및 Java와 같은 다른 언어에서와 마찬가지로 while 루프가 작동하도록 수정할 수 있습니다.

Python에서는 초기에 조건이 True인 while 루프를 사용하여 do-while 루프의 동작을 시뮬레이션한 다음 원하는 조건이 충족되면 루프에서 벗어날 수 있습니다.



while 루프를 수행

Do while 루프는 루프에 지정된 조건문이 false가 될 때까지 모든 명령문을 실행할 수 있는 제어 루프 문 유형입니다. do while 루프에서는 조건이 false인지 true인지에 관계없이 명령문이 적어도 한 번 실행됩니다.

do while 루프의 구문:

do{ // statement or // set of statements } while(condition)>

C++의 do while 루프 예

이 예에서는 do while 루프를 사용하여 2의 배수를 인쇄합니다. 그래서 우리는 do while 루프의 작동을 이해할 수 있습니다.



C++




봄의 JPA



#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 루프를 비교하겠습니다.

파이썬3




# 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>

>

>

산출: 동안 목록의 항목을 인쇄하고 있습니다. Do while 루프에는 두 가지 종료 조건이 있습니다.

목록의 포인터가 마지막 +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:

파이썬3




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>