python - Python 中的参数和参数如何工作?

标签 python function python-3.x parameters arguments

我查遍了 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 ? 有人可以解释一下吗?

最佳答案

在函数中

def checkCave(chosenCave):
    ...

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

代数类比

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

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)

关于python - Python 中的参数和参数如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21226307/

相关文章:

c - 我如何使指针工作?

python - ValueError : not enough values to unpack (expected 2, 得到 1) NetworkX python 3

python - 从具有对象属性之一的对象列表中获取索引

Python 清除用于 Tkinter 小部件的列表

python - 运行时错误: both arguments to matmul need to be at least 1d but they are 0d and 2d

python - 绘制烛台(matplotlib)

python - 如何突出显示文本小部件的当前行?

python - 变量的 mod_python 缓存

sql-server - 提取字符串的 SQL 函数

c - 将字符串数组从函数传递到主函数(C 代码)