The whole purpose of programs (and computers for that matter) is automation. That is, computers and the programs they run are designed to do stuff we don't feel like doing ourselves.
Functions are one way we automate stuff in our programs. In the following example, I've written a function called castSpell that specifies one parameter. Parameters are those things typed in between the parentheses following a function's name. So, in the line castSpell(spell), spell is the parameter to the function called castSpell. def is simply the keyword in python that begins the creation of any function. The body of the function is the line directly below the def ... line. A couple of lines below that we see a call to the castSpell function. In that call, we've provided the argument "Lightning Bolt" that satisfies the parameter required.
Again, castSpell is the name of the function. The spell inside the parantheses of castSpell(spell) is the parameter. The line below that is the body of the function.
You may have noticed the indentation in this and previous examples. That is, you have seen that any line that ends with a colon (:) is followed below it by a line indented by 4 spaces. This is a part of python's syntax (rules for how the language works). If you fail to indent by 4 spaces in the body of any element of code ending in a colon, you will likely experience what is known as a syntax error.
- Let's go ahead and get our feet wet with some syntax errors. Remove the indentation from the body of the castSpell function. Run it. What happened?
- Fix the indentation. Now, take the last line (the one that has the call to the castSpell function), cut it and paste it right up inside the body of the castSpell function. Run. What happens?
- Put the call to castSpell back down and outside of the castSpell function body. Remove the "Lightning Bolt" argument from inside the call's parentheses. Run. What happened?
- Modify that call to the castSpell function so that the output of running the program is now "You are casting the Dragon Breath spell!".
- What would the output of the program be if you provided "Ice Blast" as the argument inside the castSpell function call?
Join the Dungeon Crawl: A place for programmers to ponder, partake, and peruse postulations pertaining to programming, politics, potions, and pizza.
If you subscribe on Patreon, you will be granted access to the Dojo, a growing collection of quality computer science classes created and actively mantained and frequented by the Dungeon Master!Become a Patron!