> Solution 1: In the normal method>>">

Finding avg of continuous numbers in normal method Vs by using data structures

05 min read

Find the average of continuous numbers entered by the user until the user enters "done" indicating the end of the program.

  1. basic loops in Python.
  2. by using data structures.

Solution 1: In the normal method>>

total =0                                               #initialise the sum value to be zero in the start of the program
count=0 # initialise the count value to 0 to check the number of entries
while True: # forever loop
inp = input('Enter number:')
if inp == 'done': # if user enters "done" get out of the loop and calculate final average
break
value = float (inp) # remember all values entered in the input by the user are takenin as strings by default, hence convery to int or float.
total +=value # calculate the sum, tot = previous_tot + new_value
count +=1 # increase number of entries by one
average=total/count
print(avg)

Solution 2: By using data structures in Python >>

numList= list()       # create an empty list
while true:
inp=input('Enter number')
if inp == 'done' : break # if an 'if' statement has only onecondition in it, the syntax can directly bewritten as shown.
value = float(inp)
numlist.append(value) # add new elements to the list from the end
average = sum(numList)/ len(numList) # sum() is a inbuilt function to add all elements in a list. len() returns the total number of elements in the matrix
print(average)

 

POST A NEW COMMENT
     
  • Input (stdin)

    Output (stdout)


    Input (stdin)

    Your Output (stdout)

    Expected Output

    Compiler Message

    Input (stdin)

    2    3

    Your Output (stdout)

    5

    Expected Output

    5

    Compiler Message

    5

    Error