gpt4 book ai didi

python - 为什么我的 python 代码运行了两次?

转载 作者:太空宇宙 更新时间:2023-11-04 10:04:40 24 4
gpt4 key购买 nike

每当我为“你想求另一个形状的面积吗?”输入“否”时它再次问我这个问题。这是我的代码:-

def calculate_area():
print "Welcome to the area calculator"
user= raw_input("Enter the shape you would like to calculate the area of:").lower()

def restart():
answer= raw_input( "Would you like to find the area of another shape?('yes' or 'no')")
if answer=="yes":
calculate_area()
def rerun():
restart()


if user== "rectangle":
def calculate_rectangle():
rect1= int(raw_input("Enter the length of the first side:"))
rect2= int(raw_input("Enter the length of the second side:"))
print "The area is:",float(rect1*rect2)
calculate_rectangle()
rerun()

elif user== "square":
def calculate_square():
square=int(raw_input("Enter the length of the side:"))
print "The area is:",float(square**2)
calculate_square()
rerun()


elif user== "triangle":
def calculate_triangle():
triangle=int(raw_input("Enter the length of the base:"))
triangle2=int(raw_input("Enter the height of the triangle:"))
print "The area is:", float((0.5*triangle)*triangle2)
calculate_triangle()
rerun()


elif user== "trapezoid":
def calculate_trap():
trapezoid=int(raw_input("Enter the length of base 1:"))
trapezoid2=int(raw_input("Enter the length of base 2:"))
trapezoid3=int(raw_input("Enter the height:"))
print "The area is:", (float(trapezoid+trapezoid2)/2*float(trapezoid3))
calculate_trap()
rerun()

elif user== "circle":
def calculate_circle():
circle=int(raw_input("Enter the radius:"))
print "The area is:", (float((circle**2)*3.14))
calculate_circle()
rerun()

elif user== "rhombus":
def calculate_rhombus():
rhombus1=int(raw_input("Enter the length of diagonal 1:"))
rhombus2=int(raw_input("Enter the length of diagonal 2:"))
print "The area is:", (float((rhombus1*rhombus2)/2))
calculate_rhombus()
rerun()

else:
print "Shape not recognized"
rerun()

此代码位于“def restart”下,每当我键入“no”时运行两次。为什么会这样?

最佳答案

您为每个问题调用两次 rerun():

if user== "rectangle":
# ...
rerun()

elif user== "square":
# ...
rerun()

# all other elif branches each have rerun()

else:
print "Shape not recognized"
rerun()

你在这里依赖递归,但是递归函数return;当您输入 "No" 时,restart() 返回到 rerun(),它将控制权返回到它被调用的位置,所以在您的 if ... elif ... 分支之一。在这些分支之后您再次调用rerun()

您一开始就不应该使用递归。改为使用无限循环:

print "Welcome to the area calculator"

while True:
user = raw_input("Enter the shape you would like to calculate the area of:").lower()
# execute their choice
if user== "rectangle":
# ...
# etc.

else:
print "Shape not recognized"

answer = raw_input( "Would you like to find the area of another shape?('yes' or 'no')")
if answer != "yes":
break

末尾的 break 结束了 while True 循环。如果输入 yes,则 while 循环从顶部继续,重新运行整个 block 。

关于python - 为什么我的 python 代码运行了两次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41652800/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com