python-3.x - 调用函数后全局变量不变
问题描述
所以我正在做一个附带项目,诚然我对 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。
解决方案
您的变量在类内。尝试将它们移出课堂:
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
推荐阅读
- php - 通过 API HTTP PUT 上传 Laravel 文件在本地工作,但在 AWS 上不工作
- python - 根据数据集中的 x 和 y 值将数据帧拆分为多个并获取值计数 Pandas
- django - Django:忽略给定更新的事务
- rabbitmq - RabbitMQ & RascalJS - 应用程序随着时间的推移与服务器创建多个连接
- python - 如何根据各种条件方法在 Pandas 中插入缺失值
- python - Python Pandas 按其他列中的给定值重复一行
- npm - npm 忽略它自己的范围私有注册表的配置,包括 npm 6.x 和 npm 7.x
- ios - 游戏中心完成横幅未在 iOS 模拟器中显示
- assembly - 内存段定义
- r - 如何确定时间序列中某个值何时减少或增加某个阈值?