How do functions in Python work?

What you will learn in this post:  Python functions; if, elif, and else statements in Python; while loops in Python; global variables in Python; moving positions in Python

Functions in Python are used to perform repetitive tasks or computations.  From the main program, you send values to a function.  The function then uses these values to perform a task or computation.  The function can return a value if needed.

In the example below, a function has been developed to track a location on a grid based on whether the user moves left, right, up, or down.  The grid used in this program is shown below.  


In this program, the user begins at position (0,0).  To do this, we initialize variables xval and yval to zero.  We can also add a print statement to explain the starting position and to explain what the Python program expects from the user.

The code for the initialization and the print statement is shown below.  We also initialize a variable, out, to zero.  The purpose of this is shown later.  If your print statement exceeds one line, use a backslash, \, at the end of a line in the print statement to indicate a continuation of the line in the program.

print("This game begins at position (0,0).  You can move left, right, up, or down until you exit\
the grid.  You move by typing in left, right, up, or down.")

xval = 0
yval = 0
out = 0

Functions in Python are noted by using def.  In the code below, our function (named new_position) accepts the move that has been input by the user from the main portion of the program (that code is shown later).  It then changes the value of xval or yval based on the direction of the move indicated by the user.  For example, if the move is "up", yval is increased by one,  If the move is "left", xval is decreased by one.  If a valid response is not input, the program will notify the user.  This is accomplished through the use of if, elif, and else statements in Python.  Notice also that we indicate that xval, yval, and out are global variables.  If you are changing the value of a variable within a function, that variable needs to be defined as being global.  Recall that xval, yval, and out were initialized outside of the function and are being changed within the function.  

After updating the value for xval or yval depending on the direction of the move, an additional if and else Python statement is used to determine if the user is still on the grid or has exited the grid.  That if and else statement is the final portion of the function named new_position.  Also note that the value of the variable, out, is set to 1 if we have exited the grid. 

Note where the two equals signs are used in the Python if statements.   

def new_position(move):
    global xval
    global yval
    global out
    if move == "left":
        xval = xval - 1
    elif move == "right":
        xval = xval + 1
    elif move == "up":
        yval = yval + 1
    elif move == "down":
        yval = yval - 1
    else:
        print("You did not enter a valid response")
    if(xval<0) or (xval>3) or (yval<0) or (yval>3):
        print("You have exited the grid.")
        out=1
    else:
        print("Your new position is ",xval,",",yval) 

The main portion of our Python program contains only three lines of code.  The code consists of a while loop which prompts the user for the direction of the move as long as the variable, out, is set to zero.  After receiving the direction of the move (which we defined as a string since text is being input), we then call the function, new_position, and send the direction of the move to that function.  

Note that if we have exited the grid based on a previous move, the value of the variable, out, will be set to one and the while loop will not be executed.  

while out==0:        
    move = str(input("What is your next move? "))
    new_position(move)

A sample simulation of this program gives the following:

This game begins at position (0,0).  You can move left, right, up, or down until you exit the grid.  You move by typing in left, right, up, or down.
What is your next move? right
Your new position is  1 , 0
What is your next move? down
You have exited the grid.









Comments