Lets say I have three lists and I need to iterate through them and do some stuff to the contents.
The three lists are streaks_0
, streaks_1
, and streaks_2
. For each list, I need to use different values specific to each list. For example, streak_0_num0s
will not work in the streaks_1
for loop.
Is there a way to make these three for loops into one or at least a way to clean this up?
for number in streaks_0:
if number == 0:
streak_0_num0s += 1
elif number != 0:
streak_0_sum += number
streak_0_average = (streak_0_sum / (len(streaks_0) - streak_0_num0s))
for number in streaks_1:
if number == 0:
streak_1_num0s += 1
elif number != 0:
streak_1_sum += number
streak_1_average = (streak_1_sum / (len(streaks_1) - streak_1_num0s))
for number in streaks_2:
if number == 0:
streak_2_num0s += 1
elif number != 0:
streak_2_sum += number
streak_2_average = (streak_2_sum / (len(streaks_2) - streak_2_num0s))
Python provides two keywords that terminate a loop iteration prematurely: The Python break statement immediately terminates a loop entirely. Program execution proceeds to the first statement following the loop body. The Python continue statement immediately terminates the current loop iteration.
The only way to exit a repeat loop is to call break.
You can do the same type of for loop if you want to loop over every character in a string. To loop through a set of code a certain number of times, you can use the range() function, which returns a list of numbers starting from 0 to the specified end number.
You can stop an infinite loop with CTRL + C . You can generate an infinite loop intentionally with while True . The break statement can be used to stop a while loop immediately.
Why not use a function?
def get_average(streaks):
streak_0_num0s = 0
streak_0_sum = 0
for number in streaks:
if number == 0:
streak_0_num0s += 1
elif number != 0:
streak_0_sum += number
streak_0_average = (streak_0_sum / (len(streaks) - streak_0_num0s))
print(streak_0_average)
get_average(streaks01)
get_average(streaks02)
get_average(streaks03)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With