To increase the start value by a different number, you use the following form of the range() function: range(start, stop, step) Code language: Python ( python ) Output: 1 2 3 4 5 Code language: Python ( python ) Specifying the increment for the sequenceīy default, the range(start, stop) increases the start value by one in each loop iteration. The following example uses a for loop to show five numbers, from 1 to 5 to the screen: for index in range( 1, 6): In this syntax, the range() function increases the start value by one until it reaches the stop value. In addition, the range() function allows you to specify the starting number like this: range(start, stop) Code language: Python ( python ) Specifying the starting value for the sequenceīy default, the range() function uses zero as the starting number for the sequence. In this example, we increase the index by one in each iteration and print it out. Output: 1 2 3 4 5 Code language: Python ( python ) Print(index + 1) Code language: Python ( python ) If you want to show 5 numbers from 1 to 5 on the screen, you can do something like this: for index in range( 5): In this example, the for loop executes the statement print(index) exactly five times. Output: 0 1 2 3 4 Code language: Python ( python ) Print(index) Code language: Python ( python ) The following example shows how to use the for loop with the range() function to display 5 numbers from 0 to 4 to the screen: for index in range( 5): The following diagram illustrates the for loop statement: Note that it’s always short of the final number ( n). ![]() So the range(n) generates a sequence of numbers: 0, 1, 2, … n-1. It increases the value by one until it reaches n. The range(n) generates a sequence of n integers starting at zero. It’s like the print() function in the sense that it’s always available in the program. The range() is a built-in function in Python. The name of the loop counter doesn’t have to be index, you can use whatever name you want. And n is the number of times that the loop will execute the statement. In this syntax, the index is called a loop counter. Statement Code language: Python ( python ) ![]() The following illustrates the syntax of a for loop: for index in range(n): In programming, you often want to execute a block of code multiple times. Introduction to Python for loop statement with the range() function Summary: in this tutorial, you’ll learn about the Python for loop and how to use it to execute a code block a fixed number of times.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |