In this now you code we will learn to re-factor a program into a function. This is the most common way to write a function when you are a beginner. Re-factoring is the act of re-writing code without changing its functionality. We commonly do re-factoring to improve performance or readability of our code. Through the process we will also demonstrate the DRY (don't repeat yourself principle of coding).
The way you do this is rather simple. First you write a program to solve the problem, then you re-write that program as a function and finally test the function to make sure it works as expected.
This helps train you to think abstractly about problems, but leverages what you understand currently about programming.
The best way to get good at writing functions, a skill you will need to master to become a respectable programmer, is to use the Write - Refactor - Test - Rewrite approach. The basic idea is as follows:
Which Rock, Paper Scissors strategy is better? Random guessing or always choosing rock? Let's write a program which plays the game of Rock, Paper, Scissors 10,000 times and compares strategies. You can get the rock, paper scissors code from the previous lab.
Here's the algorithm:
play_game(playera, playerb)
which returns the winning player.
In [ ]: