+ 2

Calculate results in a while loop

Hi guys, How you doin' ? :) I'm coming here because i have a question about the while loop. In a code that I'm testing, I made a while loop who are doing a mathematical operation while i<100 (with i=0) that give me a result each time. I want to know if, instead of print() each result, i can make the addition and the average of all the 100 results and print this only average result? Thanks for your answers. And sorry for my weak english, french guy here ! ^^ GregGS

1st Aug 2020, 7:50 PM
Greg GS
Greg GS - avatar
4 Respuestas
+ 6
Where's your attempt? Anywhere I've put comment too for you to understand. i = 0 # for iterating upto 100 _sum = 0 # for storing the sum of 100 nos while i <= 100: # loop for until i is less than or equal to 100 _sum += i # add each number i += 1 # increment the no. (1,2,3,4,5,..) print("the average of 100 nos", _sum/100) #print the average of 100 nos.
1st Aug 2020, 7:53 PM
minirkk
minirkk - avatar
+ 3
Hmmm, ok I see... I think it is the variable sum or add who are missing in my code when I compare it to your examples. I will see, thanks for your answers guys.
1st Aug 2020, 8:11 PM
Greg GS
Greg GS - avatar
+ 2
i=0 add=0 while i<100: add+=i i+=1 print(add) if you keep print statement out of while loop ,final value of add is printed
1st Aug 2020, 7:54 PM
Abhay
Abhay - avatar
+ 2
Just to be sure that i understand the concept of the while loop, if i want to addition the 100 results of score_Team1 and score_Team2, this is that two variables that I need to increment += i ? from random import randint i=0 score_Team1 = 0 score_Team2 = 0 while i < 100: # Criteria for Home Team nbr_HalfDistance1 = randint(90,110) nbr_Exterior1 = randint(40,60) nbr_FreeThrow1 = randint(10,30) accuracy_HalfDistance1 = randint(40,70) / 100 accuracy_Exterior1 = randint(20,50) / 100 accuracy_FreeThrow1 = randint (60,100) / 100 # Criteria for Away Team nbr_HalfDistance2 = randint(90,110) nbr_Exterior2 = randint(40,60) nbr_FreeThrow2 = randint(10,30) accuracy_HalfDistance2 = randint(40,70) / 100 accuracy_Exterior2 = randint(20,50) / 100 accuracy_FreeThrow2 = randint (60,100) / 100 # Operation for calculate the number of points scored by Home Team score_Team1 = int((((nbr_HalfDistance1 * accuracy_HalfDistance1) * 2) + ((nbr_Exterior1 * accuracy_Exterior1) * 3) + (nbr_FreeThrow1 * accuracy_FreeThrow1))) # Operation for calculate the number of points scored by Away Team score_Team2 = int((((nbr_HalfDistance2 * accuracy_HalfDistance2) * 2) + ((nbr_Exterior2 * accuracy_Exterior2) * 3) + (nbr_FreeThrow2 * accuracy_FreeThrow2))) i += 1 score_Team1 += i score_Team2 += i print(str(score_Team1) + "-" + str(score_Team2))
1st Aug 2020, 8:39 PM
Greg GS
Greg GS - avatar