如何停止我的功能?
How to stop my function?
如何让我的功能在满足条件时停止?
例如在我的以下代码中,当用户输入:“q
” for (quit) 时,我希望我的函数简单地停止。
我试过使用“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
将退出一个函数,将控制权返回给最初调用该函数的任何对象。如果您想了解更多,google 的短语是 "Return statements."
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()
break
只用于退出for
循环、while
循环、try
循环。
return
将退出具有指定值的函数。简单地使用 return
将 return 一个 None
值,而使用 return True
或 return False
将分别 return true 和 false。您还可以 return 一个变量,例如,要 return 一个变量 x
您将使用 return x
.
如何让我的功能在满足条件时停止?
例如在我的以下代码中,当用户输入:“q
” for (quit) 时,我希望我的函数简单地停止。
我试过使用“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
将退出一个函数,将控制权返回给最初调用该函数的任何对象。如果您想了解更多,google 的短语是 "Return statements."
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()
break
只用于退出for
循环、while
循环、try
循环。
return
将退出具有指定值的函数。简单地使用 return
将 return 一个 None
值,而使用 return True
或 return False
将分别 return true 和 false。您还可以 return 一个变量,例如,要 return 一个变量 x
您将使用 return x
.