how to decrease ifs? in python

Asked

Viewed 91 times

-2

I’m starting in programming and would like to know if I have how to decrease the uses of ifs

"""

Classification of a person by height and weight

alt = float(input("Digite a sua altura"))

p = float(input('Digite seu peso'))


if alt < 1.20 and p <= 60:
    print(f'Classificação A')
elif alt < 1.20 and 60 < p < 90:
    print(f'Classificação D')

elif alt < 1.20 and p > 90:
    print(f'Classificação G')

elif 1.20 < alt < 1.70 and p <= 60:
    print(f'Classificação B')

elif 1.20 < alt < 1.70 and 60 < p < 90:
    print(f'Classificação E')

elif 1.20 < alt < 1.70 and p > 90:
    print(f'Classificação H')

elif alt > 1.70 and p <= 60:
    print('Classificação C')

elif alt > 1.70 and 60 < p < 90:
    print('Classificação F')

elif alt > 1.70 and p > 90:
    print('Classificação I')
  • 1

    For this code, I see no reason to decrease the ifs, but you can replace it with switch or by a função (def)

  • 3

    I still do not intend the difficulty of copy and stick together the code... the person does the hardest and the least helps...

  • will not decrease but uses logic to optimize, look carefully and see that vc validates 3 times (alt < 1.20), 3 times (1.20 < alt < 1.70) and 3 times (alt > 1.70), the ideal is to decrease to only one validation

1 answer

1

Hello,

Try testing the extremes first: For example, all heights less than 1.20, and within that, all weights. And also for weights: less than 60, or more than 90.

Example:

alt = float(input("Digite a sua altura"))

p = float(input('Digite seu peso'))


if alt < 1.20:
  if p <= 60:
    print(f'Classificação A')
  elif p >= 90:
    print('Classificação G')
  else:
    print(f'Classificação D')
elif alt > 1.70:
  if p <= 60: 
    print('Classifição C')
  elif p > 90:
    print('Classificação I')
  else: 
    print('Classificação F')
else: 
  if p <= 60:
    print('Classificação B')
  elif p > 90:
    print('Classificação H')
  else: 
    print('Classificação E')

Browser other questions tagged

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