There are two new things going on in this code. We are importing the random
module to be able to easily choose random numbers. And we have put all the code for the program into a function called main()
with some funky stuff at the bottom.
Just type it in for now, and I'll explain shortly.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
|
SCISSORS 1-10: 7 2 9 7 10-20: 15 10 16 17
(Actually, you probably won't see that. The numbers are random, after all.)
We start off by importing the random
module. The method random.random()
returns a random float between 0 and 1. (Exclusive of 1, so the number might be 0 sometimes but will never be larger than 0.9999999999999.)
So the if
statement
if rps < 0.33333333
...will be true roughly one-third of the time.
The method random.randint(x,y)
returns a random... int
between x and y, inclusive. Nice.
(This is much easier than what you have to do in Java.)
Okay, so let's talk about this main()
thing.
A lot of programming languages (like C, C++, Java, Go) require you to put all your code into a main()
function before you can even run anything. Python does not, as you might have noticed.
But it isn't a bad idea, especially if you have other functions in your program. (We will learn about functions soon.)
So Python programmers have developed a habit of creating a main()
function for all the code to live in and then adding a couple of magic lines at the bottom to make it run.
In Python, a function is defined using the keyword
def
. Essentially we are naming a big chunk of code "main". So then later if we writemain()
in the code, all this code runs.
On line 28, there's a strange if
statement. Honestly I don't entirely understand it myself, but it seems to mean "if they are running this python file directly, then run the function main()
."
- Add some code to choose some random numbers between 70 and 100 and print them out.
©2017 Graham Mitchell