Translations of this page:

007 function

step007

functions

create your own functions

If you watch the output of the previous code example you will see something like:

 --- Goblin Dice Duel ---
round    hitpoints
 0 Stinky: 22 Grunty: 43
 1 Stinky: 22 Grunty: 38
 2 Stinky: 21 Grunty: 32
 3 Stinky: 20 Grunty: 32
 4 Stinky: 15 Grunty: 30
 5 Stinky: 12 Grunty: 27
 6 Stinky:  8 Grunty: 24
 7 Stinky:  4 Grunty: 18
Game Over
Grunty wins
thank you for playing Gobling Dice Duel. bye-bye!

Take a closer look at the line of combat round 7 in this example: Stinke has still 4 hitpoints left, but in the next round Grunty wins. Evidently Grunty was hitting Stinky really hard for 4 hitpoints damage or more. Sadly we don't know exactly because the damage output ist printed only inside the main loop, not after the mainloop.

While it would be no problem to copy the relevant code line

print("{0:2d} Stinky: {1:2d} Grunty: {2:2d}".format(combatround, hitpointsStinky, hitpointsGrunty))

after the while loop ( but before the Game Over message ), this is something that a good coder avoids: writing the exact code line twice.

You only code once

Why ? One reason is maintenance.

By writing the same line of code twice or even more times, you make the code harder to maintain. Imagine you need to correct an error in the duplicated code line or you make an improvement to it:
Now you must sync this correction to all the identical lines in your code. Sooner or later, you will forgot to update one of those identical lines, and your whole code comes out of sync. Working most times, and sometimes not, depending of how often the not-corrected code line is computed at runtime.
It is far better to make this correction only once in one single line.

Another reason to never code the same line twice is vanity.

If you have to code the same line several times manually, you know deep in your heart that you are no good coder. There must be a more elegant solution !

functions

By defining your own functions, you teach your python program a trick ( some lines of code) and everytime you need this trick executed you simply call your function.

Functions can have zero or more arguments or parameters …. like the random.randint() function. And functions can return a value to the calling code. Again, like the randint() function.

function documentation

The python online documentation is not too helpful on functions:

A function definition defines a user-defined function object (see section The standard type hierarchy):

funcdef        ::=  [decorators] "def" funcname "(" [parameter_list] ")" ["->" expression] ":" suite
decorators     ::=  decorator+
decorator      ::=  "@" dotted_name ["(" [parameter_list [","]] ")"] NEWLINE
dotted_name    ::=  identifier ("." identifier)*
parameter_list ::=  (defparameter ",")*
                    ( "*" [parameter] ("," defparameter)* ["," "**" parameter]
                    | "**" parameter
                    | defparameter [","] )
parameter      ::=  identifier [":" expression]
defparameter   ::=  parameter ["=" expression]
funcname       ::=  identifier

If you remember that square brackets in the python documentation hint that something is optional, you can gather those pieces of information out of the python documentation:

  • A function definition need the keyword def
  • A function definition must have an unique function name (funcname) and a pair of round brackets behind this name.
  • A function definition can ( but do not need to) have parameters inside the round brackets. If a function has more than one parameter, those are comma seperated.
  • The first line of a function definition ends with an colon :
  • The lines after the colon are indented, building the suite

Other good things to know about functions in python are:

  • functions can have an docstring, a string (in quotes) or multi-line string (in triple quotes) doing nothing at runtime, but describe what the functions does. A bit like a comment, but better integrated in the various help functions, like the auto-complete feature of many python editors. You can access the docstring with .__doc__.
  • functions have their own local scope for variables. If you create or manipulate variables inside a function, those are not visible to the code outside the function (local variables). Unless you use global variables. However you can return values to calling code
  • functions can return value(s) to the calling code with the return statement. See python documentation. Unless the calling code does something with those values (like assigning them to variables or printing them), a function has no way of manipulating code outside the function's scope.
  • functions can have default parameters, that is a parameter followed by an = and a default value. If the function is called without such an parameter, the default value is set. Note that if you mix non-default parameters and default parameters, the non-default parameters need to come first.

function demo

Try out this function demo inside your python editor or inside your python shell. Change the values of a,b,c and d and play around with it:

source code

click reload on your browser if you see no source code here or visit Github.com

output

The output of this function demo:

a,b,c,d: 5 22 100 5000
inside the function. The parameters a,b,c:
a: 5 b: 20 c: 30
i set now d locally to -100
the local variable d: -100
i manipulate locally a and double it
local a is now: 10
returning a,b and c
a,b,c,d: 10 20 30 5000
a docstring in triple quotes explaining that this function print out variables

online example

Of course you can also test out the function demo online. Click on the graphic, and use the “edit code” feature:
Click me

improving Goblin Dice Duel

It is time to improve the Gobling Dice Duel using a function for output:

source code

click reload on your browser if you see no source code here or visit Github.com

online

Of course you can try out this example online. Just click on the graphic below:
click me

output

The output is now improved, telling what happened at the end of the game:

 --- Goblin Dice Duel ---
round    hitpoints
 0 Stinky: 22 Grunty: 43
 1 Stinky: 17 Grunty: 42
 2 Stinky: 12 Grunty: 41
 3 Stinky: 10 Grunty: 39
 4 Stinky:  8 Grunty: 35
 5 Stinky:  4 Grunty: 31
 6 Stinky: -1 Grunty: 30
Game Over
Grunty wins
thank you for playing Goblin Dice Duel. bye-bye!

As you can see here, in his last action, Stinky managed to inflict one damage on the still mighty Grunty, but received 5 damage when only having 4 hitpoints left.

step007

en/python/goblins/step007.txt · Last modified: 2014/01/09 11:07 (external edit)