How do I stop my function?
How do I make my function stop when the condition is met? for example, in my following code, when the user types: " q
" for (quit), I want my function to just stop. I tried to use the operator break
, but it doesn't work.
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()
when i run it it executes:
Enter shape to draw (q to quit): q
Goodbye
Enter size:
I don't want it to ask for the size.
source to share
return
will exit the function, returning control to what was originally called the function. If you want to know more, google's phrase is "Return Operators".
break
will exit the loop as described here .
Try something like:
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()
source to share
break
used only to exit the cycle for
, cycles while
and try
.
return
will exit the function with the specified value. Simple use return
will return a value None
, and using return True
or return False
will return true and false respectively. You can also return a variable, for example to return a variable x
that you would use return x
.
source to share