python - loops questions help?

Hi, im unsure how to answer these, could anyone help?

1.  Do you think that all loops can be used interchangeably or not? Explain

your answer with examples.

2. How can you break out of a loop of any kind in the middle, including an infinite loop?

1 Answer

  • EddieJ
    Lv 7
    1 month ago

    I'l  answer (2) first.  You would use a  <break> statement.  But, then it really isn't an infinite loop.  So, maybe the answer is that you can close the shell window where the program is running.  

    (1) The term "interchangeably" is not well-defined.

    while True:

        zero or more statements

        if <boolean-expression>: break

        zero or more statements

        #end of loop

    So, if you want to test a condition at the start, then you have zero statements before the break.  If you want to test at the end then you have zero statements after the break.

    So, how do you do "while True:" with a <for> loop (which is intended to loop a specific number of times.  You can use an iterator.

    for _ in iter (int, 1):

        x = input (str (_))

    If you want to run this, it will prompt you with a number (zero) and allow you to press [Enter] each time through the loop.  So, when you run this, you can see that you can break out of the infinite loop by closing your shell window.

    You can also try to enter [Ctrl] + [C] to break out.  This will usually work if the there is an <input> statement in the loop, however, it won't always work if there is no pause in the loop (like an <input> statement provides).  It can depend on the system.

    • Login to reply the answers
Still have questions? Get your answers by asking now.