我是一个使用python编码语言的初学者,我在python中编写一个可以在终端中运行的简单程序时遇到了麻烦。这是迄今为止的计划。
import random
X = "*"
O = "*"
Player = "*"
Computer = "*"
def inputPlayerLetter():
letter = raw_input('Do you want to be X or O? \n')
if letter == "X":
print "You are now X's, you will go first"
Player = "X"
Computer = "O"
elif letter == "O":
print "You are now O's you will go second"
Player = "O"
Computer = "X"
inputPlayerLetter()
print Player
print Computer
这是我在运行代码时在终端中获得的内容。
Do you want to be X or O?
X
You are now X's, you will go first
*
*
或
Do you want to be X or O?
O
You are now O's you will go second
*
*
基本上,在我的功能中,如果我选择X,我希望Player为X,而计算机为O(或者当我选择O时,我希望Player为O,而计算机为X)。但是,当我打印变量时,我得到*和*。我如何解决这个问题,以便我的if ifif语句的尝试结果具有我想要的效果。
答案 0 :(得分:0)
您要分配的播放器和计算机的值是该功能的本地值。您应该从函数中返回值,以便它们可以在主范围中访问:
def inputPlayerLetter():
Player , Computer = "*", "*"
letter = raw_input('Do you want to be X or O? \n')
if letter == "X":
print "You are now X's, you will go first"
Player, Computer = "X", "0"
elif letter == "O":
print "You are now O's you will go second"
Player, Computer = "O", "X"
return Player, Computer
Player, Computer = inputPlayerLetter()
有关详细信息,请参阅What are the rules for local and global variables in Python?:
在Python中,仅在函数内引用的变量是 隐含全球性。如果在任何地方为变量分配了新值 在函数体内,它被认为是一个本地的。如果是变量 在函数内部分配了一个新值,变量是 隐式本地,您需要明确地将其声明为“全局”。
虽然起初有点令人惊讶,但片刻的考虑解释了 这个。一方面,要求全局分配变量提供了一个 禁止意外的副作用。另一方面,如果全球化了 所有全局引用都需要,你将全局使用全局 时间。您必须将每个对内置的引用声明为全局 功能或导入模块的组件。这种混乱会 打败全球宣言的有用性 副作用。
你也可以将变量设为全局,但这通常被认为是不好的做法,因为它打开了意外副作用的大门。
答案 1 :(得分:0)
您的播放器,计算机变量位于inputplayerletter()
函数之外,因此您将值存储在局部变量中。
要解决此问题,请使用以下函数来使用全局变量:
global Player, Computer
最终代码:
import random
X = "*"
O = "*"
Player = "*"
Computer = "*"
def inputPlayerLetter():
global Player, Computer
letter = raw_input('Do you want to be X or O? \n')
if letter == "X":
print "You are now X's, you will go first"
Player = "X"
Computer = "O"
elif letter == "O":
print "You are now O's you will go second"
Player = "O"
Computer = "X"
inputPlayerLetter()
print Player
print Computer
希望有所帮助