Function Return after Eoferror [Python]

Asked

Viewed 69 times

0

Good afternoon, I need to solve the following problem using the While structure:

Given a sequence of real values, calculate your average.

The command given by the teacher was:

while True:
    try:
        valor = float(input())
        # processar o valor
    except EOFError:
        break

And I developed the following code:

while True:
    try:
        n = input()
        seq_break = n.split(',')
        armazena = 0
        cont = 0

        for val in seq_break:
            armazena += float(n)
            cont += 1
        a = (armazena/cont)
        print(a)

    except EOFError:
        break

Meanwhile, I’m having trouble getting out. Instead of returning me the average of the values (expressed in variable a) it is returning me either all the input values or the last value. I don’t know where I’m going wrong.

  • 1

    Are you running this program for some platform that the teacher made available?

1 answer

1


You are iterating over the numbers stored in the array seq_break with the value val and not with the value of n. The right thing would be:

while True:
try:
    n = input()
    seq_break = n.split(",")
    armazena = 0
    cont = 0

    for val in seq_break:
        armazena += float(val)
        cont += 1
    a = (armazena/cont)
    print(a)

except EOFError:
    break

Browser other questions tagged

You are not signed in. Login or sign up in order to post.