python程序有问题(2.7.10)

2024-05-28 22:34:34 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我对python还比较陌生,在我的编程课上,我必须编写一个关于100米赛跑的程序,并根据完成比赛所花的时间来判断你是否合格。如果你是一个男性,你花了超过10.18秒才完成,那么你就没有资格。如果你是女性,花了超过11.29秒才完成,那么同样,你没有资格。你知道吗

我的问题是,无论你的时间是什么,这两条信息都会显示你是否合格。我使用的是python2.7.10。到目前为止,我的代码是:

gender = raw_input("Are you Male (M) or Female (F)?: ")
time = raw_input("What time did you get for the 100m race?: ")


if gender is "M" and time > 10.18:
    print "Sorry, you did not qualify"
else:
    print "Congratulations, you qualified!"

if gender is "F" and time > 11.29:
    print "Sorry, you did not qualify"
else:
    print "Congratulations, you qualified!"

Tags: andyouinputrawiftimeis时间
3条回答

else for each子句将始终运行,因为性别将始终与用户输入的内容相反。您还需要将第二个输入转换为float,以便正确地将值与10.18或11.29进行比较。你知道吗

要更正此问题(无需重构):

gender = raw_input("Are you Male (M) or Female (F)?: ")
time = float(raw_input("What time did you get for the 100m race?: "))

if gender is "M" and time > 10.18:
    print "Sorry, you did not qualify"    
elif gender is "F" and time > 11.29:
    print "Sorry, you did not qualify"
else:
    print "Congratulations, you qualified!"

尝试使用elif来更好地处理

if gender is "M" and time > 10.18:
    print "Sorry, you did not qualify"
elif gender is "F" and time > 11.29:
    print "Sorry, you did not qualify"
else:
    print "Congratulations, you qualified!"

原始输入返回一个字符串。你需要做什么 time = float(raw_input("What time..."))

(请注意,python允许您将字符串与float进行比较,但它不会尝试将字符串转换为匹配)

(编辑:如发帖时其他两个答案所示,你应该使用elif)

相关问题 更多 >

    热门问题