~ Gentle introduction to For Loops in Python


9 - Gentle introduction to For Loops in Python

Gentle Introduction to For Loops in Python

Having looked at while loops, consider the difference between them and the FOR Loop that we are going to look at next. While loops are conditon controlled loops - they have a condition at the start which brings the loop to an end. For loops however, are count controlled loops. They are used when you generally know the amount of times you want to loop through the program or script. Let's look at some examples and how they work.

Download Python 3 here:



Task 1

1.First, run the code to see how it works! Take careful note of the passed in parameters, 0, 100, and 5. What do you think they are doing?

2.Change the code in the for loop to make it start at 2, stop at 20, and go up by 2 each time. e.g. 2,4,6,8,10,12,etc

Code

#Can you change the code in the for loop below to make it start at 2, stop at 20m and go up by 2 each time. e.g. 2,4,6,8...etc
def main():
  for i in range(0,100,5):
    print(i)

main()

Task 2

1.Run the code below and note how it works..

2. Change the number '10' to something, in order to get the code to print numbers from 0 to 10, instead of 0 to 9.

Code

#what one thing you do you need to change to make this code print the numbers from 0 to 10 instead of 0 to 9

def main():
  for i in range(10):
    print(i)
  
main()

Task 3

1. Run and analyse the program.The for loop produces the following output: it starts at 3 and goes up to 19.

2. Adapt the code so that it starts at 5 and goes up to 50.

Code

#This loop starts at 3 and goes up by 1 each time, all the way up to 19.
#Change it so it starts at 5, and goes up to 50
def main():
  for i in range(3,20):
    print(i)

main()

Task 4

1. This program simply loops over a list (the len(mylist) is providing the range which is the length of the items in the list. It prints the result.

2. Comment each line to explain what is happening step by step.

3. Add more items to the list and ensure that it still works. Note carefully how you can use a for loop to loop and print the items contained in a list.

Code

def main():
  mylist=["smarties","toblerone","nestle milk","cadburys"]
  for i in range (len(mylist)):
    print(mylist[i])
  
main()

Task 5

1.Change the code so that the loop prints 20 stars on each line, and only three lines of stars instead of ten.

#Change the code so that the loop prints 20 stars on each line, and only 3 lines of stars

def main():
  for i in range(10):
    print("*******")

main()

Final Challenge

Use your knowledge and skills from the completed tasks. Use the trinket below to complete your challenge.

Create a program that asks the user for an integer input (of any number between 1 and 20). Use a for loop to print numbers from 0 and up to the user defined integer the sreen. For example, if the user enters 15. Print the numbers 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15 to the screen.

Answers

Coming soon!