Sometimes we will want to add to something repeatedly using a loop.
The basic format of an accumulator loop is this:
start with an "empty" variable outside the loop
add to that variable within your loop
Here are 3 examples:
total = 0
for num in range(times):
value = int(input("input a value"))
total += value
print(total)
print("Average " + str(total/times))
text = ""
for i in range(times):
word = int(input("input a word"))
total += word
print(total)
word_list = []
for i in range(times):
word = int(input("input a word"))
word_list.append(word)
print(word_list)
Counting loops count how many times something has happened. To create a counting loop:
set a count variable to 0 outside the loop
inside the loop, if the event occurs, add 1 to the count
Detection loops determine whether something has happened (True/False). To create a detection loop.
set a detection variable to False
inside the loop, if the event occurs, set the detection variable to true (and break if you want to reduce runtime)
fives_count = 0
for i in range(times):
value = int(input("input a value"))
if value == 5:
fives_count += 1
print(fives_count)
five_detected = False
for i in range(times):
value = int(input("input a value"))
if value == 5:
five_dectected = True
break
print(five_detected)
Maximum-finding loops find the biggest value.
Set the first value as the maximum. (If you know that your values are positive, you can also set the maximum to 0.)
In the loop, check if each value is larger than the current maximum. If it is, it becomes the maximum.
( You may write a loop to detect the minimum in a similar way. )
max = -1e99 #a really small number
for i in range(times):
value = int(input("input a value"))
if value > max or i == 0:
max = value
print(max)
max = my_list[0]
for value in my_list:
if value > max:
max = value
print(max)
min = 1e99 #a really big number
for i in range(times):
value = int(input("input a value"))
if value < min or i == 0:
min = value
print(min)
min = my_list[0]
for value in my_list:
if value < max:
min = value
print(min)