gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 23:29:14 25 4
gpt4 key购买 nike

我查遍了 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com