Close
Close

while loop query

   Nitin-diwakar123

When I’m using while to do:-

>>Take 10 integers from keyboard using loop and print their average value on the screen.

when I’m writing in last line – print(“Average is”, avg)

so it print multiple times ‘Average’ also like this-

>>OUTPUT:-

Enter number: 1

Average 0.1

Average 0.2

Average 0.3

Average 0.4

Average 0.5

Average 0.6

Average 0.7

Average 0.8

Average 0.9

Average 1.0

 


Answers

  •   

    It is getting printed multiple times because you are printing it inside the loop.

    In the following code, I created a variable sum to which each number gets added in each iteration of the while loop. After all the 10 iterations of the while loop have been completed, the sum variable stores the sum of all the 10 numbers entered by the user. After that, the average is calculated and printed.

    sum = 0
    i = 0
    
    while i < 10:
    	n = int(input("Enter a number"))
    	sum = sum + n
    	i = i + 1
    
    avg = sum/10
    print("Average: ", avg)
    

     



Ask Yours
Post Yours
Write your answer