Ask for n python entries

Asked

Viewed 1,265 times

2

I’m having a hard time with this exercise:

"Do a program that asks n people your age, at the end the program should check if the average age of the class varies between 0 and 25, 26 and 60 and above 60; and then, tell if the class is "young", "adult" or "elderly", according to the calculated average. The program must finish when typed -1."

I don’t know how to ask for the age of n people. How would I do that ?

  • With the function input is a simple way.

3 answers

3

I don’t know how to ask for the age of n people. How would I do that ?

idade = 0
lista_com_idades = []
while idade != '-1':
    idade = input('Diga sua idade: ')
    lista_com_idades.append(idade)

This is the answer to your question. While the user does not type '-1' he keeps asking the age. I hope I’ve helped !

  • I found it bad the fact of age -1 be stored

2

In Python 3. I do not know if I understood the doubt. But the following works:

z=0
x=[]
while z != -1:
    z = int(input('Digite a idade: '))

    if z != -1:
        x.append(z)

if len(x) != 0:
    media = sum(x)/len(x)

m = round(media,0)

if 0 <= m <= 25:
    print('Populacao jovem')

if 26 <= m <= 60:
    print('Populacao adulta')

if m > 60:
    print('Populacao idosa')

Would that be?

EDIT: error in round, must be 0, not 1. Tbm includes m "if" to check if you have any age typed.

  • That’s right, I’m still learning to program, and n had knowledge of this x.append. Valeu !

  • 1

    You could have used the whole division sum(x)//len(x) to avoid rounding up

  • The problem with using sum(x)//Len(x) is that it always rounds down, as in int(), truncates the number instead of rounding. Right? (I’m new to programming)

-1

Can cycle in a user data range:

n = raw_input("Quantas pessoas são?")
for i in range(1,n):
blabla
  • Then that’s it, I can’t do a user-given loop, who will process the code is the run codes. Data entry must stop when typing "-1".

  • then do a while,

  • You are reading n-1 data. And it’s also Python 2 that raw_input in my memory

Browser other questions tagged

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