How do i get my function to stop, when a condition has been met? for example in my following code, when the user inputs: "q
" for (quit), i want my function to simply stop. i've tried using the "break
" statement, but it's not working.
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 size.
return
will exit a function, returning control to whatever had originally called the function. If you want to learn more, the phrase to google is "Return statements."
break
will exit a 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()
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments