For Loop GCSE Computer Science – Python
For Loop The for loop iterates over the items in a sequence, which can be a string or a list (we will discuss lists later in this lesson) each time assigning the values in this sequence to a given variable. Note that the terminating condition is that we are at the end of the list.
For Loop The for loop is used as shown below: for ___ in range(___): code to be run here more code to be run here this code is not in the for loop
For Loop The for loop is used as shown below: for ___ in range(___): The first blank line must be replaced with a variable that keeps track of how many times the loop has run. The second blank line must be replaced with a number of times to loop.
For Loop The for loop is used as shown below: for ___ in range(___): for x in range (10): print (x) for pizza in range (99): print (pizza)
Counter The counter variable in Python starts from 0. for x in range (9): print (x) What do you think this will print?
For Loop – Example for x in range (10): print (“Mr Selwood”) ####################################### for pizza in range (5): print (pizza) ###################################### print (“Eight Times Table”) for x in range (10): print (x * 8)
Different Values You can change the start value of the for loop as shown below: for x in range(5, 10): print (x) What do you think this will print?
Different Values You can change the step value of the for loop as shown below: for x in range(5, 100, 10): print (x) What do you think this will print?
Individual Tasks For each of the following tasks: Use Python (IDLE) to code the solution. Copy and paste your solution into this PowerPoint Presentation. You can add additional slides!
1. Write a program to print the numbers one to twenty.
2. Write a program to print the six times table.
3. Ask the user to input a number. Print the times table for that number.
4. Ask the user for their age. Print “Happy Birthday” for every year of their age.