我如何避免在这里使用全局变量?
How would I avoid using a global variable here?
我知道使用全局变量是个坏习惯,所以我试图在不使用全局变量的情况下重新制作我的 black jack 程序。目前此代码打印出玩家的手牌 (pH),但不打印玩家手牌的价值 (pHnum)。抱歉,我知道这是很多代码,问题发生的地方是“await ctx.send(pHnum)”,它没有发送我想要的值。我知道如何使用全局变量解决此问题,但还有其他方法吗???下面的代码。
# lists
pH = []
dH = []
# Hand Values
pHnum = 0
dHnum = 0
# The starting player hand
async def playerHand():
addCardP(pHnum, pH);
addCardP(pHnum, pH);
await ctx.send(pH)
await ctx.send(pHnum)
# Adding a card to the player hand
def addCardP(pHnum, pH):
# Creating a Card
Card = randint(2,14)
# Creating a Suit
suit = randint(1,4)
if (suit == 1):
suit = '♤'
elif (suit == 2):
suit = '♡'
elif (suit == 3):
suit = '♢'
elif (suit == 4):
suit = '♧'
# For if the card is less then 10; 2-10
if (Card <= 10):
pHnum = pHnum + Card
Card = str(Card)
cardS = Card + suit
pH.append(cardS)
# If the card is greater then 10; 11-14
else:
if (Card == 14):
Card = 'A'
cardS = Card + suit
pH.append(cardS)
else:
pHnum =+ 10
if (Card == 11):
Card = 'J'
cardS = Card + suit
pH.append(cardS)
elif (Card == 12):
Card = 'Q'
cardS = Card + suit
pH.append(cardS)
elif (Card == 13):
Card = 'K'
cardS = Card + suit
pH.append(cardS)
return pH, pHnum
我想找到一种不使用全局变量的方法。很抱歉,如果这是一个愚蠢的问题,我是整个编码的新手。非常感谢您的提前帮助。希望你今天过得愉快!!
您需要将结果赋值给变量。
async def playerHand():
pH = []
phNum = 0
pH, pHnum = addCardP(phnum, pH)
pH, pHnum = addCardP(phnum, pH)
await ctx.send(pH)
await ctx.send(pHnum)
我知道使用全局变量是个坏习惯,所以我试图在不使用全局变量的情况下重新制作我的 black jack 程序。目前此代码打印出玩家的手牌 (pH),但不打印玩家手牌的价值 (pHnum)。抱歉,我知道这是很多代码,问题发生的地方是“await ctx.send(pHnum)”,它没有发送我想要的值。我知道如何使用全局变量解决此问题,但还有其他方法吗???下面的代码。
# lists
pH = []
dH = []
# Hand Values
pHnum = 0
dHnum = 0
# The starting player hand
async def playerHand():
addCardP(pHnum, pH);
addCardP(pHnum, pH);
await ctx.send(pH)
await ctx.send(pHnum)
# Adding a card to the player hand
def addCardP(pHnum, pH):
# Creating a Card
Card = randint(2,14)
# Creating a Suit
suit = randint(1,4)
if (suit == 1):
suit = '♤'
elif (suit == 2):
suit = '♡'
elif (suit == 3):
suit = '♢'
elif (suit == 4):
suit = '♧'
# For if the card is less then 10; 2-10
if (Card <= 10):
pHnum = pHnum + Card
Card = str(Card)
cardS = Card + suit
pH.append(cardS)
# If the card is greater then 10; 11-14
else:
if (Card == 14):
Card = 'A'
cardS = Card + suit
pH.append(cardS)
else:
pHnum =+ 10
if (Card == 11):
Card = 'J'
cardS = Card + suit
pH.append(cardS)
elif (Card == 12):
Card = 'Q'
cardS = Card + suit
pH.append(cardS)
elif (Card == 13):
Card = 'K'
cardS = Card + suit
pH.append(cardS)
return pH, pHnum
我想找到一种不使用全局变量的方法。很抱歉,如果这是一个愚蠢的问题,我是整个编码的新手。非常感谢您的提前帮助。希望你今天过得愉快!!
您需要将结果赋值给变量。
async def playerHand():
pH = []
phNum = 0
pH, pHnum = addCardP(phnum, pH)
pH, pHnum = addCardP(phnum, pH)
await ctx.send(pH)
await ctx.send(pHnum)