【问题标题】:Results from my program [closed]我的程序的结果[关闭]
【发布时间】:2014-11-01 01:40:48
【问题描述】:

当我在下面运行我的代码时,我得到了平局和玩家二的结果,但玩家一显示为 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()

【问题讨论】:

  • 抱歉 -- StackOverflow 不是一个通用的调试服务。现在,如果您已将问题缩小到特定问题或疑问(最好使用最少的复制器 - 请参阅 stackoverflow.com/help/mcve),那么我们将在更好的地方提供帮助。

标签: python python-2.7


【解决方案1】:

查看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)

希望这会有所帮助。

【讨论】:

  • 也可以乱序调用函数参数。然后你必须用winnerName = rollDice(playerOne=playerOne, playerTwo=playerTwo, winnerName=winnerName)调用它
  • 感谢大家的帮助。认真地盯着这个 2 小时试图弄清楚。我的万圣节做好了!
  • 我什至不知道为什么你有winnerName 作为参数。您根本不会在函数中使用它。
【解决方案2】:

这是因为变量 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

【讨论】:

    猜你喜欢
    • 2013-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-31
    • 2020-05-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多