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
相关产品推荐
相关产品推荐

