其他声明不起作用。什么都没输入时如何关闭循环?

时间:2013-02-15 07:51:57

标签: python

其他声明不起作用。什么都没输入时如何关闭循环?关于如何处理的建议?

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 个答案:

答案 0 :(得分:2)

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

while name:

答案 1 :(得分:0)

你需要这个:

while len(name) > 0

答案 2 :(得分:0)

如果使用此if-else构造

未输入任何内容,则可以从循环中转义
if (name==''):
    break
else:
    <job to be done>

答案 3 :(得分: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..."实际告诉我们最慢的弓箭手的时间,而不是他们的名字