简体   繁体   中英

While loop to continuously prompt user to provide correct input type

I have a homework problem and I need to add a while loop to my function that will give the user 3 additional tries to enter another value if the value originally entered is not a number. The original function of the code is to determine the area of a triangle or trapezoid.

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

Though I'm not even sure where to fit the above lines in my code.

    # 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.

You can use a try/except on the input to handle the ValueError when float() fails to convert the value to a float or an OverflowError " if the argument is outside the range of a Python float ".

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

You can check for all the inputs at once inside the try block (if you don't care which one specifically is invalid or you don't need to point it out to the user):

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

To avoid lots of repeated try-except 's, I suggest creating a method for getting a float input (or all of the inputs), and then just calling it from your main method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM