Python Vs Scratch II

This is the third post in a series for the Naas-Sallins Coder Dojo about using the Python programming language.  This time we are going to have a look at how we break up a program into small sections which perform particular tasks and how we connect those sections together. We are going to use our lotto example from the last time

""" Lotto number generator for dojo"""
import random
balls = [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,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45]
picks = random.sample(balls,6)
print picks

but we are going to extend it so that we ask our user to enter their 6 numbers and then use our random number selection code to simulate the lotto draw. We will keep going until the draw matches our numbers and then we will tell the user how many goes it took.

So we are going to introduce the concept of a function which is a small chunk of code that we use to do a particular thing.  An equivalent is a block which is available in Scratch 2 and BYOB/SNAP. We start off by defining its name and then we write the code that we want the function to perform. An example makes more sense so amending our code above to put it in a function we get

def draw_random():
picks = random.sample(balls,6)
    return(picks)

now anytime we want to use the code in the function we just call it by using its name draw_random(). For example if we want to print out two sets of numbers our program would look like this

import random
def draw_random():
    """get 6 randoms from the pot"""
    picks = random.sample(balls,6)
    return(picks)

balls = [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,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45]

print draw_random()
print draw_random()

So whats important to get from this is the structure of a function, we give it a name and then all the code that is part of the function is indented and when its finished it returns a value to the code that called the function. In this case it returns our list of 6 numbers to the print statement which displays the value returned. Our output would be something like

[2, 7, 19, 24, 28, 40]
[7, 18, 24, 31, 39, 45]

Now we want to get the user to enter the numbers they want to pick. In scratch we might have something like

scratchask6

where we ask the user for a number and add that number to our list.

In python we can do this as follows

for repeat in range(6):
    answer = raw_input("enter a number between 1 and 45")
    selection.append(int(answer))

Here we are saying that we want to do something 6 times,
that we will make the variable answer equal to whatever the user enters
and then we add the answer to our list called selection (we actually convert answer to an integer number with the int(answer) part so make sure the user entered a number)

Now if we put together what we have and pop the code to get user input into a function we can come up with the following program

""" Lotto number generator 2 for dojo"""
import random

def draw_random():
    """get 6 randoms from the pot"""
    picks = random.sample(balls,6)
    picks.sort()
    return(picks)

def get_selection():
    """get 6 numbers from the user"""
    selection = []
    for i in range(6):
        number = raw_input('Enter a number ')
        selection.append(int(number))
    selection.sort()
    print "You Picked"
    print selection
    return(selection)

balls = [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,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45]
count = 0
myselection = get_selection()
while True:
    draw = draw_random()
    count += 1
    if draw == myselection:
        print "You won on draw"
        print count
        print "The number of years it would have taken for your numbers to come up is"
        print count/104 #--2 draws per week
        break

So lets go through this to see what we are doing. Our first function draw_random is the same as above except for the line picks.sort() which takes our list and sorts it in ascending order. We do this to make it easier to compare out list of random numbers with our list of picked numbers. Our second function get_selection is where we get the 6 numbers from the user, again we sort our list before we return it.

Our main section of code starts when we make our list containing the 45 balls and then make a variable called count which we set to zero. The next line myselection = get_selection() is where we call the get_selection function and myselection gets the value of the list returned. Next we start a loop with the while True: statement. This is similar to

scratchmain

a forever loop in Scratch. We call our draw_random function and it returns a list of 6 random numbers to draw. After that we add one to our variable count and then check if our 6 random numbers are equal to the 6 numbers that the user picked. If they are we tell the user how many times we picked the random numbers before they matched and how many years it would have taken to do that in the real bi-weekly lotto draw. If they didn’t match then we tray again until they do.

The main thing to take away from this is the general structure of our python program. It is worth typing the commands into the python editor as you get the hang of the python syntax. Also if you are running on an older computer be prepared for your program to run for a while. As usual don’t worry if you get stuck or have problems, I will give you a hand at the next dojo session but it is worth giving this or a similar sized program a try so you can get the hang of python and how it works.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s