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

Python调用deck卡组中卡牌的face面值返回空白无结果如何解决

问题修复方案

核心错误点

Card类的构造函数没有将传入的面值、花色参数绑定到实例属性上,直接给属性赋值了空字符串,导致所有卡牌的face、suit属性都是空值,输出就会显示空白。

修正后的代码

import random

def guessFaceOnly():
    randNum = random.randint(0, len(face)-1)
    print("\nFace Guess: " + face[randNum])
    print("Pulled Cards Face: " + deck[51].face)
def guessSuitOnly():
    print("ok")
def guessFaceAndSuit():
    print("J")
def menu():
    print("""To play the game choose one of the following:
1: To guess the face value only.
2: To guess the suit value only.
3: To guess the both the face and suit.
9: To end the game.
""")
    
class Card:
    def __init__(c, suit, face):
        c.suit = suit
        c.face = face
face = ["One", "Two", "Three", "Four", "Five","Six", "Seven", "Eight","Nine", "Ten","Jack", "Queen", "King"]
suit = ["Spade", "Club", "Diamond", "Heart"]
deck = []

for i in range(0,13):
    for j in range(0,4):
        newCard = Card(suit[j], face[i])
        deck.append(newCard)
        
while True:
    menu()
    random.shuffle(deck)
    choice = input()
    if choice == "1":
        guessFaceOnly()
    elif choice == "2":
        guessSuitOnly()
    elif choice == "3":
        guessFaceAndSuit()
    elif choice == "9":
        break

额外优化说明

  • 原代码中menu函数的多行字符串调整为三引号包裹,避免换行语法问题
  • 原代码中未使用的循环变量i已移除,简化为while True逻辑更清晰

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 07:06:03