当我在下面运行我的代码时,我得到一个平局和玩家二的结果,但是玩家一显示为NO NAME。当我输入一个名字时,无法弄清楚为什么playerOne变量没有改变。新手程序员希望对我的工作有所帮助。
import random
#the main function
def main():
print
#initialize variables
endProgram = 'no'
playerOne = 'NO NAME'
playerTwo = 'NO NAME'
#call to inputName
playerOne, playerTwo = inputNames(playerOne, playerTwo)
#while loop to run program again
while endProgram == 'no':
winnerName = 'NO NAME'
#initialize variables
p1number = 0
p2number = 0
#call to roll dice
winnerName = rollDice(playerOne, playerTwo, winnerName)
#call to display info
winnerName = displayInfo(winnerName)
endProgram = raw_input ('Do you want to end the program? (Enter yes or no): ')
#this function gets the players names
def inputNames(playerOne, playerTwo):
playerOne = raw_input('Player one enter name ')
playerTwo = raw_input('Player two enter name ')
return playerOne, playerTwo
#this function will get the random values
def rollDice(winnerName, playerOne, playerTwo):
p1number = random.randint (1, 6)
p2number = random.randint (1, 6)
if (p1number == p2number):
winnerName = 'TIE'
elif (p1number > p2number):
winnerName = playerOne
else:
winnerName = playerTwo
return winnerName
#this function displays the winner
def displayInfo(winnerName):
print 'The winners name is ', winnerName
#calls main
main()
答案 0 :(得分:0)
查看rollDice
函数中的参数顺序。
#this function will get the random values
def rollDice(winnerName, playerOne, playerTwo):
....
....
期待winnerName
作为第一个参数。在main
函数中,您将其设置为最后一个参数。
改变这个:
winnerName = rollDice(playerOne, playerTwo, winnerName)
到此:
winnerName = rollDice(winnerName, playerOne, playerTwo)
希望这有帮助。
答案 1 :(得分:0)
因为变量playerOne是函数“main”的本地变量。当您在其他函数中为该变量名分配时,您将创建第二个单独的值。
如果要在函数之间共享变量,可以使用'global'关键字来表示,更新变量的值时,表示全局变量名称空间中的值,而不是函数本地的变量名称空间。 :
def f():
global x
x += 1
x = 99
print x
f()
print x
或者,您可以从函数返回值:
def calcNewValue(x):
return x+1
x = 99
print x
x = calcNewValue(x)
print x
或者使用类来保存一组常用函数的变量:
class GameState:
def __init__(self):
self.x = 99
self.y = "hello"
def update():
self.x = self.x +1
s = GameState()
print s.x
s.update()
print s.x