Iteration means executing the same block of code over and over, potentially many times. A programming structure that implements iteration is called a loop. Show
In programming, there are two types of iteration, indefinite and definite:
In this tutorial, you’ll:
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 LoopLet’s see how Python’s 6 statement is used to construct loops. We’ll start simple and embellish as we go.The format of a rudimentary 6 loop is shown below:
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 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, 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 6 loop is encountered, 2 is first evaluated in . If it is true, the loop body is executed. Then 2 is checked again, and if still true, the body is executed again. This continues until 2 becomes false, at which point program execution proceeds to the first statement beyond the loop body.Consider this loop: >>>
Here’s what’s happening in this example:
Note that the controlling expression of the 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:>>>
In the example above, when the loop is encountered, 7 is 6. The controlling expression 0 is already false, so the loop body never executes.Here’s another 6 loop involving a list, rather than a numeric comparison:>>>
When a , it is truthy if it has elements in it and falsy if it is empty. In this example, 2 is true as long as it has elements in it. Once all the items have been removed with the 3 method and the list is empty, 2 is false, and the loop terminates.Remove adsThe 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 StatementsIn each example you have seen so far, the entire body of the 6 loop is executed on each iteration. Python provides two keywords that terminate a loop iteration prematurely:
The distinction between 5 and 6 is demonstrated in the following diagram:Here’s a script file called 2 that demonstrates the 5 statement:
Running 2 from a command-line interpreter produces the following output:
When 7 becomes 6, the 5 statement is executed. The loop is terminated completely, and program execution jumps to the 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 6 loop with a 5 statement to emulate it.The next script, 1, is identical except for a 6 statement in place of the 5:
The output of 1 looks like this:
This time, when 7 is 6, the 6 statement causes termination of that iteration. Thus, 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 7 becomes 6, as previously.The while <expr>: <statement(s)> else: <additional_statement(s)> 1 ClausePython allows an optional 1 clause at the end of a 6 loop. This is a unique feature of Python, not found in most other programming languages. The syntax is shown below:
The 4 specified in the 1 clause will be executed when the 6 loop terminates.About now, you may be thinking, “How is that useful?” You could accomplish the same thing by putting those statements immediately after the 6 loop, without the 1:
What’s the difference? In the latter case, without the 1 clause, 4 will be executed after the 6 loop terminates, no matter what.When 4 are placed in an 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 5 statement, the 1 clause won’t be executed.Consider the following example: >>> 0In this case, the loop repeated until the condition was exhausted: 7 became 6, so 0 became false. Because the loop lived out its natural life, so to speak, the 1 clause was executed. Now observe the difference here:>>> 1This loop is terminated prematurely with 5, so the 1 clause isn’t executed.It may seem as if the meaning of the word 1 doesn’t quite fit the 6 loop as well as it does the 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 6 loop’s 1 clause out of the language.One of the following interpretations might help to make it more intuitive:
If you don’t find either of these interpretations helpful, then feel free to ignore them. When might an 1 clause on a 6 loop be useful? One common situation is if you are searching a list for a specific item. You can use 5 to exit the loop if the item is found, and the 1 clause can contain code that is meant to be executed if the item isn’t found:>>> 2Note: 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 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 19 operator:>>> 3The 20 method would also work. This method raises a 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 22 statement to handle an exception. An example is given below:>>> 4You will learn about exception handling later in this series. An 1 clause with a 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 adsInfinite LoopsSuppose you write a 6 loop that theoretically never ends. Sounds weird, right?Consider this example: >>> 5This code was terminated by Ctrl+C, which generates an interrupt from the keyboard. Otherwise, it would have gone on unendingly. Many 26 output lines have been removed and replaced by the vertical ellipsis in the output shown.Clearly, 27 will never be false, or we’re all in very big trouble. Thus, 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 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 3 until it is empty:>>> 6When 2 becomes empty, 32 becomes true, and the 5 statement exits the loop.You can also specify multiple 5 statements in a loop: 7In cases like this, where there are multiple reasons to end the loop, it is often cleaner to 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 LoopsIn general, Python control structures can be nested within one another. For example, 1/ 38/ 1 conditional statements can be nested: 8Similarly, a 6 loop can be contained within another 6 loop, as shown here:>>> 9A 5 or 6 statement found within nested loops applies to the nearest enclosing loop: 0Additionally, 6 loops can be nested inside 1/ 38/ 1 statements, and vice versa: 1 2In 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 6 loop can’t be contained within an 1 statement” or “ 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 adsOne-Line >>> n = 0 >>> while n > 0: ... n -= 1 ... print(n) ... 6 LoopsAs with an 1 statement, a 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 ( 54):>>> 3This only works with simple statements though. You can’t combine two compound statements into one line. Thus, you can specify a 6 loop all on one line as above, and you write an 1 statement on one line:>>> 4But you can’t do this: >>> 5Remember that discourages multiple statements on one line. So you probably shouldn’t be doing any of this very often anyhow. ConclusionIn this tutorial, you learned about indefinite iteration using the Python 6 loop. You’re now able to:
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 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. Send Me Python Tricks » About John Sturtz John is an avid Pythonista and a member of the Real Python tutorial team. 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: Aldren Joanna 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 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 EmailWhat’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.
|