[英]How to pull a variable from one function to another
def letterChoice():
playerLetter = input('Please choose X or O.').upper()
if playerLetter in ['X','O']:
print('The game will now begin.')
while playerLetter not in ['X','O']:
playerLetter = input('Choose X or O.').upper()
if playerLetter == 'X':
computerLetter = 'O'
else:
computerLetter = 'X'
turnChooser()
def turnChooser():
choice = input("Would you like to go first, second or decide by coin toss?(enter 1, 2 or c) ")
while choice not in ["1","2","c"]:
choice = input("Please enter 1, 2 or c. ")
if choice == 1:
print("G")
cur_turn = letterChoice.playerLetter()
elif choice == 2:
print("H")
else:
print("P")
moveTaker()
我不知道應該如何將playerLetter繼承到turnChooser()中,我曾嘗試將playerLetter放入每個函數的括號中,但是它們不會傳遞並創建參數錯誤和print("G")
等等只是在這里查看代碼是否有效,但是每當我輸入1或2時,都會輸出“ P”。
您應該嘗試使用類: Python文檔
這應該是代碼:
class Game:
def __init__(self):
self.cur_turn = ''
self.choise = ''
self.playerLetter = ''
self.computerLetter = ''
def letterChoice(self):
while True:
self.playerLetter = input('Please choose X or O.').upper()
if self.playerLetter in ['X','O']:
print('The game will now begin.')
if playerLetter == 'X':
self.computerLetter = 'O'
else:
self.computerLetter = 'X'
break
else:
print ('Please enter only X or O')
def turnChooser(self):
while True:
self.choice = input("Would you like to go first, second or decide by coin toss? (enter 1, 2 or c) ")
if self.choice in ["1","2","c"]:
if self.choice == 1:
print("G")
self.cur_turn = self.playerLetter()
elif self.choice == 2:
print("H")
else:
print("P")
break
else:
print ('Please enter 1, 2 or c')
game = Game()
game.letterChoice()
game.turnChooser()
# If you want to read any of the variables in Game just write 'self.VARIABLE_NAME'
您需要為playerLatter
定義函數屬性
對於EX:
def foo():
foo.playerletter=input('Please choose X or O.').upper()
>>> foo()
Please choose X or O.x
>>> foo.playerLetter
'X'
從其他功能訪問
def bar():
variable=foo.playerLetter
print(variable)
>>> bar()
X
>>>
您始終可以檢查給定功能可以使用哪些屬性
>>> [i for i in dir(foo) if not i.startswith('_')]
['playerLetter']
>>>
將turnchooser()編輯為turnchooser(var),然后在調用函數時將字母傳遞給函數,如下所示:
def LetterChoice():
Code...
turnchooser(playerletter)
和,
def turnchooser(var):
Code...
該字母將放置在一個名為var的變量中,這意味着您的代碼將使用字母作為var而不是playerletter。
當然,您可以將名稱更改為任何您喜歡的名稱。
您可以向該函數添加盡可能多的變量,但是它們都應該分配有一些東西,也就是說,您不能像這樣調用前一個函數:
turnchooser()
除非您為其分配默認值,否則:
def turnchooser(var = 'x')
除非另有說明,否則無論何時調用該函數,“ var”的值都是x。
請注意,如果要將其從一個函數傳遞給另一個函數,則必須將字母分配給變量,然后在“ LetterChoice”之外調用該函數,或者在“ LetterChoice”的定義中調用它
在其中具有變量的函數中,鍵入:
global variableName
顯然,將variableName更改為實際調用的變量。 希望這可以幫助!
湯米
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.