【问题标题】:I am trying to print out the highest bidder Part 2 *Beginner*我正在尝试打印出最高出价者第 2 部分 *初学者*
【发布时间】:2022-01-13 05:22:28
【问题描述】:

在尝试从头开始编写代码后,我试图打印出最高出价者。我已经盯着这个看了一个小时,不明白为什么这一切都有效,但它总是宣布最近的竞标者为中标者,而不是最高的。一双新鲜的眼睛将不胜感激!

#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)

【问题讨论】:

  • 你正在重置maxBid = -1循环中的每一次迭代!在循环之前设置它一次
  • 您在每次循环迭代时将 max_bid 设置为 -1,因此每次都将接受任何正值作为新的最高出价

标签: python arrays loops dictionary


【解决方案1】:

您可以将maxBid 移出for 循环,在您的keep_gooing == 'no' 案例中。它看起来像这样:

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!")

如果maxBid在for循环内,则每次循环运行时都会设置为-1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-11
    • 2023-02-21
    • 2011-12-14
    • 2022-12-05
    • 1970-01-01
    • 1970-01-01
    • 2022-10-15
    相关资源
    最近更新 更多