简体   繁体   中英

How do I get python to go back to a line of code?

I'm relatively new to python and coding in general but I'm currently trying to make a modular game where you input what you want to do based on options given to you. I've used a while loop in the past that covers a question with multiple choices:

    while(cont==False):
Intro2=input("Continue; New Game; Settings; Save Files; ")
if(cont==False):

if(Intro2=="Continue"):
  print("This option is currently not available.")
elif(Intro2=="Settings"):
  print("This option is currently not available.")
elif(Intro2=="Save Files"):
  print("This option is currently not available.")
elif(Intro2=="New Game"):
  N_G=input("New game selected. Continuing will erase all previous save data. Are you sure you want to continue? 'yes' 'no': ")
else:
  print("Your response is invalid. Make sure you are using the exact wording, including grammar and spelling.")
  
if(N_G=="yes"):
  print("redirecting")
  time.sleep(1)
  print(".")
  time.sleep(1)
  print(".")
  time.sleep(1)
  print(".")
  cont=True
elif(N_G=="no"):
  print("redirecting")
  cont=False
else:
  print("Your response is invalid. Make sure you are using the exact wording, including grammar and spelling.")
  cont=False
  break 

But I don't want to have to do this every time there's an input and I'm unsure if there is an easier way to do this. The specific area of code that I'm trying to implement this is:

    q1=input("you lost a bet to the local wizard and now you have to hold your end of the bargain. You lay in your room, staring at the ceiling, knowing the criticism you'll get as soon as you walk out your door; 'get up': ")
if(q1=="get up"):
  print("you get up out of your bed and look around. Your room is still basic as ever, only 
consisting of 5 things: your bed, dresser, desk, window, and door.")
else:
  print("Your response is invalid. Make sure you are using the exact wording, including 
grammar and spelling.")

Enter from left stage: python functions. You can learn all about them here . In short, it allows you to essentially reuse blocks of code wherever you want to keep your code dynamic and removing the need of duplicate copy/pasted code everywhere

Here's an example of what you could do:

 def your_function_here():
   q1=input("you lost a bet to the local wizard and now you have to hold your end of the bargain. You lay in your room, staring at the ceiling, knowing the criticism you'll get as soon as you walk out your door; 'get up': ")
  if(q1=="get up"):
    print("you get up out of your bed and look around. Your room is still basic as ever, only 
consisting of 5 things: your bed, dresser, desk, window, and door.")
  else:
    print("Your response is invalid. Make sure you are using the exact wording, including 
grammar and spelling.")

 your_function_here()

Anywhere in the code that you call your_function_here() it will run that block of code

In Python, indentation is really important. This is not the case in other languages like Java and C. But to state that a line takes place inside a while loop, indent said lines by two spaces (or 4, depending on your settings in Python.

In your first line, your while loop is indented further than the following statements, which should lead to an error. I would put everything indented inside the loop.

while (cont == False):
    input2 = input("Continue; New Game; Settings; Save Files")
    if input2 == ...:
        ...
    elif input2 == ...:
        ...

print("This line will be outside of the loop")

Once you've done that, try to split your large block of code into smaller functions like Halmon said.

Keep up the good work!

Like Halmon said, this is a good opportunity to learn about functions. When you find yourself doing roughly the same thing (even if it's not exactly the same thing) over and over, it's a good clue that you should define a function to do that thing.

The thing I see your code doing repeatedly is "prompt for one of a set of options, and re-prompt if the input is invalid". So let's make that specific thing a function:

def prompt_with_options(option_list: list) -> str:
    """Prompt for one of the options in the list until a valid option is chosen."""
    while True:
        option = input("; ".join(option_list))
        if option in option_list:
            return option
        print("Your response is invalid. Make sure you are using the exact wording.")

Now the rest of your code can look like this:

while True:
    option = prompt_with_options(["Continue", "New Game", "Settings", "Save Files"])
    if option is not "New Game":
        print("This option is currently not available.")
        continue

    # New Game
    print("New game selected. Continuing will erase all previous save data. Are you sure you want to continue?")
    option = prompt_with_options("yes", "no")

    print("redirecting")
    if option == "no":
        break

    # yes
    for _ in range(3):
        time.sleep(1)
        print(".")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM