Translations of this page:

004 print



So far, the Gobling Dice Duel is not only boring and predictable, it is also only visible for the computer, not for us humans. To change that and to get rid of the need for inspecting each variable manually, let's use the print function.

With the print function, you can force python to print out ( usually to the screen ) some text ( so called strings ) or the value of variables or an combination of both. The things you want to print out need to be put inside the round brackets of the print function. Yes, the arguments ! If you want to print out more than one thing, the arguments need to be comma seperated. Python is clever enough to put spaces between the “things” so that the output is usually good to read. Also note that the print function does an New Line or carriage return after each printing. Let's see this little example of the Goblin dice duel:

source code

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

code discussion

This program gives now an real output, like you can see if you run it in your python editor or in the python shell or online (click on the graphic below):

Click on the graphic

better printing

The mixing of variable values and text ( in quotes ) is something you will see very often in python code as well as in various python tutorials. There are several ways how to mix variables and textstrings inside print:

combatround = 1
print("--- this is combat round",combatround, "---")           # comma seperated 
print("--- this is combat round " + str(combatround) + " ---") # notice the space after round
print("--- this is combat round %i ---" % combatround)         # old syntax from python2
print("--- this is combat round {0} ---".format(combatround))  # new syntax (recommended)

While the output of all 4 print statements above is identical, i will for the rest of this tutorial use the last variant with the .format syntax.

Basically, you write place-holders for variables inside your string in curly brackets. The zero inside the brackets is not exactly necessesary but may be helpful later. If you have several variables to put into an string you write several curly brackets ( ideally with numbers inside them starting with 0 and counting upwards):

combatround = 1
hitpointsStinky = 22
hitpointsGrunty = 43
print("combatround {0} Stinky has {1} hitpoints, Grunty has {2} hitpoints".format(combatround, hitpointsStinky, hitpointsGrunty))

If python interprets this code, it will replace the curly brackets with the values of the variables given in the .format part. So {0} get replaced with the value of combatround, {1} get replaced with the value of hitpointsStinky etc.

There is a lot more about printing and formating to know. See the python documentaion for details.


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