Цикл while для постоянного запроса правильного типа ввода - PullRequest
0 голосов
/ 08 февраля 2019

У меня проблема с домашней работой, и мне нужно добавить цикл while в мою функцию, который даст пользователю 3 дополнительные попытки ввести другое значение, если первоначально введенное значение не является числом.Первоначальная функция кода заключается в определении площади треугольника или трапеции.

loopCount = 0
# The "while" statement keeps looping until its condition (loopCount<4) made False.
while loopCount<4:
    # loopCount will increase 1 for each loop
    loopCount += 1

Хотя я даже не уверен, где разместить вышеупомянутые строки в моем коде.

    # This program calculates the area of a triangle or trapezoid

    # Statement: print function outputs the statement on screen  
    print("This program finds the area of a triangle or trapezoid.")
    print()

    # Module: math module imported
    import math

    # Determine the objects shape
    print("Please enter the shape from the following menu")
    print("Triangle = type 1")
    print("Trapezoid = type 2")

    # If user types a number other than 1 or 2, this will prompt them again to pick a valid choice
    user_input = 0
    while user_input not in (1,2) :
            user_input = int(input("Enter your choice: "))

    # Variables: asigns new value to a variable depending on which shape we are caluclating the area of
    if (user_input == 1):
        print("Alright, you want to calculate the area of a triangle: ")
        height = float(input("Please enter the height of the triangle: "))
        base = float(input("Please enter the base length of the triangle: "))

    if (user_input == 2):
        print("Alright, you want to calculate the area of a trapezoid: ")
        base_1 = float(input("Please enter the base length of the trapezoid: "))
        base_2 = float(input("Please enter the second base length of the trapezoid: "))
        height = float(input("Please enter the height of the trapezoid: "))

    # Expression and operators: calculates area based on shape choosen.  Triangle_area = (base*height)/2, Trapezoid_area = ((base1+base2)/2)*height
    if (user_input == 1):
        area_triangle = 0.5 * height * base
    if (user_input == 2):   
        area_trapezoid = ((base_1+base_2)/2)*height

    # Function: math function returns a statement defining the height, base(s) and area of the triangle or trapezoid
    if (user_input == 1):
        print("The area of a triangle with height", height, "and base", base, "is", area_triangle)

    if (user_input == 2): 
        print("The area of a trapezoid with height", height, ", base 1", base_1, "and base 2", base_2, "is", area_trapezoid)

    If the user enters a value that could not be converted to numeric type, allow 3 additional opportunities to enter a new value. If the user fails to enter a correct value after 4 attempts, inform them of such failure and allow the program to end without crashing.

1 Ответ

0 голосов
/ 08 февраля 2019

Вы можете использовать try / кроме на входе для обработки ValueError, когда float() не может преобразовать значение в число с плавающей запятой илиOverflowError ", если аргумент находится вне диапазона числа с плавающей точкой Python ".

loopCount = 0
while loopCount < 4:
    try:
        height = float(input("Please enter the height of the triangle: "))
        break
    except:
        print("That is not a number.")
        loopCount += 1 

if loopCount == 4:
    print("You failed to input valid values")
    # return with an error or maybe abort with sys.exit(1)
else:
    print("Great! I can now compute stuff.")

Вы можете проверить все входы одновременно внутриБлок try (если вам все равно, какой из них является недействительным, или вам не нужно указывать это пользователю):

loopCount = 0
while loopCount < 4:
    try:
        base_1 = float(input("Please enter the base length of the trapezoid: "))
        base_2 = float(input("Please enter the second base length of the trapezoid: "))
        height = float(input("Please enter the height of the trapezoid: "))
        break
    except:
        print("One of the inputs is not a number.")
        loopCount += 1 

if loopCount == 4:
    print("You failed to input valid values")
    # return with an error or maybe abort with sys.exit(1)
else:
    print("Great! I can now compute stuff.")

Чтобы избежать многократных повторений try-exceptЯ предлагаю создать метод для получения входных данных с плавающей запятой (или всех входных данных), а затем просто вызвать его из основного метода.

...