【问题标题】:How do Arguments and Parameters Work in Python? [closed]参数和参数在 Python 中是如何工作的? [关闭]
【发布时间】:2014-01-20 04:35:30
【问题描述】:

我查看了整个 Stackoverflow,但找不到答案,所有的网络教程都在我脑海中浮现。我有一个我不明白的功能代码

import random
import time

def displayIntro():
    print('You are in a land full of dragons. In front of you,')
    print('you see two caves. In one cave, the dragon is friendly')
    print('and will share his treasure with you. The other dragon')
    print('is greedy nd hungry, and will eat you on sight.')
    print()

def chooseCave():
    cave = ''
    while cave != '1' and cave != '2':
        print('Which cave will you go into? (1 or 2)')
        cave = input()

    return cave

def checkCave(chosenCave):
    print('You approach the cave...')
    time.sleep(2)
    print('It is dark and spooky...')
    time.sleep(2)
    print('A large dragon jumps out in front of you! He opens his jaws and...')
    print()
    time.sleep(2)

    friendlyCave = random.randint(1, 2)

    if chosenCave == str(friendlyCave):
        print('Gives you his treasure')
    else:
        print('Gobbles you down in one bite!')

playAgain = 'yes'
while playAgain == 'yes' or playAgain == 'y':
    displayIntro()
    caveNumber = chooseCave()
    checkCave(caveNumber)
    print('do you want to play again? (yes or no)')
    playAgain = input()

我不明白def checkCave(chosenCave): 部分,为什么参数说chosenCave? 谁能解释一下?

【问题讨论】:

    标签: python function python-3.x parameters arguments


    【解决方案1】:

    在函数中

    def checkCave(chosenCave):
        ...
    

    chosenCave 成为您传递给函数的局部变量。然后,您可以访问该函数内部的值来处理它,提供您想要提供的任何副作用(例如打印到屏幕上,就像您正在做的那样),然后返回一个值(如果您不这样做)如果不显式执行,Python 默认返回 None,它的 null 值。)

    代数类比

    在代数中,我们这样定义函数:

    f(x) = ...
    

    例如:

    f(x) = x*x
    

    在 Python 中,我们这样定义函数:

    def f(x):
        ...
    

    并与上面的简单示例保持一致:

    def f(x):
        return x*x
    

    当我们希望将该函数的结果应用于特定 x(例如 1)时,我们调用它,它在处理该特定 x 后返回结果。:

    particular_x = 1    
    f(particular_x)
    

    如果它返回我们想要的结果供以后使用,我们可以将调用该函数的结果分配给一个变量:

    y = f(particular_x)
    

    【讨论】:

      【解决方案2】:

      chosenCave 这个名字似乎被用来描述它所代表的东西,即玩家选择的洞穴。你期待它被命名为别的吗?该名称不需要与程序中其他位置的任何名称匹配或不匹配。

      【讨论】:

        猜你喜欢
        • 2016-12-27
        • 2015-11-21
        • 1970-01-01
        • 2018-09-21
        • 2018-07-07
        • 2019-08-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多