这是一个简单的代码,脚本会询问用户的姓名,年龄,性别和身高,并根据该代码提供输出。我目前的代码如下:
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)
我对if,elif,else语句感到很沮丧:
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"
如果性别是男性或女性,代码将区分,但总会返回“你是一个高xxx”。我无法弄清楚如何获得“你低于平均水平”的回报。
答案 0 :(得分:1)
那是因为raw_input()
返回一个字符串,而不是一个浮点数,并且在Python 2中字符串和浮点数之间的比较总是相同的。
>>> "1.0" > 6.0
True
这样做:
height = float(raw_input())
height = input()
也会起作用但不鼓励(因为评估而导致安全问题)
注意:这在Python 3中已得到修复(可能因为它不是非常有用且容易出错):尝试这样做会导致
TypeError: unorderable types: str() > float()
这是明确的,并且可以让你意识到自己的错误。
注意:如果您尝试比较age
同样的问题(age = raw_input()
应为age = int(raw_input())
)