【问题标题】:Rock^Paper^Scissors Total Amounts not receiving the updated values...PythonRock^Paper^Scissors Total Amounts 未收到更新的值...Python
【发布时间】:2015-06-06 14:44:03
【问题描述】:

这是我的代码:

import os
import random
import time

def main():
    ### Declarations ###
    items = []
    userItems = []
    machineItems = []
    totalTies = 0
    userWins = 0
    cpuWins = 0

    ### Adding elements ###
    items.append("rock")
    items.append("paper")
    items.append("scissors")

    ### Function calls ###
    replay(items, userItems, machineItems, totalTies, userWins, cpuWins)
    os.system('cls')
    printResults(userItems, machineItems, totalTies, userWins, cpuWins)

def replay(items, userItems, machineItems, totalTies, userWins, cpuWins):
    response = 'yes'
    while (response == 'yes'):
        print("*Please enter only lower-cased words*")

        ### It was a tie! ###
        ## This is also Input Validation for the below loop ##
        print("Do you pick: ",
              "\n\t1. Rock?",
              "\n\t2. Paper?",
              "\n\t3. Scissors?")
        userChoice = input("Object: ")
        machineChoice = random.choice(items)

        if (userChoice == machineChoice):
            print("Another game is to be played.")
            time.sleep(.5)
            print("Seting up...")
            time.sleep(1)

            os.system('cls')

            print("Do you pick: ",
                  "\n\t1. Rock?",
                  "\n\t2. Paper?",
                  "\n\t3. Scissors?")
            userChoice = input("Object: ")
            machineChoice = random.choice(items)

            totalTies += 1
            userItems.append(userChoice)
            machineItems.append(machineChoice)

            os.system('cls')

            while (userChoice == machineChoice):
                print("Another game is to be played.")
                time.sleep(.5)
                print("Seting up...")
                time.sleep(1)

                print("Do you pick: ",
                      "\n\t1. Rock?",
                      "\n\t2. Paper?",
                      "\n\t3. Scissors?")
                userChoice = input("Object: ")
                machineChoice = random.choice(items)

                totalTies += 1
                userItems.append(userChoice)
                machineItems.append(machineChoice)

                os.system('cls')

        ### User picked "rock" ###
        elif(userChoice == "rock"):
            if(machineChoice == "paper"):
                print("You chose: ", userChoice)
                time.sleep(.5)
                print("The computer chose: ", machineChoice)
                time.sleep(.5)
                print("And the verdict is...")
                time.sleep(1.5)

                print("Paper covers rock.")
                time.sleep(.5)
                print("You lose.")

                cpuWins += 1
                userItems.append(userChoice)
                machineItems.append(machineChoice)
                os.system('cls')

            elif(machineChoice == "scissors"):
                print("You chose: ", userChoice)
                time.sleep(.5)
                print("The computer chose: ", machineChoice)
                time.sleep(.5)
                print("And the verdict is...")
                time.sleep(1.5)

                print("Rock crushes scissors.")
                time.sleep(.5)
                print("You win!")

                userWins += 1
                userItems.append(userChoice)
                machineItems.append(machineChoice)
                os.system('cls')

        ### User picked "paper" ###
        elif(userChoice == "paper"):
            if(machineChoice == "scissors"):
                print("You chose: ", userChoice)
                time.sleep(.5)
                print("The computer chose: ", machineChoice)
                time.sleep(.5)
                print("And the verdict is...")
                time.sleep(1.5)

                print("Scissors cuts paper.")
                time.sleep(.5)
                print("You lose.")

                cpuWins += 1
                userItems.append(userChoice)
                machineItems.append(machineChoice)
                os.system('cls')

            elif(machineChoice == "rock"):
                print("You chose: ", userChoice)
                time.sleep(.5)
                print("The computer chose: ", machineChoice)
                time.sleep(.5)
                print("And the verdict is...")
                time.sleep(1.5)

                print("Paper covers rock.")
                time.sleep(.5)
                print("You win!")

                userWins += 1
                userItems.append(userChoice)
                machineItems.append(machineChoice)
                os.system('cls')

        ### User picked "scissors" ###
        elif(userChoice == "scissors"):
            if(machineChoice == "rock"):
                print("You chose: ", userChoice)
                time.sleep(.5)
                print("The computer chose: ", machineChoice)
                time.sleep(.5)
                print("And the verdict is...")
                time.sleep(1.5)

                print("Rock smashes scissors.")
                time.sleep(.5)
                print("You lose.")

                cpuWins += 1
                userItems.append(userChoice)
                machineItems.append(machineChoice)
                os.system('cls')

            elif(machineChoice == "paper"):
                print("You chose: ", userChoice)
                time.sleep(.5)
                print("The computer chose: ", machineChoice)
                time.sleep(.5)
                print("And the verdict is...")
                time.sleep(1.5)

                print("Scissors cuts paper.")
                time.sleep(.5)
                print("You win!")

                userWins += 1
                userItems.append(userChoice)
                machineItems.append(machineChoice)
                os.system('cls')

        response = input("Replay? ('yes' to continue) ")
        os.system('cls')

def printResults(userItems, machineItems, totalTies, userWins, cpuWins):
    print("You chose: ", "\n")
    for i in userItems:
        print("\t", i)

    print("The computer chose: ", "\n")
    for i in machineItems:
        print("\t", i)

    print("Total ties: ", totalTies)
    print("User wins: ", userWins)
    print("Computer wins: ", cpuWins)

    gamesPlayed = (totalTies + userWins + cpuWins)
    print("Games played: ", gamesPlayed)

    input("Press [Enter] to continue...")

main()

这只是一个 Rock_Paper_Scissors 程序,如果出现平局则重新启动,记录 userWinscpuWinstotalTies。当我运行它时,一切正常,除了userWinscpuWinstotalTies 没有收到更新的值,所以当我在程序结束时打印出结果时,向用户展示他们如何做了,它会说userWinscpuWinstotalTiesgamesPlayed都是0。我不明白,因为列表userItemsmachineItems,用于向用户显示选择了什么在每一方,工作,但不是前面陈述的变量。有人可以告诉我我做错了什么吗?提前谢谢!

【问题讨论】:

  • Python 中的列表是可变的。整数不是,当它作为参数传递时,你不能更新整数值。

标签: python variables python-3.x


【解决方案1】:

Python 中的列表是可变的。整数不是。因此,您不能通过将整数值作为函数参数传递来更新它。

最少的可重现代码:

def f(a_list, an_integer):
     a_list.append(3)
     an_integer += 1
     print a_list, an_integer


l = []
i = 1
f(l, i)  # output: [3] 2
f(l, i)  # [3, 3] 2
f(l, i)  # [3, 3, 3] 2
print l, i  # [3, 3, 3] 1

解决方案是从函数中返回这些值并显式更新这些整数。

totalTies, userWins, cpuWins = replay(...)

【讨论】:

  • 我认为这与列表的可变性无关 - 在您的示例中分配 a_list 也不会反映在函数之外。
【解决方案2】:

在 Python 中将值传递给函数会创建该值的副本,无法通过修改函数内的值来更新原始函数参数:

def a(mynumber):
    mynumber = 10

mynumber = 5 
a(mynumber) 
print(mynumber)  # will print 5

即使对于列表和复杂对象,这也是一样的 - 虽然您可以修改调用对象的方法,这可能会修改其状态,但您不能替换调用者代码中的实际引用。

在您的情况下,一种可能的解决方案是使用全局变量并且不将“共享”变量作为参数传递:

userItems = 0
machineItems = 0 
totalTies = 0 
userWins = 0 
cpuWins = 0

def replay(items):
    global userItems, machineItems, totalTies, userWins, cpuWins
    ...

def printResults():
    global userItems, machineItems, totalTies, userWins, cpuWins
    ...

【讨论】:

    【解决方案3】:

    感谢您的所有帮助,但我已经想通了。

    main()printResults() 应该是这样的:

    def main():
        ### Declarations ###
        items = []
        userItems = []
        machineItems = []
        totalTies = []
        userWins = []
        cpuWins = []
    
        ### Adding elements ###
        items.append("rock")
        items.append("paper")
        items.append("scissors")
    
        ### Function calls ###
        replay(items, userItems, machineItems, totalTies, userWins, cpuWins)
        os.system('cls')
        printResults(userItems, machineItems, totalTies, userWins, cpuWins)
    
    def printResults(userItems, machineItems, totalTies, userWins, cpuWins):
        print("You chose: ", "\n")
        for i in userItems:
            print("\t", i)
    
        print("The computer chose: ", "\n")
        for i in machineItems:
            print("\t", i)
    
        print("Total ties: ", sum(totalTies))
        print("User wins: ", sum(userWins))
        print("Computer wins: ", sum(cpuWins))
    
        gamesPlayed = (sum(totalTies) + sum(userWins) + sum(cpuWins))
        print("Games played: ", gamesPlayed)
    
        input("Press [Enter] to continue...")
    

    【讨论】:

    • 再次感谢大家的帮助,我不怀疑这些会奏效!好好休息一天! Python 新手,Ghost_Programmer!
    【解决方案4】:

    这里的问题是整数在 python 中是不可变的。当您增加变量userWinscpuWinstotalTies 的值时,变量的值在replay 函数内更新。另一方面,列表是可变的。因此,如果您在函数内部修改列表(添加或删除元素),更改会反映在函数外部。

    你可以做两件事:

    1. 将三个整数变量设置为全局变量。此方法有效,但不推荐
    2. 使函数返回改变后的整数值。

      replay函数末尾添加下面一行

      return (totalTies, userWins, cpuWins)
      

      另外,将调用replay 函数的行修改为以下内容:

      (totalTies, userWins, cpuWins)=replay((items, userItems, machineItems, totalTies, userWins, cpuWins)
      

      这段代码现在应该可以工作了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-26
      • 1970-01-01
      • 2015-07-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多