Hello World! What’s your function?

0
671

By Jeff Kazmierski, Copy Editor

Greetings, future programmers, I hope you had a good Spring Break.  Welcome back to another installment of Hello World!, our continuing series on Python programming. Last month we went over some of the basics of programming – input/output, information processing, and variables – and got into some more advanced topics of arrays and lists. I hope you’ve been practicing some over the break, because this week we’ll be discussing functions.

Until now we’ve been writing linear programs.  They have a defined start, they work through some routines, and when they’re done, they just end.  But the operating systems and programs we use every day don’t do that, do they?  Word doesn’t just quit when you’re done writing a paper.  Programmers do this by building functions.

You’ve already seen a few standard functions, like print(), input() and range(). In our previous programs we’ve called these functions to execute their code.  But we can also create our own functions within our programs.

So, what is a function?  Simply put, it’s a reusable chunk of code that can be called repeatedly by a program. Using functions makes programming and (as you get more advanced), debugging, easier. If you have a routine your program uses repeatedly, you only have to write the code once.  

Confused yet? Let’s write some code to illustrate.  Start up IDLE and open an editor window.

A function in Python looks like this:

def showIntro():

print(“Program v.1.0”)

print(“Choose a number from 1 to 10: “)

Functions in Python are identified by the keyword def, a function name, a set of parentheses, and a colon.  The function name can be anything you choose, as long as it has no spaces or special characters and doesn’t start with a number. You can call it helloIMustBeGoing() or IamTheVeryModelOf AModernMajorGeneral() if you want, but I wouldn’t recommend it. Generally speaking, it’s better to use names that actually describe what the function does.  

Notice that the text you type after the colon is automatically indented.  To stop adding code to a function, just backspace to remove the indentation.

Let’s add another function:    

def getInput():

x = 0

while x < 1 or x > 10:

    x = int(input(“> “))

return x

The return statement at the end of the function tells Python to send the value of ‘x’ back to the routine that called getInput().  Normally, x would be lost once getInput() is finished executing, but the return statement makes x usable outside of getInput().

Add a third function:

def compare(x):

comp = False

if x == 6:

    print(“Correct!”)

  comp = True

else:

  print(“Wrong!”)

return comp

This one compares the input against an expected result, then sends a true/false (boolean) value back to the caller function.

The last one we’ll add is the main() function:

def main():

showIntro()

guess = getInput()

if compare(guess) == False:

    getInput()

else:

    x = input(“Play again (y/n)? “)

    if x[0].upper() == ‘Y’:

       getInput()

main()

The main function is where the program really starts. Because the Python interpreter reads the entire program in one line at a time before executing it, the main() function must be the last thing it reads for the program to work properly. If you put it at the start, you’ll get an error because Python will be looking for functions it hasn’t read yet. The last line of code tells Python to execute the main() function and run the program.

Okay, I admit, there’s not much to it. It’s also very predictable – once you know what the “secret number” is, you can guess it every time.  Let’s add a few more lines of code at the very beginning:

# guessmynumber.py

# a simple number guessing game    

import random

and modify our compare() function:

def compare(x):

comp = False

num = random.randint(1, 10)

if x == num:

    print(“Correct!”)

    comp = True

else:

    print(“Wrong!”)

return comp

Now, our program will compare the user input to a random number from one to 10 and tell him if he got it right. Of course, in this version, the number changes every time you make a guess, so it’s not really fair. To make it less, well, random, you can modify the main() function like this:

def main():

num = random.randint(1, 10)

If compare(guess, num) == False:

And the compare() function:    

def compare(x, n):

comp = False

if x == n:

And that makes the game slightly more interesting (not to mention solveable). You can see the finished code in the sidebar.

For fun, why don’t you try adding an array variable that keeps track of the numbers the player has guessed? This is a little trickier, but it can be done with what we’ve learned so far. Another fun (and slightly easier) thing to add is a routine that tells the player if his guess was too high or too low. You can also expand the range of numbers to guess, and add a variable to keep track of the number of guesses.

Next week, we’ll start putting it all together with a variation on the old Rock-Paper-Scissors game.

 

Guess The Number Game

# guessmynumber.py

# a simple number guessing game

import random

def showIntro():

    print(“Program v.1.0”)

    ()print(“Choose a number from 1 to 10: “)

def getInput():

    x = 0

    while x < 1 or x > 10:

        x = int(input(“> “))

    return x

def compare(x, n):

    comp = False

    if x == n:

        print(‘Correct!’)

        comp = True

    else:

        print(‘Wrong!’)

    return comp

def main():

    num = random.randint(1, 10)

    showIntro()

    guess = getInput()

    if compare(guess, num) == False:

        getInput()

    x = input(“Play again (y/n)? “)

    if x[0].upper() == ‘Y’:

        getInput()

main()

 

Comments

comments