Choosing Numbers Randomly

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.

randomnumbers.py
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
from __future__ import print_function
import random

def main():
    rps = random.random()
    if rps < 0.3333333:  # will be true 1/3 of the time
        print("ROCK")
    elif rps < 0.6666667:
        print("PAPER")
    else:
        print("SCISSORS")

    # pick four random integers, each 1-10
    a = random.randint(1,10)
    b = random.randint(1,10)
    c = random.randint(1,10)
    d = random.randint(1,10)
    print("1-10:\t{}\t{}\t{}\t{}".format(a, b, c, d))

    # pick four random integers, each 10-20
    a = random.randint(10,20)
    b = random.randint(10,20)
    c = random.randint(10,20)
    d = random.randint(10,20)
    print("10-20:\t{}\t{}\t{}\t{}".format(a, b, c, d))


if __name__ == "__main__":
    main()

What You Should See

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 write main() 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()."

Study Drills

  1. Add some code to choose some random numbers between 70 and 100 and print them out.



©2017 Graham Mitchell