Nested structure giving error

Asked

Viewed 40 times

0

I’m trying to create a script that reads if the person is older or younger. I would like if for example only 1 person is bigger, it writes '1 person' and not '1 people', but my code is giving some error if all people are smaller or larger, but it works if I merge. What can it be?

from datetime import date
atual = date.today().year
maior = menor = cont = 0
for nasc in range(1, 4):
    cont += 1
    nasc = int(input(f'Ano de nascimento da {cont}ª pessoa:'))
    idade = atual - nasc


    if idade >= 18:
        maior += 1
        if maior != 1:
            p1 = 'pessoas'
        else:
            p1 = 'pessoa'
    else:
        menor += 1
        if menor != 1:
            p2 = 'pessoas'
        else:
            p2 = 'pessoa'

print(f'{maior} {p1} de maior e {menor} {p2} de menor')
  • 1

    If all people are older than 18 (or younger) no attribution to the variable P2 (or P1) will occur but you consider such variables in print. As well as initializing the variables larger, smaller and cont initialize also the variables P1 and P2.

  • You don’t actually need these variables P1 and P2: https://ideone.com/epxCR0

  • Thank you very much!

1 answer

0

Simplify logic, remember that knowing if you are "person" or "people" during the loop is irrelevant since this information will change with each loop execution for.

It’s information that only matters when the message is printed, so...

from datetime import date

atual = date.today().year
maior = menor = 0

for cont in range(1, 4):
    nasc = int(input(f'Ano de nascimento da {cont}ª pessoa:'))
    idade = atual - nasc

    if idade >= 18:
        maior += 1
    else:
        menor += 1

p1 = "pessoa" if maior==1 else "pessoas"
p2 = "pessoa" if menor==1 else "pessoas"

print(f'{maior} {p1} de maior e {menor} {p2} de menor')

This structure, the p1 = ... if ... else ... is Python’s ternary and does the same thing as a...

if maior == 1:
    p1 = "pessoa"
else
    p1 = "pessoas"

Only occupying only one line. :-)

Ah, remember that we say 0 people and not 0 person!

Browser other questions tagged

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