在python游戏中使用全局变量

时间:2015-05-25 15:24:33

标签: python

我有一些代码

<menu>

这是高或低游戏的简单版本 但它不像

那样有效
import random
Numbers = ("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King")
Types = ("Hearts", "Clubs", "Spades", "Diamonds")

Number = random.choice(Numbers)
Type = random.choice(Types)
Card = Number + " of " + Type

print(Card)
ans = input("h or l?\n")

def second_card():
    Number2 = random.choice(Numbers)
    Type2 = random.choice(Types)
    Card2 = Number2 + " of " + Type2
    if Card2 == Card:
        second_card()

if ans == "h":
    if Number < Number2:
        print(Card2)
    elif Number > Number2:
        print(Card2)
        print("YOUR OUT")
    else:
        print(Card2)
        print("equal")
elif ans == "l":
    if Number > Number2:
        print(Card2)
    elif Number < Number2:
        print(Card2)
        print("YOUR OUT")
    else:
        print(Card2)
        print("equal")

行它不识别变量Number2我做了全局Number2,因为我尝试了几个地方而且它们不起作用

1 个答案:

答案 0 :(得分:0)

您可以在return函数中添加second_card()语句,以便返回Number2Type2Card2。然后再调用second_card()(您目前不会这样做,因此该功能都无法设置这些变量)。

def second_card():
    Number2 = random.choice(Numbers)
    Type2 = random.choice(Types)
    Card2 = Number2 + " of " + Type2
    if Card2 == Card:
        return second_card()
    return (Number2, Type2, Card2)

Number2, Type2, Card2 = second_card()

或者使用全局变量:

Number2, Type2, Card2 = None, None, None

def second_card():
    global Number2, Type2, Card2
    Number2 = random.choice(Numbers)
    Type2 = random.choice(Types)
    Card2 = Number2 + " of " + Type2
    if Card2 == Card:
        second_card()

second_card()