If, ELIF and ELSE
I am taking my first steps in Python, and I have a doubt in the IF/else sentence, trying to solve the following exercise:
" having as input data the height and sex of a person, construct an algorithm that calculates his ideal weight, using the following formulas:
For men: (72.7 * h) - 58
For women: (62.1*h) - 44.7 (h = height)
Ask for the person's weight and let them know if they are in, above or below the weight."
This was the logic used by me:
def main():
altura = float(input("Digite a altura do paciente: "))
sexo = input("Digite o sexo do paciente, H(Masculino) ou F(Feminino): ")
altura
if sexo == H or sexo == h:
peso = (72.7 * altura) - 58
print ("O peso ideal do paciente é: ",peso)
elif sexo == F or sexo == f:
peso = (62.1 * altura) - 44.7
print ("O peso ideal da paciente é: ",peso)
else:
print ("Sexo inválido")
pesopaciente = input("Digite o seu peso: ")
if pesopaciente < peso:
print("Você está abaixo do peso ideal.")
elif pesopaciente > peso:
print("Você está acima do peso ideal.")
else:
print("Você está na média de peso.")
main()
However, it returns the following error:
Traceback (most recent call last):
File "python", line 12
Elif sex = = F or sex = = f:
^
SyntaxError: invalid syntax
Could you help me?
Grateful!
2 answers
When you put sexo == H
it understands that you are referring to the variable H
. Put in quotation marks, like this: sexo == "H" or sexo == "h"
Also the indentation is all wrong. The contents of the function main
are not indented, and elif
and else
must be in the same column as if
.
Read this article:
I don't have python 3 with me to test, only 2.7... but I believe this code will work:
def main():
altura = float(input("Digite a altura do paciente: "))
sexo = input("Digite o sexo do paciente, H(Masculino) ou F(Feminino): ")
if sexo == "H" or sexo == "h":
peso = (72.7 * altura) - 58
print ("O peso ideal do paciente é: ",peso)
elif sexo == "F" or sexo == "f":
peso = (62.1 * altura) - 44.7
print ("O peso ideal da paciente é: ",peso)
else:
print ("Sexo inválido")
pesopaciente = input("Digite o seu peso: ")
if pesopaciente < peso:
print("Você está abaixo do peso ideal.")
elif pesopaciente > peso:
print("Você está acima do peso ideal.")
else:
print("Você está na média de peso.")
main()
In addition to fixing the indentation and quotation mark problem, you should use the function raw_input()
instead of the simple function input()
. When using the input()
function, the user must type " h " (with quotation marks) for the program to recognize the character as a string.
The input()
function recognizes user input as Python code. That is, by entering only h (without quotes), python would try to evaluate this variable, which does not exist in your program.
The function raw_input (), in turn, returns the sequence of ASCII characters entered by the user before pressing ENTER, and this sequence of characters is interpreted as a string.