gpt4 book ai didi

python-3.x - 如何停止我的功能?

转载 作者:行者123 更新时间:2023-12-04 06:24:24 24 4
gpt4 key购买 nike

当满足条件时,如何让我的功能停止?
例如在我下面的代码中,当用户输入:“q”(退出)时,我希望我的函数简单地停止。
我试过使用“break”语句,但它不起作用。

def main():
shape = input("Enter shape to draw (q to quit): ").lower()
while shape != 'triangle' and shape != 'square' and shape != 'q':
print("Unknown shape. Please try again")
shape = input("Enter shape to draw (q to quit): ").lower()
if shape == "q":
print("Goodbye")
break #Python not happy with the indentation.

def get_valid_size():
size = int(input("Enter size: "))
while size < 1:
print("Value must be at least 1")
size = int(input("Enter size: "))
main()
get_valid_size()

当我运行它时,它执行:
Enter shape to draw (q to quit): q
Goodbye
Enter size:

我不希望它要求尺寸。

最佳答案

return 将退出一个函数,将控制权返回给最初调用该函数的任何人。如果你想了解更多,谷歌的短语是“退货声明”。
break将退出循环,as described here .

尝试类似:

def main():
shape = input("Enter shape to draw (q to quit): ").lower()
while shape != 'triangle' and shape != 'square' and shape != 'q':
print("Unknown shape. Please try again")
shape = input("Enter shape to draw (q to quit): ").lower()
if shape == "q":
print("Goodbye")
return
get_valid_size()

def get_valid_size():
size = int(input("Enter size: "))
while size < 1:
print("Value must be at least 1")
size = int(input("Enter size: "))
main()

关于python-3.x - 如何停止我的功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30147995/

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