Skip to content Skip to sidebar Skip to footer

Can A Def Function Break A While Loop?

def CardsAssignment(): Cards+=1 print (Cards) return break while True: CardsAssignment() Yes, I know that I cannot return break. But how can I break

Solution 1:

No it cannot. Do something like:

defCardsAssignment():
  Cards+=1print (Cards)
  if want_to_break_while_loop:
    returnFalseelse:
    returnTruewhileTrue:
  ifnot CardsAssignment():
    break

Solution 2:

A very Pythonic way to do it would be to use exceptions with something like the following:

classStopAssignments(Exception): pass# Custom Exception subclass.defCardsAssignment():
    global Cards  # Declare since it's not a local variable and is assigned.

    Cards += 1print(Cards)
    if time_to_quit:
        raise StopAssignments

Cards = 0
time_to_quit = FalsewhileTrue:
    try:
        CardsAssignment()
    except StopAssignments:
        break

Another, less common approach would be to use a generator function which will return True indicating that it's time to quit calling next() on it:

defCardsAssignment():
    global Cards  # Declare since it's not a local variable and is assigned.whileTrue:
        Cards += 1print(Cards)
        yieldnot time_to_quit

Cards = 0
time_to_quit = False
cr = CardsAssignment()  # Get generator iterator object.next(cr)  # Prime it.whilenext(cr):
    if Cards == 4:
        time_to_quit = True# Allow one more iteration.

Solution 3:

You could have CardsAssignment return True (to continue) or False (to stop) and then have

ifnotCardsAssignment():
    break

or indeed just loop

whileCardsAssignment():

Solution 4:

If you use a for loop instead of a while, you can cause it to break early by raiseing StopIteration - this is the usual signal for a for loop to finish, and as an exception, it can be nested inside functions as deep as you need and will propagate outward until it is caught. This means you need something to iterate over - and so, you probably want to change your function into a generator:

def cards_assignment():
     cards += 1yield cards

for card incards_assignment():
    print(card)

, in which case instead of doing raise StopIteration, you would just return from the generator and the loop will finish. However, note that this (as well as options having the function return a flag that you test in the loop condition) is subtly different to using break - if you use an else clause on your loop, returning from a generator will trigger it, whereas break in the loop body won't.

Solution 5:

defCardsAssignment():
      Cards+=1print (Cards)
      if (break_it):
          returnFalseelse:
          returnTruewhile CardsAssignment():
    pass

Post a Comment for "Can A Def Function Break A While Loop?"