Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
108 views
in Technique[技术] by (71.8m points)

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

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?

UPDATE my code so far:

#PLAYER DETAILS
first_name = input("What is your first name? ")
last_name = input("What is your last name? ")
while True:
    middle = input("Do you have a middle name? (y/n) ")
    if middle.upper() not in ("Y", "N"):
        print("whats does {} mean? You were meant to type 'y' or 'n'! Try again.." .format(middle))
    elif middle.upper() == "Y":
        middle_name = input("What is it? ")
        break
    elif middle.upper() == "N":
        middle_name = None
        break
# is_middle_empty = bool(middle_name)
# print(is_middle_empty)
print("So your full name is {} {} {}? ".format(first_name, '' if middle_name is None else middle_name, last_name))
import time
time.sleep(1)
print("Hmmm..")
time.sleep(1)
just_first = str(input("Should I just call you {}? (y/n) ".format(first_name)))
if just_first.upper() == "Y":
   player = first_name
   print("Great, nice to meet you", player)
elif just_first.upper() != "Y":
   name = first_name, "" if middle_name is None else middle_name, last_name
   player = " ".join(name)
   print("Sorry about that, let's stick to {} then." .format(player))
print()

#DIRECTION FUNCTION
def getUserDirection():
    direction = str(input("Which direction do you wish to go? (L/F/R) "))
    direction = direction.upper()
    if direction.upper() not in ("L", "F", "R"):
        print("whats does {} mean? You were meant to type 'y' or 'n'! Try again..".format(direction))
    elif direction.upper() == "L":
        print(L1())
    elif direction.upper() == "F":
        print(F1())
    elif direction.upper() == "R":
        print(R1())
    return

#STORY LINES
def start():
    print("You have arrived at ... To your left (L) is ..., ahead (F) is ... To your right (R) is ...")
def L1():
    print("you go left")
def F1():
    print("You continue forward")
def R1():
    print("You turn right")

#ADVENTURE-1
adventure = input("So do you fancy a quick adventure? (y/n) ")
if adventure.upper() == "Y":
    print("Great then lets set off...")
elif adventure.upper() == "N":
    print("Ah well, I guess we can't all be ubercool adventurers like me, fairwell {}, I hope we meet again some day." .format(player))

#ADVENTURE-2
time.sleep(1)
print(start())
print(getUserDirection())

the output is:

What is your first name? b

What is your last name? m

Do you have a middle name? (y/n) n

So your full name is b m?

Hmmm..

Should I just call you b? (y/n) y

Great, nice to meet you b

So do you fancy a quick adventure? (y/n) y

Great then lets set off...

You have arrived at ... To your left (L) is ..., ahead (F) is ... To your right (R) is ...

None

Which direction do you wish to go? (L/F/R) f

You continue forward

None

None

Process finished with exit code 0

I've highlighted the "None" returns, why are they there?

question from:https://stackoverflow.com/questions/65917805/how-can-i-reuse-a-section-of-code-repeatedly-in-the-same-script-without-retypin

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...