Day 5: For Loops, Range & Code Blocks
Last updated
Was this helpful?
Last updated
Was this helpful?
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'
Think about the logic before writing code. How can you compare numbers against each other to see which one is larger?
Break down the code into steps:
Input student scores 78 65 89 86 55 91 64 89
( this will end up as strings) eg
Convert 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 :)
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
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.