打印错误的python

时间:2018-09-29 18:31:25

标签: python

我最近开始编码,所以我不了解很多,这就是为什么我来这里寻求帮助。我目前正在使用python编写游戏(不是我想做的复杂游戏),它基本上只是我的一个朋友组成的纸牌游戏。到目前为止,我唯一的问题是我的变量之一返回错误,并且同时正确吗?

这是很奇怪的代码:

Card = "Nothing"

def Draw_Card():
    Rank = random.randint(1, 13)
    print(Rank)
    Card = str(Rank)
    print(Card)

    if Rank == 11:
        Card = "J"
    elif Rank == 12:
        Card = "Q"
    elif Rank == 13: 
        Card = "K"

    Suit = random.randint(1, 4)
    if Suit == 1:
        Card = Card + "D"
    elif Suit == 2:
        Card = Card + "C"
    elif Suit == 3:
        Card = Card + "H"
    elif Suit == 4:
        Card = Card + "S"

Top()
Help()
Top()
print("And the game begins!")
time.sleep(2)
Top()
Card = "Nothing"
Draw_Card()
print(Card)

忽略Top()函数和其他函数,重要的是Draw_Card()和通过此代码运行的print(Card)将返回

7, 7 没事

假设7是生成的随机值。在Draw_Card()函数中可以正确打印卡片,但在函数外部时则不能正确打印。我不明白为什么会这样,并且会有所帮助

另一件事是Card =“ Nothing”在函数内部不起作用,它在Card未定义的情况下返回,但是那不是重点

3 个答案:

答案 0 :(得分:0)

Draw_Card内,名称Card表示局部变量。退货怎么样?

在函数末尾添加

return Card

在函数之外,执行以下操作:

Card = Draw_Card()

另一种选择是声明名称来自全局范围:

def Draw_Card():
    global Card
    Rank = random.randint(1, 13)
    print(Rank)
    ...

但我通常会尽可能避免使用globalnonlocal

答案 1 :(得分:0)

假设您在调用Draw_Card函数(即7D)时要打印西装和卡片,则可以将print(card)移动到Draw_Card函数的底部。

此外,为了在函数外部更改Card变量,您需要将global Card放在函数顶部。

import random

Card = "Nothing"
def Draw_Card():
  global Card
  Rank = random.randint(1, 13)

  Card = str(Rank)

  if Rank == 11:
      Card = "J"
  elif Rank == 12:
      Card = "Q"
  elif Rank == 13: 
      Card = "K"

  Suit = random.randint(1, 4)
  if Suit == 1:
      Card = Card + "D"
  elif Suit == 2:
      Card = Card + "C"
  elif Suit == 3:
      Card = Card + "H"
  elif Suit == 4:
      Card = Card + "S"
  print(Card)


print("And the game begins!")
Card = "Nothing"
Draw_Card()
print(Card)

答案 2 :(得分:0)

您的函数只需要resetSearch,您应该专注于使用this.userSearch,然后再使用return返回的值

return
print