如果输入的形状无效,我试图让这段代码重新开始,我将如何解决这个问题?
I'm trying to get this code to start over if the shape entered is invalid, how would I go about fixing this?
我正在尝试编写一个程序来计算多个形状的总面积。首先,我找到形状的数量,然后是形状的类型,然后将它们全部加起来。如果输入不正确,我试图让用户重新输入形状类型。我尝试在最后一个 else 中使用 return,但我不断收到错误消息,指出它不在函数内。如果输入无效,我似乎无法弄清楚如何重复 shape_type。
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")
将输入包装在 while True
循环中,只有在输入有效时才跳出循环。
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
我正在尝试编写一个程序来计算多个形状的总面积。首先,我找到形状的数量,然后是形状的类型,然后将它们全部加起来。如果输入不正确,我试图让用户重新输入形状类型。我尝试在最后一个 else 中使用 return,但我不断收到错误消息,指出它不在函数内。如果输入无效,我似乎无法弄清楚如何重复 shape_type。
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")
将输入包装在 while True
循环中,只有在输入有效时才跳出循环。
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