How to emulate the do-while cycle in python?

0

Some of you could tell me how to emulate the do-while cycle in python, looking for in different pages I found the following code

 while True:
     stuff() #que hace esa funcion o alguno puede ser tan amable de darme un ejemplo de uso
     if fail_condition:
     break

that was all many thanks in advance

    
asked by Cesar Quintero 19.02.2018 в 21:24
source

2 answers

1

It is as you say, but to give you an example to back you up with, you could do it in the following way:

i = 1

while True:
    print(i)
    i = i + 1
    if(i > 3):
        break

I understand that it looks fast, but what you do is a do-while which, in C for example, would be like this:

int i = 1;

do{
  printf("%d\n", i);
  i = i + 1;
} while(i <= 3);
    
answered by 19.02.2018 / 23:34
source
1

If you want to avoid the break (some purists consider that the break is not structured programming and should not be used), you have the following option, which for my taste is worse, but good:

i = 1
repetir_bucle = True
while repetir_bucle:
    print(i)
    i = i + 1
    if i>3:
       repetir_bucle = False

Or to make the output condition even more like a loop% C_% of C:

i = 1
repetir_bucle = True
while repetir_bucle:
    print(i)
    i = i + 1
    repetir_bucle = (i<=3)

which for my taste is even uglier than the previous one. I would keep the solution do...while , but for tastes ...

    
answered by 20.02.2018 в 10:44