尝试并除外覆盖以循环用户输入

时间:2018-09-11 07:28:05

标签: python

我一直在尝试尝试,除了进入for循环。它可以正常工作,但是for循环仅保存最后的赛车比赛,而不是所有赛车的比赛。 我相信这是由于尝试和除外。

for name in [runner1, runner2, runner3]:
    while True:
        try:
            race1 = int(input(name + ": Enter runner placing for race 1:"))
            race2 = int(input(name + ": Enter runner placing for race 2:"))
            race3 = int(input(name + ": Enter runner placing for race 3:"))
            race4 = int(input(name + ": Enter runner placing for race 4:"))
        except ValueError:
            print("Enter a integer")
            continue
        break

3 个答案:

答案 0 :(得分:1)

也许简短的重新设计在这里会有所帮助。

for name in [runner1, runner2, runner3]:
    race = dict()
    for r in range(4):
        while True:
            try:
                race[r] = int(input("{0}: Enter runner placing for race {1}:".format(name, r+1)))
            except ValueError:
                print("Enter a integer")
                continue
            break
    # do something for this particular value of race[]
    # before continuing on to the next runner

如果您无法处理循环中的输入,则将它们保存在字典中。

runners = {x: None for x in [runner1, runner2, runner3]}
for name in runners.keys():
    race = dict()
    for r in range(4):
        while True:
            try:
                race[r] = int(input("{0}: Enter runner placing for race {1}:".format(name, r+1)))
            except ValueError:
                print("Enter a integer")
                continue
            break
    runners[name] = race

在这一点上,runners[runner1][2]具有种族3的runner1值(记住Python数组索引是从零开始的。)

答案 1 :(得分:0)

问题可能是,您遍历循环的每一轮都覆盖了先前的输入。只有一个变量race1,然后在下一次迭代中为其分配新值。更好的设计是从跑步者到种族的位置建立一个字典,如下所示:

runners = {runner1:[], runner2:[], runner3:[]}
for runner in runners:
    while True:
        try:
            race1 = int(input(name + ": Enter runner placing for race 1:"))
            race2 = int(input(name + ": Enter runner placing for race 2:"))
            race3 = int(input(name + ": Enter runner placing for race 3:"))
            race4 = int(input(name + ": Enter runner placing for race 4:"))
            runners[runner] = [race1, race2, race3, race4]
        except ValueError:
            print("Enter a integer")
            continue
        break

这将为您提供一本字典,其中包含跑步者作为关键字,并列出其位置作为值。

答案 2 :(得分:0)

我会更改您的代码以进行更好的设计。另外,将race1-4的值存储在某种类型的集合中,然后在其他循环中将其丢失

for name in [runner1, runner2, runner3]:
    race1 = inputForRace(1)
    race2 = inputForRace(2)
    race3 = inputForRace(3)
    race4 = inputForRace(4)


def inputForRace(raceOrder):
   shouldContinue = True
   race = 0
   while shouldContinue:
      try:
         race = int(input(name + ": Enter runner placing for race {0}:".format(raceOrder)))
         shouldContinue = False
      catch ValueError:
        print("Enter integer")
        shouldContinue = True
   return race