How can I reuse a section of code repeatedly in the same script, without retyping it every time?

Question:

I have decided to make a textbased adventure game (Think BBC Micro!) to help me learn.

So far it is going pretty well, but I wondered if there was a way to reuse the code that asks the user for the next action without retyping the whole thing. I assume there is a way to create a function and then simply recall that function each time it is required, but I cannot work out how to do it.

The most common scenario I would use this is when asking the user which direction they want to travel (L, F, R) at the moment I’m doing it like this:

print("You have arrived at... To your left (L) is ... , ahead (F) is ... To your right (R) is...")
direction = str(input("Which direction do you wish to go? (L/F/R) "))
if direction.upper() not in ("L", "F", "R"):
    print("whats does {} mean? You were meant to type 'L', 'F' or 'R'! Try again..".format(direction))
elif direction.upper() == "L":
    print("You turn left and find...")
elif direction.upper() == "F":
    print("You go forward and find...")
elif direction.upper() == "R":
    print("You turn right and find...")

How could I reuse this code for each new direction without retyping (copy/pasting) it at every turn?
Also is there a way to fill the print(") under each direction by directing the code to a new variable?

I’m thinking along the lines of placing it in a loop so that each time the if statement runs it increments by 1, then I could list all the responses to each action and simply assign them a name of L1, L2, L3…F1, F2, F3…R1, R2, R3. This way the text can be created in a block rather than included in every if/elif statement, it could then be placed inside a print() command by taking the direction (L, F, R) value and the loop count (1, 2, 3) and combining them to give the name of the variable (F3).

The text appears, then runs the loop again asking for the next direction.

Would this be an appropriate way of doing it and if so how do I assign the if/elif statement to a recallable function?

Asked By: Benn Moffat

||

Answers:

Use def statement to define a function. For example:

def direction_func():
    direction = str(input("Which direction do you wish to go? (L/F/R) "))
    if direction.upper() not in ("L", "F", "R"):
        print("whats does {} mean? You were meant to type 'L', 'F' or 'R'! Try again..".format(direction))
    elif direction.upper() == "L":
        print("You turn left and find...")
    elif direction.upper() == "F":
        print("You go forward and find...")
    elif direction.upper() == "R":
        print("You turn right and find...")
    return direction

And then call this function in every part of code you need it:

direction = direction_func()
print(direction)
Answered By: Punker

you can use a function in that case:

def getUserDirection():
    print("You have arrived at... To your left (L) is ... , ahead (F) is ... To your right (R) is...")
    direction = str(input("Which direction do you wish to go? (L/F/R) "))
    direction = direction.upper()
    if direction not in ("L", "F", "R"):
        print("whats does {} mean? You were meant to type 'L', 'F' or 'R'! Try again..".format(direction))
    elif direction == "L":
        print("You turn left and find...")
    elif direction == "F":
        print("You go forward and find...")
    elif direction == "R":
        print("You turn right and find...")
    return direction

then you can call it anywhere like :

userDirection = getUserDirection()

Now you get your user’s current direction in the variable userDirection

if you want to get the correct result only and ask for correct input each time when user enter some wrong values then you can call the function again recursively
:

def getUserDirection():
    print("You have arrived at... To your left (L) is ... , ahead (F) is ... To your right (R) is...")
    direction = str(input("Which direction do you wish to go? (L/F/R) "))
    direction = direction.upper()
    if direction not in ("L", "F", "R"):
        print("whats does {} mean? You were meant to type 'L', 'F' or 'R'! Try again..".format(direction))
        direction = getUserDirection()
    elif direction == "L":
        print("You turn left and find...")
    elif direction == "F":
        print("You go forward and find...")
    elif direction == "R":
        print("You turn right and find...")
    return direction
Answered By: SM Abu Taher Asif
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.