Cara menggunakan infinite loop python

Iteration means executing the same block of code over and over, potentially many times. A programming structure that implements iteration is called a loop.

In programming, there are two types of iteration, indefinite and definite:

  • With indefinite iteration, the number of times the loop is executed isn’t specified explicitly in advance. Rather, the designated block is executed repeatedly as long as some condition is met.

  • With definite iteration, the number of times the designated block will be executed is specified explicitly at the time the loop starts.

In this tutorial, you’ll:

  • Learn about the
    >>> n = 0
    >>> while n > 0:
    ...     n -= 1
    ...     print(n)
    ...
    
    6 loop, the Python control structure used for indefinite iteration
  • See how to break out of a loop or loop iteration prematurely
  • Explore infinite loops

When you’re finished, you should have a good grasp of how to use indefinite iteration in Python.

Free Bonus: Click here to get our free Python Cheat Sheet that shows you the basics of Python 3, like working with data types, dictionaries, lists, and Python functions.

Take the Quiz: Test your knowledge with our interactive “Python "while" Loops” quiz. Upon completion you will receive a score so you can track your learning progress over time:

Take the Quiz »

The >>> n = 0 >>> while n > 0: ... n -= 1 ... print(n) ... 6 Loop

Let’s see how Python’s

>>> n = 0
>>> while n > 0:
...     n -= 1
...     print(n)
...
6 statement is used to construct loops. We’ll start simple and embellish as we go.

The format of a rudimentary

>>> n = 0
>>> while n > 0:
...     n -= 1
...     print(n)
...
6 loop is shown below:

while <expr>:
    <statement(s)>

>>> a = ['foo', 'bar', 'baz']
>>> while a:
...     print(a.pop(-1))
...
baz
bar
foo
0 represents the block to be repeatedly executed, often referred to as the body of the loop. This is denoted with indentation, just as in an
>>> a = ['foo', 'bar', 'baz']
>>> while a:
...     print(a.pop(-1))
...
baz
bar
foo
1 statement.

Remember: All control structures in Python use indentation to define blocks. See the discussion on in the previous tutorial to review.

The controlling expression,

>>> a = ['foo', 'bar', 'baz']
>>> while a:
...     print(a.pop(-1))
...
baz
bar
foo
2, typically involves one or more variables that are initialized prior to starting the loop and then modified somewhere in the loop body.

When a

>>> n = 0
>>> while n > 0:
...     n -= 1
...     print(n)
...
6 loop is encountered,
>>> a = ['foo', 'bar', 'baz']
>>> while a:
...     print(a.pop(-1))
...
baz
bar
foo
2 is first evaluated in . If it is true, the loop body is executed. Then
>>> a = ['foo', 'bar', 'baz']
>>> while a:
...     print(a.pop(-1))
...
baz
bar
foo
2 is checked again, and if still true, the body is executed again. This continues until
>>> a = ['foo', 'bar', 'baz']
>>> while a:
...     print(a.pop(-1))
...
baz
bar
foo
2 becomes false, at which point program execution proceeds to the first statement beyond the loop body.

Consider this loop:

>>>

 1>>> n = 5
 2>>> while n > 0:
 3...     n -= 1
 4...     print(n)
 5...
 64
 73
 82
 91
100

Here’s what’s happening in this example:

  • >>> a = ['foo', 'bar', 'baz']
    >>> while a:
    ...     print(a.pop(-1))
    ...
    baz
    bar
    foo
    
    7 is initially
    >>> a = ['foo', 'bar', 'baz']
    >>> while a:
    ...     print(a.pop(-1))
    ...
    baz
    bar
    foo
    
    8. The expression in the
    >>> n = 0
    >>> while n > 0:
    ...     n -= 1
    ...     print(n)
    ...
    
    6 statement header on line 2 is
     1n = 5
     2while n > 0:
     3    n -= 1
     4    if n == 2:
     5        break
     6    print(n)
     7print('Loop ended.')
    
    0, which is true, so the loop body executes. Inside the loop body on line 3,
    >>> a = ['foo', 'bar', 'baz']
    >>> while a:
    ...     print(a.pop(-1))
    ...
    baz
    bar
    foo
    
    7 is decremented by
     1n = 5
     2while n > 0:
     3    n -= 1
     4    if n == 2:
     5        break
     6    print(n)
     7print('Loop ended.')
    
    2 to
     1n = 5
     2while n > 0:
     3    n -= 1
     4    if n == 2:
     5        break
     6    print(n)
     7print('Loop ended.')
    
    3, and then printed.

  • When the body of the loop has finished, program execution returns to the top of the loop at line 2, and the expression is evaluated again. It is still true, so the body executes again, and

     1n = 5
     2while n > 0:
     3    n -= 1
     4    if n == 2:
     5        break
     6    print(n)
     7print('Loop ended.')
    
    4 is printed.

  • This continues until

    >>> a = ['foo', 'bar', 'baz']
    >>> while a:
    ...     print(a.pop(-1))
    ...
    baz
    bar
    foo
    
    7 becomes
     1n = 5
     2while n > 0:
     3    n -= 1
     4    if n == 2:
     5        break
     6    print(n)
     7print('Loop ended.')
    
    6. At that point, when the expression is tested, it is false, and the loop terminates. Execution would resume at the first statement following the loop body, but there isn’t one in this case.

Note that the controlling expression of the

>>> n = 0
>>> while n > 0:
...     n -= 1
...     print(n)
...
6 loop is tested first, before anything else happens. If it’s false to start with, the loop body will never be executed at all:

>>>

>>> n = 0
>>> while n > 0:
...     n -= 1
...     print(n)
...

In the example above, when the loop is encountered,

>>> a = ['foo', 'bar', 'baz']
>>> while a:
...     print(a.pop(-1))
...
baz
bar
foo
7 is
 1n = 5
 2while n > 0:
 3    n -= 1
 4    if n == 2:
 5        break
 6    print(n)
 7print('Loop ended.')
6. The controlling expression
 1n = 5
 2while n > 0:
 3    n -= 1
 4    if n == 2:
 5        break
 6    print(n)
 7print('Loop ended.')
0 is already false, so the loop body never executes.

Here’s another

>>> n = 0
>>> while n > 0:
...     n -= 1
...     print(n)
...
6 loop involving a list, rather than a numeric comparison:

>>>

>>> a = ['foo', 'bar', 'baz']
>>> while a:
...     print(a.pop(-1))
...
baz
bar
foo

When a , it is truthy if it has elements in it and falsy if it is empty. In this example,

C:\Users\john\Documents>python break.py
4
3
Loop ended.
2 is true as long as it has elements in it. Once all the items have been removed with the
C:\Users\john\Documents>python break.py
4
3
Loop ended.
3 method and the list is empty,
C:\Users\john\Documents>python break.py
4
3
Loop ended.
2 is false, and the loop terminates.

Remove ads

The Python C:\Users\john\Documents>python break.py 4 3 Loop ended. 5 and C:\Users\john\Documents>python break.py 4 3 Loop ended. 6 Statements

In each example you have seen so far, the entire body of the

>>> n = 0
>>> while n > 0:
...     n -= 1
...     print(n)
...
6 loop is executed on each iteration. Python provides two keywords that terminate a loop iteration prematurely:

  • The Python

    C:\Users\john\Documents>python break.py
    4
    3
    Loop ended.
    
    5 statement immediately terminates a loop entirely. Program execution proceeds to the first statement following the loop body.

  • The Python

    C:\Users\john\Documents>python break.py
    4
    3
    Loop ended.
    
    6 statement immediately terminates the current loop iteration. Execution jumps to the top of the loop, and the controlling expression is re-evaluated to determine whether the loop will execute again or terminate.

The distinction between

C:\Users\john\Documents>python break.py
4
3
Loop ended.
5 and
C:\Users\john\Documents>python break.py
4
3
Loop ended.
6 is demonstrated in the following diagram:

Cara menggunakan infinite loop python
break and continue

Here’s a script file called

 1n = 5
 2while n > 0:
 3    n -= 1
 4    if n == 2:
 5        continue
 6    print(n)
 7print('Loop ended.')
2 that demonstrates the
C:\Users\john\Documents>python break.py
4
3
Loop ended.
5 statement:

 1n = 5
 2while n > 0:
 3    n -= 1
 4    if n == 2:
 5        break
 6    print(n)
 7print('Loop ended.')

Running

 1n = 5
 2while n > 0:
 3    n -= 1
 4    if n == 2:
 5        continue
 6    print(n)
 7print('Loop ended.')
2 from a command-line interpreter produces the following output:

C:\Users\john\Documents>python break.py
4
3
Loop ended.

When

>>> a = ['foo', 'bar', 'baz']
>>> while a:
...     print(a.pop(-1))
...
baz
bar
foo
7 becomes
 1n = 5
 2while n > 0:
 3    n -= 1
 4    if n == 2:
 5        continue
 6    print(n)
 7print('Loop ended.')
6, the
C:\Users\john\Documents>python break.py
4
3
Loop ended.
5 statement is executed. The loop is terminated completely, and program execution jumps to the
 1n = 5
 2while n > 0:
 3    n -= 1
 4    if n == 2:
 5        continue
 6    print(n)
 7print('Loop ended.')
8 statement on line 7.

Note: If your programming background is in C, C++, Java, or JavaScript, then you may be wondering where Python’s do-while loop is. Well, the bad news is that Python doesn’t have a do-while construct. But the good news is that you can use a

>>> n = 0
>>> while n > 0:
...     n -= 1
...     print(n)
...
6 loop with a
C:\Users\john\Documents>python break.py
4
3
Loop ended.
5 statement to emulate it.

The next script,

C:\Users\john\Documents>python continue.py
4
3
1
0
Loop ended.
1, is identical except for a
C:\Users\john\Documents>python break.py
4
3
Loop ended.
6 statement in place of the
C:\Users\john\Documents>python break.py
4
3
Loop ended.
5:

 1n = 5
 2while n > 0:
 3    n -= 1
 4    if n == 2:
 5        continue
 6    print(n)
 7print('Loop ended.')

The output of

C:\Users\john\Documents>python continue.py
4
3
1
0
Loop ended.
1 looks like this:

C:\Users\john\Documents>python continue.py
4
3
1
0
Loop ended.

This time, when

>>> a = ['foo', 'bar', 'baz']
>>> while a:
...     print(a.pop(-1))
...
baz
bar
foo
7 is
 1n = 5
 2while n > 0:
 3    n -= 1
 4    if n == 2:
 5        continue
 6    print(n)
 7print('Loop ended.')
6, the
C:\Users\john\Documents>python break.py
4
3
Loop ended.
6 statement causes termination of that iteration. Thus,
 1n = 5
 2while n > 0:
 3    n -= 1
 4    if n == 2:
 5        continue
 6    print(n)
 7print('Loop ended.')
6 isn’t printed. Execution returns to the top of the loop, the condition is re-evaluated, and it is still true. The loop resumes, terminating when
>>> a = ['foo', 'bar', 'baz']
>>> while a:
...     print(a.pop(-1))
...
baz
bar
foo
7 becomes
 1n = 5
 2while n > 0:
 3    n -= 1
 4    if n == 2:
 5        break
 6    print(n)
 7print('Loop ended.')
6, as previously.

The while <expr>: <statement(s)> else: <additional_statement(s)> 1 Clause

Python allows an optional

while <expr>:
    <statement(s)>
else:
    <additional_statement(s)>
1 clause at the end of a
>>> n = 0
>>> while n > 0:
...     n -= 1
...     print(n)
...
6 loop. This is a unique feature of Python, not found in most other programming languages. The syntax is shown below:

while <expr>:
    <statement(s)>
else:
    <additional_statement(s)>

The

while <expr>:
    <statement(s)>
else:
    <additional_statement(s)>
4 specified in the
while <expr>:
    <statement(s)>
else:
    <additional_statement(s)>
1 clause will be executed when the
>>> n = 0
>>> while n > 0:
...     n -= 1
...     print(n)
...
6 loop terminates.

Cara menggunakan infinite loop python

About now, you may be thinking, “How is that useful?” You could accomplish the same thing by putting those statements immediately after the

>>> n = 0
>>> while n > 0:
...     n -= 1
...     print(n)
...
6 loop, without the
while <expr>:
    <statement(s)>
else:
    <additional_statement(s)>
1:

while <expr>:
    <statement(s)>
<additional_statement(s)>

What’s the difference?

In the latter case, without the

while <expr>:
    <statement(s)>
else:
    <additional_statement(s)>
1 clause,
while <expr>:
    <statement(s)>
else:
    <additional_statement(s)>
4 will be executed after the
>>> n = 0
>>> while n > 0:
...     n -= 1
...     print(n)
...
6 loop terminates, no matter what.

When

while <expr>:
    <statement(s)>
else:
    <additional_statement(s)>
4 are placed in an
while <expr>:
    <statement(s)>
else:
    <additional_statement(s)>
1 clause, they will be executed only if the loop terminates “by exhaustion”—that is, if the loop iterates until the controlling condition becomes false. If the loop is exited by a
C:\Users\john\Documents>python break.py
4
3
Loop ended.
5 statement, the
while <expr>:
    <statement(s)>
else:
    <additional_statement(s)>
1 clause won’t be executed.

Consider the following example:

>>>

 1>>> n = 5
 2>>> while n > 0:
 3...     n -= 1
 4...     print(n)
 5...
 64
 73
 82
 91
100
0

In this case, the loop repeated until the condition was exhausted:

>>> a = ['foo', 'bar', 'baz']
>>> while a:
...     print(a.pop(-1))
...
baz
bar
foo
7 became
 1n = 5
 2while n > 0:
 3    n -= 1
 4    if n == 2:
 5        break
 6    print(n)
 7print('Loop ended.')
6, so
 1n = 5
 2while n > 0:
 3    n -= 1
 4    if n == 2:
 5        break
 6    print(n)
 7print('Loop ended.')
0 became false. Because the loop lived out its natural life, so to speak, the
while <expr>:
    <statement(s)>
else:
    <additional_statement(s)>
1 clause was executed. Now observe the difference here:

>>>

 1>>> n = 5
 2>>> while n > 0:
 3...     n -= 1
 4...     print(n)
 5...
 64
 73
 82
 91
100
1

This loop is terminated prematurely with

C:\Users\john\Documents>python break.py
4
3
Loop ended.
5, so the
while <expr>:
    <statement(s)>
else:
    <additional_statement(s)>
1 clause isn’t executed.

It may seem as if the meaning of the word

while <expr>:
    <statement(s)>
else:
    <additional_statement(s)>
1 doesn’t quite fit the
>>> n = 0
>>> while n > 0:
...     n -= 1
...     print(n)
...
6 loop as well as it does the
>>> a = ['foo', 'bar', 'baz']
>>> while a:
...     print(a.pop(-1))
...
baz
bar
foo
1 statement. Guido van Rossum, the creator of Python, has actually said that, if he had it to do over again, he’d leave the
>>> n = 0
>>> while n > 0:
...     n -= 1
...     print(n)
...
6 loop’s
while <expr>:
    <statement(s)>
else:
    <additional_statement(s)>
1 clause out of the language.

One of the following interpretations might help to make it more intuitive:

  • Think of the header of the loop (

     1>>> n = 5
     2>>> while n > 0:
     3...     n -= 1
     4...     print(n)
     5...
     64
     73
     82
     91
    100
    
    07) as an
    >>> a = ['foo', 'bar', 'baz']
    >>> while a:
    ...     print(a.pop(-1))
    ...
    baz
    bar
    foo
    
    1 statement (
     1>>> n = 5
     2>>> while n > 0:
     3...     n -= 1
     4...     print(n)
     5...
     64
     73
     82
     91
    100
    
    09) that gets executed over and over, with the
    while <expr>:
        <statement(s)>
    else:
        <additional_statement(s)>
    
    1 clause finally being executed when the condition becomes false.

  • Think of

    while <expr>:
        <statement(s)>
    else:
        <additional_statement(s)>
    
    1 as though it were
     1>>> n = 5
     2>>> while n > 0:
     3...     n -= 1
     4...     print(n)
     5...
     64
     73
     82
     91
    100
    
    12, in that the block that follows gets executed if there wasn’t a
    C:\Users\john\Documents>python break.py
    4
    3
    Loop ended.
    
    5.

If you don’t find either of these interpretations helpful, then feel free to ignore them.

When might an

while <expr>:
    <statement(s)>
else:
    <additional_statement(s)>
1 clause on a
>>> n = 0
>>> while n > 0:
...     n -= 1
...     print(n)
...
6 loop be useful? One common situation is if you are searching a list for a specific item. You can use
C:\Users\john\Documents>python break.py
4
3
Loop ended.
5 to exit the loop if the item is found, and the
while <expr>:
    <statement(s)>
else:
    <additional_statement(s)>
1 clause can contain code that is meant to be executed if the item isn’t found:

>>>

 1>>> n = 5
 2>>> while n > 0:
 3...     n -= 1
 4...     print(n)
 5...
 64
 73
 82
 91
100
2

Note: The code shown above is useful to illustrate the concept, but you’d actually be very unlikely to search a list that way.

First of all, lists are usually processed with definite iteration, not a

>>> n = 0
>>> while n > 0:
...     n -= 1
...     print(n)
...
6 loop. Definite iteration is covered in the next tutorial in this series.

Secondly, Python provides built-in ways to search for an item in a list. You can use the

 1>>> n = 5
 2>>> while n > 0:
 3...     n -= 1
 4...     print(n)
 5...
 64
 73
 82
 91
100
19 operator:

>>>

 1>>> n = 5
 2>>> while n > 0:
 3...     n -= 1
 4...     print(n)
 5...
 64
 73
 82
 91
100
3

The

 1>>> n = 5
 2>>> while n > 0:
 3...     n -= 1
 4...     print(n)
 5...
 64
 73
 82
 91
100
20 method would also work. This method raises a
 1>>> n = 5
 2>>> while n > 0:
 3...     n -= 1
 4...     print(n)
 5...
 64
 73
 82
 91
100
21 exception if the item isn’t found in the list, so you need to understand exception handling to use it. In Python, you use a
 1>>> n = 5
 2>>> while n > 0:
 3...     n -= 1
 4...     print(n)
 5...
 64
 73
 82
 91
100
22 statement to handle an exception. An example is given below:

>>>

 1>>> n = 5
 2>>> while n > 0:
 3...     n -= 1
 4...     print(n)
 5...
 64
 73
 82
 91
100
4

You will learn about exception handling later in this series.

An

while <expr>:
    <statement(s)>
else:
    <additional_statement(s)>
1 clause with a
>>> n = 0
>>> while n > 0:
...     n -= 1
...     print(n)
...
6 loop is a bit of an oddity, not often seen. But don’t shy away from it if you find a situation in which you feel it adds clarity to your code!

Remove ads

Infinite Loops

Suppose you write a

>>> n = 0
>>> while n > 0:
...     n -= 1
...     print(n)
...
6 loop that theoretically never ends. Sounds weird, right?

Consider this example:

>>>

 1>>> n = 5
 2>>> while n > 0:
 3...     n -= 1
 4...     print(n)
 5...
 64
 73
 82
 91
100
5

This code was terminated by Ctrl+C, which generates an interrupt from the keyboard. Otherwise, it would have gone on unendingly. Many

 1>>> n = 5
 2>>> while n > 0:
 3...     n -= 1
 4...     print(n)
 5...
 64
 73
 82
 91
100
26 output lines have been removed and replaced by the vertical ellipsis in the output shown.

Clearly,

 1>>> n = 5
 2>>> while n > 0:
 3...     n -= 1
 4...     print(n)
 5...
 64
 73
 82
 91
100
27 will never be false, or we’re all in very big trouble. Thus,
 1>>> n = 5
 2>>> while n > 0:
 3...     n -= 1
 4...     print(n)
 5...
 64
 73
 82
 91
100
28 initiates an infinite loop that will theoretically run forever.

Maybe that doesn’t sound like something you’d want to do, but this pattern is actually quite common. For example, you might write code for a service that starts up and runs forever accepting service requests. “Forever” in this context means until you shut it down, or until the heat death of the universe, whichever comes first.

More prosaically, remember that loops can be broken out of with the

C:\Users\john\Documents>python break.py
4
3
Loop ended.
5 statement. It may be more straightforward to terminate a loop based on conditions recognized within the loop body, rather than on a condition evaluated at the top.

Here’s another variant of the loop shown above that successively removes items from a list using

C:\Users\john\Documents>python break.py
4
3
Loop ended.
3 until it is empty:

>>>

 1>>> n = 5
 2>>> while n > 0:
 3...     n -= 1
 4...     print(n)
 5...
 64
 73
 82
 91
100
6

When

C:\Users\john\Documents>python break.py
4
3
Loop ended.
2 becomes empty,
 1>>> n = 5
 2>>> while n > 0:
 3...     n -= 1
 4...     print(n)
 5...
 64
 73
 82
 91
100
32 becomes true, and the
C:\Users\john\Documents>python break.py
4
3
Loop ended.
5 statement exits the loop.

You can also specify multiple

C:\Users\john\Documents>python break.py
4
3
Loop ended.
5 statements in a loop:

 1>>> n = 5
 2>>> while n > 0:
 3...     n -= 1
 4...     print(n)
 5...
 64
 73
 82
 91
100
7

In cases like this, where there are multiple reasons to end the loop, it is often cleaner to

C:\Users\john\Documents>python break.py
4
3
Loop ended.
5 out from several different locations, rather than try to specify all the termination conditions in the loop header.

Infinite loops can be very useful. Just remember that you must ensure the loop gets broken out of at some point, so it doesn’t truly become infinite.

Nested >>> n = 0 >>> while n > 0: ... n -= 1 ... print(n) ... 6 Loops

In general, Python control structures can be nested within one another. For example,

>>> a = ['foo', 'bar', 'baz']
>>> while a:
...     print(a.pop(-1))
...
baz
bar
foo
1/
 1>>> n = 5
 2>>> while n > 0:
 3...     n -= 1
 4...     print(n)
 5...
 64
 73
 82
 91
100
38/
while <expr>:
    <statement(s)>
else:
    <additional_statement(s)>
1 conditional statements can be nested:

 1>>> n = 5
 2>>> while n > 0:
 3...     n -= 1
 4...     print(n)
 5...
 64
 73
 82
 91
100
8

Similarly, a

>>> n = 0
>>> while n > 0:
...     n -= 1
...     print(n)
...
6 loop can be contained within another
>>> n = 0
>>> while n > 0:
...     n -= 1
...     print(n)
...
6 loop, as shown here:

>>>

 1>>> n = 5
 2>>> while n > 0:
 3...     n -= 1
 4...     print(n)
 5...
 64
 73
 82
 91
100
9

A

C:\Users\john\Documents>python break.py
4
3
Loop ended.
5 or
C:\Users\john\Documents>python break.py
4
3
Loop ended.
6 statement found within nested loops applies to the nearest enclosing loop:

>>> n = 0
>>> while n > 0:
...     n -= 1
...     print(n)
...
0

Additionally,

>>> n = 0
>>> while n > 0:
...     n -= 1
...     print(n)
...
6 loops can be nested inside
>>> a = ['foo', 'bar', 'baz']
>>> while a:
...     print(a.pop(-1))
...
baz
bar
foo
1/
 1>>> n = 5
 2>>> while n > 0:
 3...     n -= 1
 4...     print(n)
 5...
 64
 73
 82
 91
100
38/
while <expr>:
    <statement(s)>
else:
    <additional_statement(s)>
1 statements, and vice versa:

>>> n = 0
>>> while n > 0:
...     n -= 1
...     print(n)
...
1

>>> n = 0
>>> while n > 0:
...     n -= 1
...     print(n)
...
2

In fact, all the Python control structures can be intermingled with one another to whatever extent you need. That is as it should be. Imagine how frustrating it would be if there were unexpected restrictions like “A

>>> n = 0
>>> while n > 0:
...     n -= 1
...     print(n)
...
6 loop can’t be contained within an
>>> a = ['foo', 'bar', 'baz']
>>> while a:
...     print(a.pop(-1))
...
baz
bar
foo
1 statement” or “
>>> n = 0
>>> while n > 0:
...     n -= 1
...     print(n)
...
6 loops can only be nested inside one another at most four deep.” You’d have a very difficult time remembering them all.

Seemingly arbitrary numeric or logical limitations are considered a sign of poor program language design. Happily, you won’t find many in Python.

Remove ads

One-Line >>> n = 0 >>> while n > 0: ... n -= 1 ... print(n) ... 6 Loops

As with an

>>> a = ['foo', 'bar', 'baz']
>>> while a:
...     print(a.pop(-1))
...
baz
bar
foo
1 statement, a
>>> n = 0
>>> while n > 0:
...     n -= 1
...     print(n)
...
6 loop can be specified on one line. If there are multiple statements in the block that makes up the loop body, they can be separated by semicolons (
 1>>> n = 5
 2>>> while n > 0:
 3...     n -= 1
 4...     print(n)
 5...
 64
 73
 82
 91
100
54):

>>>

>>> n = 0
>>> while n > 0:
...     n -= 1
...     print(n)
...
3

This only works with simple statements though. You can’t combine two compound statements into one line. Thus, you can specify a

>>> n = 0
>>> while n > 0:
...     n -= 1
...     print(n)
...
6 loop all on one line as above, and you write an
>>> a = ['foo', 'bar', 'baz']
>>> while a:
...     print(a.pop(-1))
...
baz
bar
foo
1 statement on one line:

>>>

>>> n = 0
>>> while n > 0:
...     n -= 1
...     print(n)
...
4

But you can’t do this:

>>>

>>> n = 0
>>> while n > 0:
...     n -= 1
...     print(n)
...
5

Remember that discourages multiple statements on one line. So you probably shouldn’t be doing any of this very often anyhow.

Conclusion

In this tutorial, you learned about indefinite iteration using the Python

>>> n = 0
>>> while n > 0:
...     n -= 1
...     print(n)
...
6 loop. You’re now able to:

  • Construct basic and complex
    >>> n = 0
    >>> while n > 0:
    ...     n -= 1
    ...     print(n)
    ...
    
    6 loops
  • Interrupt loop execution with
    C:\Users\john\Documents>python break.py
    4
    3
    Loop ended.
    
    5 and
    C:\Users\john\Documents>python break.py
    4
    3
    Loop ended.
    
    6
  • Use the
    while <expr>:
        <statement(s)>
    else:
        <additional_statement(s)>
    
    1 clause with a
    >>> n = 0
    >>> while n > 0:
    ...     n -= 1
    ...     print(n)
    ...
    
    6 loop
  • Deal with infinite loops

You should now have a good grasp of how to execute a piece of code repetitively.

Take the Quiz: Test your knowledge with our interactive “Python "while" Loops” quiz. Upon completion you will receive a score so you can track your learning progress over time:

Take the Quiz »

The next tutorial in this series covers definite iteration with

 1>>> n = 5
 2>>> while n > 0:
 3...     n -= 1
 4...     print(n)
 5...
 64
 73
 82
 91
100
63 loops—recurrent execution where the number of repetitions is specified explicitly.

« Conditional Statements in Python

Python "for" Loops »

Mark as Completed

Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Mastering While Loops

🐍 Python Tricks 💌

Get a short & sweet Python Trick delivered to your inbox every couple of days. No spam ever. Unsubscribe any time. Curated by the Real Python team.

Cara menggunakan infinite loop python

Send Me Python Tricks »

About John Sturtz

Cara menggunakan infinite loop python
Cara menggunakan infinite loop python

John is an avid Pythonista and a member of the Real Python tutorial team.

» More about John


Each tutorial at Real Python is created by a team of developers so that it meets our high quality standards. The team members who worked on this tutorial are:

Cara menggunakan infinite loop python

Aldren

Cara menggunakan infinite loop python

Joanna

Cara menggunakan infinite loop python

Kyle

Master Real-World Python Skills With Unlimited Access to Real Python

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

Level Up Your Python Skills »

Master Real-World Python Skills
With Unlimited Access to Real Python

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

Level Up Your Python Skills »

What Do You Think?

Rate this article:

Tweet Share Share Email

What’s your #1 takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a comment below and let us know.

Commenting Tips: The most useful comments are those written with the goal of learning from or helping out other students. and get answers to common questions in our support portal.

Apa itu looping pada Python?

Perulangan atau juga sering dikenal dengan looping merupakan pernyataan atau instruksi yang diberikan kepada komputer agar ia mau melakukan sesuatu entah itu memproses data, menampilkan data, atau yang lainnya secara berulang.

Apa itu while loop Python?

1.While Loop. Ekspresi yang dimaksud merupakan suatu kondisi atau keadaan yang kita buat. Selama nilai yang diulang masih sesuai dengan ekspresi yang sudah ditetapkan yang berarti True dan tidak bernilai 0 maka while akan terus berjalan.

Apa fungsi dari loop?

Loop memungkinkan Anda untuk menguji kondisi di awal atau akhir struktur perulangan. Anda juga dapat menentukan apakah akan mengulangi perulangan saat kondisi tetap True ada atau sampai menjadi True .

While loop untuk apa?

While Loop adalah metode perulangan dimana ada kondisi yang harus dipenuhi supaya looping bisa berjalan terus. While Loop mengulangi eksekusi sub diagram didalamnya sampai terminal kondisi menerima nilai Boolean tertentu. Nilai Boolean tergantung dari sifat dari While Loop.