首页 > 解决方案 > 调用函数后全局变量不变

问题描述

所以我正在做一个附带项目,诚然我对 Python 或一般编码不是很有经验,但我正在尝试制作一个卡片应用程序。调用函数后,我无法更改全局变量

如果我提供相同的套装,它会在函数内打印,但不会在函数外打印。我在网上读到,将全球放在首位可以解决这个问题,但事实并非如此。任何帮助表示赞赏。

class Hand:
    people = 0
    hand = []
    suited = False
    def deal():
        global people
        global hand
        global suited
        num_1 = input("What is your first card?: ")
        suit_1 = input("What is your suit?: ")
        num_2 = input("What is your second card?: ")
        suit_2 = input("What is your suit?: ")
        people = input("How many people at the table?: ")
        card_1 = [num_1,suit_1]
        card_2 = [num_2,suit_2]
        if card_1[0] > card_2[0]:
            hand = [card_1, card_2]
        else:
            hand = [card_2, card_1]
        if card_1[1] == card_2[1]:
            suited = True
        else:
            suited = False
        print(suited)
    deal()
    print(suited)

在我输入相同的西装后,我希望它能够将适合的值更改为 True。

标签: python-3.x

解决方案


您的变量在类内。尝试将它们移出课堂:

people = 0
hand = []
suited = False

class Hand:
    def deal():
        global people
        global hand
        global suited
        num_1 = input("What is your first card?: ")
        suit_1 = input("What is your suit?: ")
        num_2 = input("What is your second card?: ")
        suit_2 = input("What is your suit?: ")
        people = input("How many people at the table?: ")
        card_1 = [num_1,suit_1]
        card_2 = [num_2,suit_2]
        if card_1[0] > card_2[0]:
            hand = [card_1, card_2]
        else:
            hand = [card_2, card_1]
        if card_1[1] == card_2[1]:
            suited = True
        else:
            suited = False
        print(f"suited: {suited}")
    deal()
    print(f"suited: {suited}")
print(f"suited: {suited}")
(py36) [~]$ python3 card_deal.py
What is your first card?: K
What is your suit?: H
What is your second card?: A
What is your suit?: H
How many people at the table?: 7
suited: True
suited: True
suited: True

推荐阅读