【问题标题】:Basic Function Query基本功能查询
【发布时间】:2021-03-27 12:06:06
【问题描述】:

关于这段代码的2个问题。代码可以工作,但是关于 is_win 函数的代码中有一些我不明白的地方。

问题一——定义函数is_win时,是否在if语句中调用它,在def play函数内?

问题 2 - 如果是,我不明白为什么需要参数用户和计算机来执行计算,而不是玩家和对手。通常,当您调用函数时,信息由函数中定义的参数转换。但在这种情况下,它似乎反过来工作。谁能解释一下这是为什么?

谢谢。

import random

def play():
    user = input ("What's your choice? 'R' for rock, 'P' for paper, 'S' for scissors: ")
    computer = random.choice(["r", "p", "s"])
    print (f"Computer chose {computer}")
    if user == computer:
        return ("You tie")

    if is_win(user,computer):
        return ("You won")

    return "You lost"

def is_win(player,opponent):
    if (player == "r" and opponent == "s") or (player == "s" and opponent == "p") or (player == "p" and opponent == "r"):
            return True

print (play())

【问题讨论】:

    标签: function parameter-passing


    【解决方案1】:

    定义和调用函数is_win(player, opponent)时,playeropponent可以是任意变量,不必同名。

    这样想,如下代码:

    if is_win(user, computer):
        return ("You won")
    

    相当于:

    if is_win(computer, user):
        return ("You lost")
    

    在第一种情况下,用户是玩家,计算机是对手,而在第二个例子中,计算机是玩家 > 而用户是对手

    如果您对此有更多的困惑,您需要阅读更多关于 python 中的变量、作用域和函数的信息:

    【讨论】:

    • 这段代码中调用的函数is_win在哪里?
    • @JonSpelman:在每个代码块的第一行调用它。
    猜你喜欢
    • 2016-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-30
    • 2019-06-15
    相关资源
    最近更新 更多