TypeError报错:字符串与int实例不支持>=比较,输入转int仍未解决
TypeError问题修复方案
报错原因
你传入Cards类初始化的rank是"Ace"、"Two"这类字符串值,在getValue方法中直接用字符串和整数10做>=比较,触发了类型不匹配错误。
需修改的核心点
- 新增牌面字符串到对应数值的映射,将rank字符串转成整数后再做比较运算
- 修复
__str__方法的返回值类型,原写法返回元组会触发打印异常 - 冗余的
getRank、getSuit方法可以删除,你初始化时已经传入了固定的牌面和花色,不需要再随机覆盖
修复后完整代码
import random class Cards: def __init__(self, rank, suit): self.rank = rank self.suit = suit # 建立牌面到数值的映射 self.rank_map = { "Ace": 1, "Two": 2, "Three": 3, "Four": 4, "Five": 5, "Six": 6, "Seven": 7, "Eight": 8, "Nine": 9, "Ten": 10, "Jack": 11, "Queen": 12, "King": 13 } def getValue(self): rank_num = self.rank_map[self.rank] if rank_num >= 10: return 10 else: return rank_num def __str__(self): return f"{self.rank} of {self.suit}" def main(): n = int(input("How many cards would you like to see? ")) for i in range(1, n+1): ranks = ["Ace", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight","Nine","Ten","Jack", "Queen", "King"] suits = ["Clubs", "Hearts", "Spades", "Diamonds"] cardhand = Cards(random.choice(ranks), random.choice(suits)) print ("The", cardhand, "has a Blackjack value of", cardhand.getValue()) main()
运行示例
输入2后输出参考:
The King of Diamonds has a Blackjack value of 10 The Five of Clubs has a Blackjack value of 5
内容的提问来源于stack exchange,提问作者Cayla Tousignant
相关产品推荐
相关产品推荐

