With while loops, it’s easy to make a mistake and find yourself caught in an infinite while-loop. Since the very simple expression ‘ True‘ is always True, this loop never stops. Why is this an infinite loop? Remember that while takes an expression, and keeps repeating the code as long as that expression evaluates to True. Let’s create such an infinite loop in Python: > while True: In such cases, an infinite loop can be of help. Sometimes you want your software to keep running. Here’s an interactive example to experiment with yourself: The output of the print statement confirms that this loop runs four times. This keeps happening as long as i is smaller than or equal to 4. In the first iteration of the loop, we print i and increase it by one. In the example above, we start with i = 1. As long as this expression evaluates to True, the block inside of the while-loop executes repeatedly. We see an expression that follows the while statement: i <= 4. Let’s take a look at an actual example: > i = 1 You should read this as: “while this expression evaluates to True, keep doing the stuff below”. While the for-loop in Python is a bit hard to understand, because of new concepts like iterability and objects, the while loop is actually much simpler! Its template looks like this: while : An extensive tutorial on Python lists can be found later on in this Python tutorial. Here are a couple of things you can try in a REPL or in the interactive code example above: > mylist = ]įrom the last example, you can see how to access nested lists. So mylist gives us the first element, and mylist the second, etcetera. Remember that in computer science, we start counting from 0. Indeed, you can create a list of lists if you want! As you can see in the interactive example, we can also access individual elements of a list.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |