I have the following script that is taken from a python game development book. The author explains everything, except for one thing. I tried to figure it out myself, but as a beginner it is not making much sense. Here is the code:
import random
import time
def displayIntro():
print('You are on a planet full of dragons. In front of you,')
print('you see two caves. In one cave, the dragon os friendly')
print('and will share his treasure with you. The other dragon')
print('is greedy and 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(3)
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()
Now my question is this: how does the parameter chosenCave get a value? To me it seems that it wasn’t defined anywhere. We defined what cave is and what friendlyCave is, but not chosenCave. What is happening here? What am I missing?
Sorry if this is a complete beginner question.
The parameter chosenCave receives its value when the checkCave function is invoked. Prior to that it doesn’t have a value.
When you define a function you have to option to declare parameters to that function. That’s where you see chosenCave in the parenthese next to the name of the function. Those parentheses create what is formally called the “Formal Parameter Declaration”. It defines how someone would call your method. It doesn’t actually invoke the method, but it just tells everyone how to call it.
Down in the bottom section of the code you see this code:
That is called the “Actual Parameter Declaration”. Its a fancy way of saying this is what the actual value of chosenCave will be. In your example, chosenCave has been assigned the value of what’s in the variable caveNumber.
Now that doesn’t mean chosenCave is forever more one value. It just means that during this execution of the function it’s a specific value. Every time you invoke a function a new value could be assigned to chosenCave. For example, the user could choose cave 1, get some treasure, say yes to play again, and then choose cave 2. That’s two invocations of checkCave. First is checkCave( 1 ), and the second is checkCave( 2 ). The value of chosenCave can change with each invocation of the function.