Как остановить цикл for, внутри цикла while в python - PullRequest
0 голосов
/ 04 мая 2018

Я создаю простую форму ввода данных о времени гонки атлета, мне нужно спрашивать каждый проход, хочет ли пользователь продолжить, если это так, то он идет снова, если нет, то он выходит из цикла while. Если пользователь не ввел по крайней мере 4-8 частей данных, он выдает ошибку вместо распечатки времени. Я полагаю, что ошибка вызвана тем, что после того, как она проходит цикл while в первый раз, она не делает еще один проход, пока не выполнит 8 в цикле for. Как бы мне обойти эту проблему. Пожалуйста, объясните свой код и соотнесите его с контекстом, который я дал.

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")

Ответы [ 3 ]

0 голосов
/ 04 мая 2018

Цикл for выполняет 8 итераций, несмотря ни на что, поэтому вы всегда будете входить в 8 дорожек. Вы можете полностью удалить цикл for и заменить его простым счетчиком. Увеличьте счетчик, когда пользователь решит добавить еще одну полосу, а когда она достигнет 8 - завершите цикл. Что-то вроде (в псевдокоде):

counter =0
while carry_on
  <read user input>
  if counter < 8
    <ask user to continue>
  if decision == "yes"
    counter++
    carry_on = true
  else
    carry_on = false
<handle input here>
0 голосов
/ 04 мая 2018

Вы можете использовать только один для цикла и инструкции разрыва:

for i in range(8):
    print("Inputting Data for Lane", i)
    gender = input("Is the athlete male or female ")
    athlete = 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

Обратите внимание, что диапазон (0, 8) можно записать: диапазон (8)

И input возвращает строку, поэтому str (input (...)) бесполезен.

Кроме того:

if 3 < i > 9

означает:

if i > 3 and i > 9:

Я думаю, что вы имеете в виду:

if 3 < i < 9:

Наконец: float (input (...)) может вызвать исключение ValueError, если пользователь вводит что-то, что не является числом. Вы должны добавить попытку: кроме: конструкция.

0 голосов
/ 04 мая 2018

Прежде всего, ИЗУЧИТЕ ОСНОВЫ

попробуйте взломать цикл не уверен, если время требуется

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")
...