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.
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.
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.
move = str(input("What is your next move? "))
new_position(move)
Comments
Post a Comment