2017-01-11 63 views
0

這是一個簡單的代碼,腳本會詢問用戶的姓名,年齡,性別和身高,並根據該代碼給出輸出。我當前的代碼如下:Python;基於用戶輸入的打印輸出

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) 

我收到掛了,如果,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高個子」。我無法弄清楚如何得到「你低於平均水平」的回報。

回答

1

這是因爲raw_input()返回一個字符串,而不是浮動,並且比較始終是一個字符串,在Python 2

>>> "1.0" > 6.0 
True 

做這一個浮子之間的相同的方式:

height = float(raw_input()) 

height = input()本來可以工作,但不鼓勵(因評估而導致的安全問題)

注意:這已在Python 3中修復(可能是因爲這是不是非常有用,而且容易出錯):試圖做到這一點在

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

這是明確的,將允許實現自己的錯誤造成的。

注:同樣的問題,如果你嘗試比較ageage = raw_input()應該age = int(raw_input())

+0

這完美。謝謝! –