You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python字典值与数字比较报TypeError,求解决方案

问题:字典值为元组导致类型错误

我是Python新手,正在通过Udemy的100天视频教程学习。奇怪的是,教程中老师的相同代码可正常运行,但我的却报错。查看过同类错误的帖子后仍无法解决,故发帖求助。

通过Thonny调试发现,bid_amnt = bidding_record[bidder]获取的值末尾带有逗号,我尝试用int(bidding_record[bidder])转换为整数也无效。错误信息:

TypeError: '>' not supported between instances of 'tuple' and 'int'

我的代码片段:

#Code snippet
def find_highest_bidder(bidding_record):
    #bidding_record = {Angela:123, James:321} examlpe of dictionary prepared
    highest_bid = 0
    winner = ""
    for bidder in bidding_record:   
        bid_amnt = bidding_record[bidder]
        if bid_amnt > highest_bid:
            highest_bid = bid_amnt
            winner = bidder
  print(f"Winner of this bid is {winner} with ${highest_bid}")

#Declaring variable for loop and empty dictionary
bid_on = True

while bid_on == True:
    #Taking user Inputs
    name = input("Please enter your name: \n")
    bid_value = int(input("please enter your bid amount: $"))
    other_users = input("are there other users who want to bid type yes/no:  \n").lower() 
    bid_dict[name] = bid_value,
  
    #Calling function by passing dictionary in argument  
    find_highest_bidder(bid_dict)
  
    #Calling clear function from replit if there are no more users  
    if other_users == "no":
        bid_on = False
    else:
    clear()

问题原因

核心错误是这一行:

bid_dict[name] = bid_value,

末尾的逗号把原本的整数bid_value变成了单元素元组(比如(123,))。当你在函数里拿这个值和整数highest_bid比较时,元组和整数无法直接用>比较,就触发了类型错误。

另外还有几个小问题:

  • bid_dict没有提前初始化,应该在循环前添加bid_dict = {}
  • print语句缩进错误,需要和函数内的代码保持同一缩进层级
  • clear()前面缩进不足,需要对齐else块的代码

修复后的代码

def find_highest_bidder(bidding_record):
    highest_bid = 0
    winner = ""
    for bidder in bidding_record:   
        bid_amnt = bidding_record[bidder]
        if bid_amnt > highest_bid:
            highest_bid = bid_amnt
            winner = bidder
    print(f"Winner of this bid is {winner} with ${highest_bid}")

# 初始化空字典和循环变量
bid_on = True
bid_dict = {}

while bid_on:
    name = input("Please enter your name: \n")
    bid_value = int(input("please enter your bid amount: $"))
    other_users = input("are there other users who want to bid type yes/no:  \n").lower() 
    # 去掉末尾的逗号,直接存整数
    bid_dict[name] = bid_value
  
    find_highest_bidder(bid_dict)
  
    if other_users == "no":
        bid_on = False
    else:
        clear()

内容的提问来源于stack exchange,提问作者Anurag Jain

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 03:10:35