1

else 语句不起作用。什么都没有输入时如何关闭循环?关于如何处理的建议?

def main():
    print "~*~*~*~*~*~ Timbuktu Archery Contest ~*~*~*~*~*~"
    archerList = [] #list
    timeList = [] #list2
    name = raw_input ("Enter contestants first name: ")
    s = str(name)
    archerList.append(name)
    while name > 0:
        time = raw_input ("Enter time (in milliseconds) for %s: " % s)
        timeList.append(time)
        name = raw_input ("Enter contestants first name: ")
        s = str(name)
        archerList.append(name)
    else:
        name == ""
        print "Slowest archer was " , min(timeList)
        print "Fastest archer was " , max(timeList)
4

4 回答 4

2

循环直到给出一个空名称:

while name:
于 2013-02-15T07:58:06.717 回答
0

如果没有输入任何内容,则可以使用此 if-else 构造退出循环

if (name==''):
    break
else:
    <job to be done>
于 2013-02-15T10:13:49.487 回答
0

你需要这个:

while len(name) > 0
于 2013-02-15T08:00:16.933 回答
0

这更像是pythonic。DRY = 不要重复自己。

def main():
    print "~*~*~*~*~*~ Timbuktu Archery Contest ~*~*~*~*~*~"
    min = max = 0
    while True:
        name = raw_input ("Enter contestants first name: ")
        if not name:
            break
        start = raw_input ("Enter time (in milliseconds) for %s: " % name)
        min = start if start < min else min
        max = start if start > max else max
    print "Slowest archer was %i" % min
    print "Fastest archer was %i" % max

需要考虑的要点:

  • 我删除archerList了,因为您没有在代码中从中获取值
  • 如果弓箭手达到相同的时间会发生什么?
  • "slowest archer was..."实际上告诉我们射手最慢的时间,而不是他们的名字
于 2013-02-15T13:00:13.363 回答