We often want computers to repeat some process several times. Programming languages provide structures that enable you to repeat blocks of instructions over and over again. This type of repetition is known as iteration.
There are two types of loop in Python:
This simple for loop example would write "hello world" 5 times:
The for loop is used to repeat a series of statements a given number of times. The first line of the for statement is used to state how many times the code should be repeated. A stepper variable is used to count through each iteration of the loop.
The range function
range() function is one of Python's built in functions. It is is used to indicate how many times the loop will be repeated.
The structure of the range function is
range(start, upto, step) in which the arguments of range are used as follows:
- start and step are both optional.
- upto must always be there, it means "up to but not including" the value.
- start, upto, and step must all be integers
Examples: of the use of range:
range(10)produces the list: [0,1,2,3,4,5,6,7,8,9]
range(1, 7)produces the list: [1,2,3,4,5,6]
range(0, 30, 5)produces the list: [0,5,10,15,20,25]
range(5, -1, -1)produces the list: [5,4,3,2,1,0]
Example FOR Loops
Using the skills demonstrated above:
- Write a program that will ask the user for a message and the number of times they want that message displayed. Then output the message that number of times.
- Write a program that will calculate the average (mean) of a set of numbers. This time, the user is to be asked how many numbers are to be averaged, they must then enter this number of numbers. Your program will calculate and display the average of those numbers.
- 1. Introduction to Python
- 2. Data types and Operators
- 3. String Operation and Math Unit Exercises
- 4. The IF Statement
- 5. More on IF
- 6. The Maze Game
- 7. Selection Exercises
- 8. FOR Loops
- 9. While Loops
- 10. Making a quiz
- 11. Iteration Exercises
- 12. Lists, Functions and Files
- 13. Creating a list
- 14. Lists with a FOR Loop
- 15. List operations
- 16. Consolidation
- 17. Lists Exercises
- 18. Functions
- 19. Parameters
- 20. Functions with parameters
- 21. Menu Program
- 22. Functions Exercises
- 23. Reading from a file
- 24. Reading from a file - Part 2
- 25. Writing to a file
- 26. Extending the Quiz