Home > other >  I'm trying to get this code to start over if the shape entered is invalid, how would I go about
I'm trying to get this code to start over if the shape entered is invalid, how would I go about

Time:03-16

I'm trying to make a program that finds the total area of multiple shapes. First I find the amount of shapes, then the type of shape, then add it all up. I'm trying to have the user re-enter the type of shape if the input is incorrect. I tried to use return in the last else, but I keep getting an error stating that it isn't within a function. I can't seem to figure out how to repeat shape_type if the input is invalid.

shape_type = input("Type of shape (circle, rectangle, or triangle): ")
    print(shape_type)
    if shape_type == "circle":
        Radius = int(input("Radius: "))
        total_area  = (math.pi * Radius**2)
    elif shape_type == "rectangle":
        Length = int(input("Length: "))
        Height = int(input("Height: "))
        total_area  = (Length * Height)
    elif shape_type == "triangle":
        Base = int(input("Base: "))
        Height = int(input("Height: "))
        total_area  = ((1/2) * Base * Height)
    else:
        print("Shape is Not Valid") 

CodePudding user response:

Wrap the input in a while True loop, and only break out of the loop if the input is valid.

while True:
    shape = input("...")
    if shape in ["circle", "square", "triangle"]:
        break
    else:
        print("Invalid answer, please try again")

# now process the shape which we know is valid
  • Related