【问题标题】:Python; printing outputs based on user inputPython;根据用户输入打印输出
【发布时间】:2017-01-11 20:25:36
【问题描述】:

这是一个简单的代码,脚本会询问用户的姓名、年龄、性别和身高,并根据这些信息给出输出。我目前的代码如下:

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”。我不知道如何获得“你低于平均水平”的回报。

【问题讨论】:

    标签: python-2.7


    【解决方案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())

    【讨论】:

      猜你喜欢
      • 2020-11-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-19
      • 1970-01-01
      • 2012-07-20
      • 2013-10-03
      相关资源
      最近更新 更多