Search code examples
pythonloopswhile-loop

Escape from loop


When I enter data and then choose "no", my loop keeps running without stopping. How can I get it to exit the loop?

I changed boolean values from False to True and and vice versa. I expected it to exit from the loop but that did not happen.

print ("Welcome to the secret auction program")
auction_participants = {}
auction_stop = False
def blind_auction (name1,bid1,contin):
  auction_participants[name1] = bid1
  higher_participant = ""
  higher_price = 0
  for price in auction_participants:
      if auction_participants[price] > higher_price:
          higher_price = auction_participants[price]
          higher_participant = price
      if contin == "no":
          auction_stop = True
          print (f"The winner is {higher_participant} with a bid of ${higher_price}")
while not auction_stop:
  blind_auction (input("What is your name?: "),int(input("What's your bid?: $")),input("Are there any other bidders? Type 'yes' or 'no'."))

Solution

  • Your function tries to update the global auction_stop variable, but you're instead just assigning to a local variable of the same name.

    You could fix this with a global statement:

    global auction_stop # put this anywhere inside the function
    

    However, your code likely still won't work as you intend, as the higher_price and higher_participant variables are also local to the function, and so not saved between function calls. You could make those global variables too, but it gets pretty messy.

    Honestly, I'd get rid of the function, it's causing you more burdens than giving benefits. Just put the function body inside the body of the while loop (with minor tweaks, like moving the higher_participant and higher_price initialization stuff somewhere outside). Doing all the input calls in a single very long function call was pretty confusing anyway.

    print ("Welcome to the secret auction program")
    auction_participants = {}
    auction_stop = False
    higher_participant = ""
    higher_price = 0
    
    while not auction_stop:
        name = input("What is your name?: ")
        bid = int(input("What's your bid?: $"))
        auction_participants[name] = bid
        contin = input("Are there any other bidders? Type 'yes' or 'no'."))
        if contin == "no":
            auction_stop = True
    
    for name in auction_participants:   # there was no reason to include this in the while loop
        if auction_participants[name] > higher_price:
            higher_price = auction_participants[name]
            higher_participant = name
          
    print (f"The winner is {higher_participant} with a bid of ${higher_price}")