Search code examples
pythonwhile-loop

Python - loop still going


I am trying to write a program similar to a blind auction, but I am having issues with the while loop. I don't understand why the loop is not ending. I used Thonny and even after the player enters 'no', it seems like the loop is breaking since it prints what is outside the loop and then goes to the bid function inside the while loop, with the player value set to 'yes'. I don't understand why this is happening. I have just started learning Python, so I would appreciate any help in explaining why this is occurring. Thank you!

def bid(player_name,player_bid):
    player_name = input("What's your name?\n")
    player_bid = input("What's your bid? PLN")
    bid_list[player_name] = player_bid

    while True:
        player = input("Are they any other users? Insert yes or no?")
        if player ==  "no":
           player = "no"
           break
    bid(player_name,player_bid)
  
  max_value = max(bid_list.values())
  print(f"{player_name} has the highest bid - {max_value} ")

  print("Thank you for playing")

player_name = ""
player_bid = 0
bid_list = {}

bid(player_name,player_bid)

I did try to change the code many times and used ChatGPT but still I don't understand why my code is not working. After I switched some part in while loop the code is working but I want to understand why my code is not working and why the loop is not ending.


Solution

  • Don't use recursion as a substitute for looping. Put your while loop around all the code that asks for player names and bids. Your recursion is outside the while loop, so it occurs every time and you never get out of the loop.

    There's also no need for player_name and player_bid to be function parameters, since the function assigns those variables itself from user input. You could instead pass in bid_list as a parameter.

    Your max() call gets the maximum bid, but not the player that made that bid. Get the maximum of bid_list.items() which returns both the keys and values.

    def bid(bid_list):
        while True:
            player_name = input("What's your name?\n")
            player_bid = input("What's your bid? PLN")
            bid_list[player_name] = player_bid
    
            player = input("Are they any other users? Insert yes or no?")
            if player ==  "no":
                break
    
        max_player, max_value = max(bid_list.items(), key=lambda x: x[1])
        print(f"{max_player} has the highest bid - {max_value} ")
    
        print("Thank you for playing")
    
    bid_list = {}
    bid(bid_list)