gpt4 book ai didi

python - Python 2 中的 TicTacToe 项目 : I am trying to avoid using global variables and return variables instead

转载 作者:太空宇宙 更新时间:2023-11-03 15:13:46 25 4
gpt4 key购买 nike

我正在开发一个项目,我不知道如何避免使用全局变量。我有一个执行点滴功能的函数列表,但我无法在它们之间传递变量!

这是我当前的代码:

====================

def player_names_input():
global player_A_name,player_B_name
player_A_name = raw_input("Please enter name for Player A : ")
player_B_name = raw_input("Please enter name for Player B : ")

def coin_flip():
global player_A_name,player_B_name,start_player,end_player,game_state
game_state = "running"
import random
print "\nFlipping a coin to see who starts first..."
random_int = random.randint(0, 1)
if random_int == 0:
coin = 'Heads'
start_player = player_A_name
end_player = player_B_name
else:
coin = 'Tails'
start_player = player_B_name
end_player = player_A_name
print '\nCoin flip --> ',coin
print '\nStarting player --> ',start_player
print '\nStarting player gets "X"'

player_names_input()
coin_flip()

这是我尝试使用 return 而不是 global 的失败尝试:

================================================== =========

def player_names_input():
player_A_name = raw_input("Please enter name for Player A : ")
player_B_name = raw_input("Please enter name for Player B : ")
return player_A_name,player_B_name

def coin_flip(player_A_name,player_B_name):
game_state = "running"
import random
print "\nFlipping a coin to see who starts first..."
random_int = random.randint(0, 1)
if random_int == 0:
coin = 'Heads'
start_player = player_A_name
end_player = player_B_name
else:
coin = 'Tails'
start_player = player_B_name
end_player = player_A_name
print '\nCoin flip --> ',coin
print '\nStarting player --> ',start_player
print '\nStarting player gets "X"'

player_names_input()
coin_flip(player_A_name,player_B_name)

1-请帮助运行我的第二个代码,我真的想像大家建议的那样避免全局变量。2-请批评我的代码,我刚刚开始,我正在努力学习编写好的代码(不仅仅是代码)。我的尝试有多糟糕?

最佳答案

由于您已定义 player_names_input() 返回一个 2 元组(两个值,player_A_nameplayer_B_name),您可以在您使用该函数的范围内像这样分配它们,

player_A_name, player_B_name = player_names_input()

现在,当调用它时:

coin_flip(player_A_name, player_B_name)

这两个变量将可供使用。

您可能需要考虑将实际的主程序包装在像

这样的主方法中
def main():
player_A_name, player_B_name = player_names_input()
coin_flip(player_A_name, player_B_name)

如果该文件是直接执行的,则调用该文件 - 这是通过检查神奇的 __name__ 变量是否等于字符串 '__main__' 来完成的,因此也将其添加到程序文件的末尾。

if __name__ == '__main__':
main()

关于python - Python 2 中的 TicTacToe 项目 : I am trying to avoid using global variables and return variables instead,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44036755/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com