![]() It is important to define the start parameter as len(a) - 1 because in Python (and computer sciences in general) we start counting from 0. If you don’t remember lists and other Python data structures, I encourage you to read more about the difference between lists, tuples, and dictionaries before you continue. We can also define a list of elements and display them in reverse order based on the list length. Let's modify the previous example and output the results: We can also set the step parameter to some other value (like -3) and the for loop will decrement by 3 instead of 1. Finally, step=-1 because it’s the difference between each number we would like to get and the previous one (e.g., 8 - 9 = -1, 2 - 3 = -1, etc.) The end is set to -1 because the end value is always excluded here, the last value we want to print is 0. The start parameter is set to 9 because that is the first value we want to obtain. We can apply it in a straightforward manner by setting the start and the end parameters so that end > for i in range(9, -1, -1):Īnd here we go! We have exactly the same loop as above, but in reverse order. The previous example provides some insight on how to decrement in a Python for loop using range(). Decrementing a Python for Loop with range() Next, let’s explore how to use this knowledge to decrement a Python for loop. The above syntax is equivalent to writing: The start and step parameters are optional they default to 0 and 1, respectively. If we only specify one value, by default it is the end parameter. As per the Python documentation, its syntax is as follows: If you do not know, maybe it is because you are not familiar with the complete syntax of the range() method. We just incremented successfully! But how do we decrement? In other words, how can we print 9, 8, 7, 6, 5, 4, 3, 2, 1, 0? ![]() You might have already learned this common way of implementing a for loop in Python: ![]() Okay, on to the for loop! Incrementing a Python for Loop
0 Comments
Leave a Reply. |
Details
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |