Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 试图让代码传递并保持统计信息而不使用全局变量_Python_Python 3.x - Fatal编程技术网

Python 试图让代码传递并保持统计信息而不使用全局变量

Python 试图让代码传递并保持统计信息而不使用全局变量,python,python-3.x,Python,Python 3.x,新的编码和尝试一个简单的石头,布,剪刀游戏。需要在用户退出时显示统计信息,而不使用全局差异。目前,无论循环运行了多少次,它都只打印win=0、loss=0、tie=0。寻找一种方法,将赢、输和平局作为参数传递,并保存它们,直到用户退出循环 尽量不要将代码分成函数,因为这样会导致类似的问题-函数只有在需要重用其中的代码时才有用。我还建议将play_reach()中的else语句更改为elif语句:)您希望根据代码的功能将代码划分为函数!不要在处理实际游戏的函数中包含跟踪统计信息的代码。相反,让游

新的编码和尝试一个简单的石头,布,剪刀游戏。需要在用户退出时显示统计信息,而不使用全局差异。目前,无论循环运行了多少次,它都只打印win=0、loss=0、tie=0。寻找一种方法,将赢、输和平局作为参数传递,并保存它们,直到用户退出循环



尽量不要将代码分成函数,因为这样会导致类似的问题-函数只有在需要重用其中的代码时才有用。我还建议将
play_reach()
中的
else
语句更改为elif语句:)

您希望根据代码的功能将代码划分为函数!不要在处理实际游戏的函数中包含跟踪统计信息的代码。相反,让游戏返回结果并在游戏函数外增加正确的计数器。比如说,

def the_game(computer, user):
    if <tie condition>:
        return 0
    elif <win condition>:
        return 1
    else: # loss
        return -1
其他轻微改善:

如果elif else,则不必编写所有嵌套的
,只需创建一个字典,定义每一个移动所击败的移动

winning_moves = { "R": "S", # rock beats scissor
                  "S": "P", # scissor beats paper
                  "P": "R"  # paper beats rock
                }
然后,您需要检查两个条件:

def the_game(computer, user):
    if computer == user: 
        return 0 # this is a tie
    elif winning_moves[user] == computer:
        return 1 # User's move beats computer's move
    else:
        return -1
要包含你的单词(“石头砸剪刀”等),你还可以将其添加到字典中:

winning_moves = { "R": ("S", "smashes"), # rock smashesscissor
                  "S": ("P", "cut"), # scissor cuts paper
                  "P": ("R", "covers")  # paper covers rock
                }
def the_game(computer, user):
    if computer == user: 
        return 0 # this is a tie
    elif winning_moves[user] == computer:
        return 1 # User's move beats computer's move
    else:
        return -1
winning_moves = { "R": ("S", "smashes"), # rock smashesscissor
                  "S": ("P", "cut"), # scissor cuts paper
                  "P": ("R", "covers")  # paper covers rock
                }
def the_game(computer, user):
    if computer == user:
        print("It's a tie!") 
        return 0 # this is a tie
    elif winning_moves[user][0] == computer:
        verb = winning_moves[user][1]
        message = f"{user} {verb} {computer}.\nYou win!"
        print(message)
        return 1 # User's move beats computer's move
    else:
        verb = winning_moves[computer][1]
        message = f"{computer} {verb} {user}.\nComputer wins!"
        print(message)
        return -1