Jason Kral
Jason Kral

Reputation: 23

Python; printing outputs based on user input

This is a simple code where the script would ask for the user's name, age, sex, and height and give an output based on that. My current code is as follows:

print "What is your name?"
name = raw_input()
print "How old are you?"
age = raw_input()
print "Are you male? Please answer Y or N"
sex = raw_input()
if sex == "Y" or sex == "y":
    sex = "Male"
else:
    sex = "Female"
print "How tall are you? Please enter in feet such as 5.5"
height = raw_input()

if sex == "Male" and height >= 6.0:
    t = "You are tall for a male"
elif sex == "Male" and height < 6.0:
    t = "You are below average for a male"

elif sex == "Female" and height >= 5.5:
    t = "You are tall for a female"
else:
    t = "You are below average for a female"


print "Hello %s. You are %s years old and %s feet tall. %s." % (name, age, height, t)

I am getting hung up on the if, elif, else statement:

if sex == "Male" and height >= 6.0:
    t = "You are tall for a male"
elif sex == "Male" and height < 6.0:
    t = "You are below average for a male"

elif sex == "Female" and height >= 5.5:
    t = "You are tall for a female"
else:
    t = "You are below average for a female"

The code will differentiate if sex is Male or Female, but will always return "You are tall for a xxx". I can not figure out how to get the "You are below average" return.

Upvotes: 0

Views: 2304

Answers (1)

Jean-Fran&#231;ois Fabre
Jean-Fran&#231;ois Fabre

Reputation: 140168

That's because raw_input() returns a string, not a float, and comparison is always the same way between a string and a float in Python 2.

>>> "1.0" > 6.0
True

Do this:

height = float(raw_input())

height = input() would have worked too but is discouraged (security issues because of evaluation)

Note: this has been fixed in Python 3 (probably because it wasn't very useful, and error-prone): trying to do this results in

TypeError: unorderable types: str() > float()

which is explicit and would have allowed to realize your mistake.

Note: same issue if you try to compare age (age = raw_input() should be age = int(raw_input()))

Upvotes: 1

Related Questions