Day 5: For Loops, Range & Code Blocks
Loops
The 1st type of loop is called the "For Loop" which means
for item in list_of_items
#Do something to each item
If we have a list called "fruits" and inside the list we have ["Apple", "Peach", "Pear"] and we want to access each item in the list individually and print each one out one by one, them we use the 'for loop'




EXERCISE 1 - Average Height





EXERCISE 2 - Highest Score

Hint
Think about the logic before writing code. How can you compare numbers against each other to see which one is larger?
Solution
Break down the code into steps:
Input student scores
78 65 89 86 55 91 64 89( this will end up as strings) egConvert the list of strings into a list of integers using the "for loop"


My new update - Angela uses her own ("don't change the code") I wanted to do the whole thing from my perspective - this is the first time that I have had to use a new function to change strings into integers in a list :) It works so that's cool :)

For Loop and range(function)
We have been using the for loop in association with lists, ie looping through the lists and getting hold of each item within the list and then doing something with it. However sometimes we might want to use a "for loop" completely independent of a list For example if we wanted to add all the numbers from 1-100 we use the "range" command however if we issued a print command this would print out all the numbers from 1-99. So we have to ADD an extra 1 to the end. So in this case the range(1, 101) If we wanted to have it add in steps of say 3 for a range(1, 11, 3) we would add the step in a the end
The syntax is this



Going back to us wanting to add up all the numbers from 1-100

Exercise: Adding Even Numbers
Instructions
You are going to write a program that calculates the sum of all the even numbers from 1 to 100, including 1 and 100.
e.g. 2 + 4 + 6 + 8 +10 ... + 98 + 100
Important, there should only be 1 print statement in your console output. It should just print the final total and not every step of the calculation.


Exercise: FizzBuzz


Project of the Day - Password Generator


Last updated
Was this helpful?