gpt4 book ai didi

python - 将字符串视为整数

转载 作者:太空宇宙 更新时间:2023-11-04 08:55:21 24 4
gpt4 key购买 nike

我正在尝试制作一款非常简单的二十一点游戏。当您发到两张牌时,如果它们都是整数或字符串,则一切正常,但如果发到的两张牌是一个字符串和一个整数,我会收到错误消息。

我怎样才能做到,如果你得到一张 7 和一张 Q,那么 Q 将被视为 10,总共给你 17?

#imports
import random

Jack = 10
Queen = 10
King = 10
Ace = 1 or 11

Cards = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 'Jack', 'Queen', 'King', 'Ace']
#Faces = Jack, Queen, King, Ace
print('Welcome to Blackjack!\n\nHere are your cards: \n ')
Card1 = random.choice(Cards)
Card2 = random.choice(Cards)
Total = Card1 + Card2
print(Card1,'and a', Card2, '. Your total is', Total)






#print(int(Jack + Ace))

最佳答案

使用字典将卡片映射到值:

Cards = {"1": 1, "2": 2, "3": 3, "4": 4, "5": 5, "6": 6, "7": 7, "8": 8, "9": 9,
"10": 10, 'Jack': 10, 'Queen': 10, 'King': 10, 'Ace': 10}

#Faces = Jack, Queen, King, Ace
print('Welcome to Blackjack!\n\nHere are your cards: \n ')
keys = list(Cards)
Card1 = random.choice(keys)
Card2 = random.choice(keys)
Total = Cards[Card1] + Cards[Card2]
print(Card1, 'and a', Card2, '. Your total is', Total)

或者使用.items:

Cards = {"1": 1, "2": 2, "3": 3, "4": 4, "5": 5, "6": 6, "7": 7, "8": 8, "9": 9,
"10": 10, 'Jack': 10, 'Queen': 10, 'King': 10, 'Ace': 10}

#Faces = Jack, Queen, King, Ace
print('Welcome to Blackjack!\n\nHere are your cards: \n ')
c = list(Cards.items())
Card1 = random.choice(c)
Card2 = random.choice(c)
Total = Card1[1] + Card2[1]
print(Card1[0], 'and a', Card2[0], '. Your total is', Total)

关于python - 将字符串视为整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30698740/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com