参数和参数如何在Python中工作?

时间:2014-01-20 04:35:30

标签: 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? 有人可以解释一下吗?

2 个答案:

答案 0 :(得分:2)

在功能

def checkCave(chosenCave):
    ...

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

答案 1 :(得分:1)

似乎已选择名称chosenCave来描述它所代表的内容,即玩家选择的洞穴。你是否期望它被命名为别的东西?该名称不需要匹配或不匹配程序中其他位置的任何名称。