I am trying to print out the highest bidder after trying to code this from scratch. I have stared at this for an hour and cannot figure out why it all works but it always declares the most recent bidder as the winner, not the highest. A fresh pair of eyes would be appreciated!
#print(logo)
#Then we set variables to store the inputs
print("Welcome to the secret auction program.\n")
#We then create a dictionary to store the functions output
bidders = []
#Function to add bids to dictionary
def create_bidder(name, bid):
bidders.append({
"name": name,
"bid" : bid
})
start_name = input("What is your name?\n")
start_bid = input("What's your bid?\n")
create_bidder(start_name,start_bid)
keep_going = input("Are there any other bidders? Type 'yes' or 'no'\n")
while keep_going == "yes":
clear()
name = input("What is your name?\n")
bid = input("What's your bid?\n")
keep_going = input("Are there any other bidders? Type 'yes' or 'no'\n")
create_bidder(name, bid)
for i in range(0, len(bidders)):
maxBid = -1
maxBidName = "";
bid = int(bidders[i]["bid"])
name = bidders[i]["name"]
if bid > maxBid:
maxBid = bid
maxBidName = name
if keep_going == 'no':
for i in range(0, len(bidders)):
maxBid = -1
maxBidName = "";
bid = int(bidders[i]["bid"])
name = bidders[i]["name"]
if bid > maxBid:
maxBid = bid
maxBidName = name
print(f"Congratulations {maxBidName}! Your bid of ${maxBid} wins!")
if keep_going == 'print':
print(bidders)
CodePudding user response:
You can move maxBid out of the for loop, in your keep_gooing == 'no' case. It would look like this:
maxBid = 0
maxBidName = ""
for bidder in bidders:
bid = int(bidder["bid"])
name = bidder["name"]
if bid > maxBid:
maxBid = bid
maxBidName = name
print(f"Congratulations {maxBidName}! Your bid of ${maxBid} wins!")
If the maxBid is inside the for loop, it will be setted to -1 every time the loop runs!
