Dark theme

Let's use this:

    decision = input("You come to a junction. Turn left or right [L,R]: ")

    if decision == "L" or decision == "l":
        print("You turn left and see a terrible ogre and a horrible troll!")
        rounds = fight(2, "Ogre")
        print("You fought it for",rounds,"rounds")
        rounds = fight(3, "Troll")
        print("You fought it for",rounds,"rounds")

The value that comes back is copied from the functions "count" variable into the programs "rounds" variable when we asign it to the function call:

        rounds = fight(2, "Ogre")

So, functions not only clean up our code in one place, but they clean up our code in multiple places. Having one copy of the fight code also means there's only one copy to make mistakes in.

We've also made it much more flexible by using arguments (values we pass into functions) and parameters (the variables inside the parentheses in the function, which pick up the argument values).

Give it a go changing your other creature fight so it uses this new function. Once you've done this, go back to your own game and clean up the code in the same way. You could have a function that has different characters giving out different amounts of gold, or saying different things (passed into the function), or with wisdom as well as strength.

In the next part, we'll add a couple of small things to tidy up the last few loose ends.

[Home > Part 3 > Part 4]