首页 > 解决方案 > 如何在python的while循环内停止for循环

问题描述

我正在制作一个简单的运动员比赛时间数据输入表单,我需要它询问每次用户是否要继续,如果是,那么它会再次执行,如果不是,则退出 while 循环。如果用户没有输入至少 4-8 条数据,那么它会产生错误而不是打印出时间。我相信错误是由于它第一次通过while循环后,它不会再通过,直到它在for循环中执行8。我将如何解决这个问题。请解释您的代码,并将其与我给出的上下文相关联。

import time
datasets= []
carry_on = True


while carry_on == True:
    for i in range(0, 8):
        print("Inputting Data for Lane", i)
        gender = str(input("Is the athlete male or female ")) 
        athlete = str(input("What is the athletes name "))
        finishTime = float(input("What was the finishing time "))
        dataset = [gender, athlete, finishTime]
        datasets.append(dataset)
        decision = input("Would you like to add another lane ")
        if decision == "yes":
            carry_on = True
        else:
            carry_on = False

print("")

if 3 < i > 9:
    print("{0:<10}{1:<10}{2:<15}".format("Gender","Athlete","Finish time"))
    ds = sorted(datasets, key=lambda x:x[2], reverse=False)
    for s in ds:
        time.sleep(1)
        print("{0:<10}{1:<10}{2:<15}".format(s[0], s[1], s[2]))
else:
    print("You have not chosen enough lanes, please choose atleast 4")

标签: pythonpython-3.xfor-loopwhile-loopboolean

解决方案


首先,学习基础知识

尝试闯入 for 循环不确定是否需要 while

for i in range(0, 8):
    print("Inputting Data for Lane", i)
    gender = str(input("Is the athlete male or female ")) 
    athlete = str(input("What is the athletes name "))
    finishTime = float(input("What was the finishing time "))
    dataset = [gender, athlete, finishTime]
    datasets.append(dataset)
    decision = input("Would you like to add another lane ")
    if decision != "yes":
        break

// 按照你的代码和你的要求

import time
datasets= []
carry_on = True


while carry_on == True:
    for i in range(0, 8):
        print("Inputting Data for Lane", i)
        gender = str(input("Is the athlete male or female ")) 
        athlete = str(input("What is the athletes name "))
        finishTime = float(input("What was the finishing time "))
        dataset = [gender, athlete, finishTime]
        datasets.append(dataset)
        decision = input("Would you like to add another lane ")
        if decision == "yes":
            carry_on = True
        else:
            carry_on = False
            break

print("")

if 3 < i > 9:
    print("{0:<10}{1:<10}{2:<15}".format("Gender","Athlete","Finish time"))
    ds = sorted(datasets, key=lambda x:x[2], reverse=False)
    for s in ds:
        time.sleep(1)
        print("{0:<10}{1:<10}{2:<15}".format(s[0], s[1], s[2]))
else:
    print("You have not chosen enough lanes, please choose atleast 4")

推荐阅读