In the previous tutorial we have our little coin flipping program. It is only 11 lines long, yet it is getting a little complicated. If someone handed you this program and you had never seen it before, you would have to look at it awhile to figure out what it is doing.
One thing that can help control the complexity would be to take little pieces of code and give them names. This next program shows a way to do that:
In this program, we have created, or defined, our own function to hold the part of the program that flips the coin. We did this using the “def” keyword in Python. This new function accepts a parameter that tells it how many times to flip the coin. The function counts the number of heads that come up. Then it returns the number of heads it counts. To use the function, we call it and pass in 1,000. We store the result from the function in the variable NumberOfHeads. Then we derive the number of tails from NumberOfHeads.
Another thing we can do to make the program more readable is to add comments to the program. A comment is simply a human-readable piece of text that lets one programmer explain something to another programmer. The computer simply ignores all comments, because they would be meaningless to the computer. In Python, the way you mark a comment is by putting a “#” in front of it. So there it is. We have flipped a coin 10,000 times almost instantly using a computer simulation. This is one of the things that makes computer programming so powerful, and so much fun. We can simulate all kinds of things with computers.
Our formerly 11 line long program is now 20 lines long. But if we handed it to another programmer, it would be much easier for the other programmer to understand what is going on.
And now lets step back and look at what we have accomplished. We have simulated 10,000 coin flips with a computer program that is just a few lines long. It would take us a whole day to flip a real coin 10,000 times. Now we can do it in a second. And if you want to flip the coin a million times instead, or even 10 million times, a quick modification to the program will get the job done. Try it! This example shows you the power of computer programming, and how interesting programming can be.
Let’s try simulating a dice roll in the next tutorial…
Python Table of Contents
- Tutorial 1 – Getting started – creating output from a computer program
- Tutorial 2 – Adding input to a computer program
- Tutorial 3 – The coin flip simulator and random numbers
- Tutorial 4 – Functions and comments
- Tutorial 5 – The dice simulator – lists in Python