【发布时间】:2020-01-15 03:58:45
【问题描述】:
我对 python 或一般编码有点陌生,我在我的 while 循环中遇到了问题。我想指出,while 循环仅在变量“loop”= True 时才有效
loop = True #Makes the asking sequence work
def loop_again(): #Makes the program ask if you want to continue
loop_again = str(input("Do you want to do this again? Yes or No: "))
if loop_again == "Yes":
loop = True
elif loop_again == "No":
loop = False
else:
print("Please answer yes or no: ")
loop_again
当我在程序询问我是否要再次执行此操作时写“否”时,它仍然循环序列,即使当我键入“否”时变量“循环”应该是假的,这应该是停止循环。
完整代码(代码底部的while循环):
#Solving for the area in a shape automatically
import math
loop = True #Makes the asking sequence work
def loop_again(): #Makes the program ask if you want to continue
loop_again = str(input("Do you want to do this again? Yes or No: "))
if loop_again == "Yes":
loop = True
elif loop_again == "No":
loop = False
else:
print("Please answer yes or no: ")
loop_again
def sqr_area(): #Asking sequence for the area of the square
if choose == "Square":
a = float(input("Input the length of the side here: "))
print(a ** 2)
loop_again()
def rec_area(): #Asking sequence for the area of the rectangle
if choose == "Rectangle":
a = float(input("Input the length of the long sides here: "))
b = float(input("Input the length of the short sides here: "))
print(a * b)
loop_again()
def tri_area(): #Asking sequence for the area of the triangle
a = float(input("Input the length of the side: "))
b = float(input("Input the length of the height: "))
print((a * b) / 2)
loop_again()
def cir_area(): #Asking sequence for the area of the circle
r = float(input("Length of the radius: "))
print((r ** 2) * math.pi)
loop_again()
while loop == True: #While loop, asking sequence
choose = str(input("Input what shape that you want to figure out the area of here: "))
if choose == "Square":
sqr_area()
elif choose == "Rectangle":
rec_area()
elif choose == "Triangle":
tri_area()
elif choose == "Circle":
cir_area()
else:
print("Invalid shape, Input one of these shapes: Square, Rectangle, Triangle, Circle")
choose
提前致谢!
【问题讨论】:
-
else: ... choose- 这是一个错字吗?choose是一个字符串。 -
再次循环的问题应该在
while循环本身中,而不是嵌入在每个*_area函数中。loop_again应该也使用while循环,而不是使用无限递归。 -
忘了说,欢迎来到 Stack Overflow!查看tour 和How to Ask。对于寻求调试帮助的问题,将您的代码缩减为 minimal reproducible example 非常有帮助。