Цикл массива Python не вызывает циклов / проблем с валидатором - PullRequest
0 голосов
/ 26 мая 2019

Я не совсем уверен, что я сделал, но при тестировании моего кода он либо сразу падает, либо застревает в цикле.Если первый вход представляет собой значение ошибки (строка), а следующий - число, оно повторяется до тех пор, пока сохраняется шаблон.Но если первый пользователь введен как int, то программа вылетает.Пожалуйста, любая помощь будет оценена.

def main():
    courseArray = []
    keepGoing = "y"
    while keepGoing == "y":
        courseArray = getValidateCourseScore()
        total = getTotal(courseArray)
        average = total/len(courseArray)
        print('The lowest score is: ', min(courseArray))
        print('The highest score is: ', max(courseArray))
        print('the average is: ', average)
        keepGoing = validateRunAgain(input(input("Do you want to run this program again? (Y/n)")))


def getValidateCourseScore():
    courseArray = []
    counter = 1
    while counter < 6:
        try:
            courseArray.append(int(input("Enter the number of points received for course: ")))
            valScore(courseArray)
        except ValueError:
            print("Please enter a valid score between 0-100")
            courseArray.append(int(input("Enter a number between 1 and 100: ")))
    counter += 1
    return courseArray


def valScore(courseArray):
    score = int(courseArray)
    if score < 0:
        print("Please enter a valid score between 0-100")
        courseArray.append(int(input("Enter a number between 1 and 100: ")))
    elif score > 100:
        print("Please enter a valid score between 0-100")
        courseArray.append(int(input("Enter a number between 1 and 100: ")))
    else:
        return courseArray

def validateRunAgain(userInput):
    if userInput == "n" or userInput == "N":
        print("Thanks for using my program")
        return "n"
    elif userInput == "y" or userInput == "Y":
        return "y"
    else:
        print("Please enter y or n")
        validateRunAgain(input("Do you want to run this program again? (Y/n)"))
        return getValidateCourseScore()

def getTotal(valueList):
    total = 0
    for num in valueList:
        total += num
    return total

main()

1 Ответ

0 голосов
/ 26 мая 2019

Слишком много входных данных от пользователя, поэтому я сократил их и изменил.
Вот разделы вашего кода, которые я изменил:
Здесь valScore() Я предполагаю, что проверяет входную оценку, поэтому я также дал индекс элемента, который должен быть проверен. Если он недействителен, мы удаляем его из массива и вызываем ValueError, поскольку он вызывает ошибку, наш counter не обновляется.

keepGoing = validateRunAgain()

def getValidateCourseScore():
    courseArray = []
    counter = 1
    while counter < 6:
        try:
            courseArray.append(int(input("Enter the number of points received for course: ")))
            valScore(courseArray, counter - 1)
            counter += 1
        except ValueError:
            print("Please enter a valid score between 0-100")
            continue
    return courseArray

def valScore(courseArray, counter):
    score = courseArray[counter]
    if score < 0 or score > 100:
        courseArray.pop()
        raise ValueError

def validateRunAgain():
    while True:
        userInput = input("Do you want to run this program again? (Y/n)")
        if userInput == 'y' or userInput == 'Y':
            return 'y'
        elif userInput == 'n' or userInput == 'N':
            print('thank you for using my program')
            return 'n'
        else:
             print('Enter Y or N')
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...