So far, we've processed lists like this:
days_of_the_week = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]
counter = 0
while counter < len(days_of_the_week):
if "S" not in days_of_the_week[counter]:
print(days_of_the_week[counter],"is a good day for programming")
counter += 1
This pattern is so common there is a special loop for doing it without having to manage the counter yourself.
days_of_the_week = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]
for day in days_of_the_week:
if "S" not in day:
print(day,"is a good day for programming")
Notice: day became the value from the list for this iteration - we didn't have to do days_of_the_week[counter]
forin:Let's rewrite something like previous loops we've seen
with open("top_male_baby_names_2010s.txt") as male_names_file:
male_names = male_names_file.readlines()
total_length = 0
counter = 0
while counter < len(male_names):
male_names[counter] = male_names[counter].rstrip()
total_length += len(male_names[counter])
counter += 1
if counter != 0:
average_length = total_length/counter
print("Average length is",average_length)
#let's rewrite it here as a for loop
with open("top_male_baby_names_2010s.txt") as male_names_file:
male_names = male_names_file.readlines()
total_length = 0
for name in male_names:
name = name.rstrip()
total_length += len(name)
if len(male_names) > 0:
average_length = total_length/len(male_names)
print("Average length is",average_length)
Write a for loop that will diplay all the temperatures in the list.
temperatures = [30, 20, 2, -5, -15, -8, -1, 0, 5, 35]
Once you have that working, change it so that it only displays the negative temperatures.