简体   繁体   中英

If “this” is the answer, go back to a previous line

I'm currently learning Python, and was wondering something. I'm writing a little text adventure game, and need help with this: If I write, for example,

example = input("Blah blah blah: ")
if example <= 20 and > 10:
    decision = raw_input("Are you sure this is your answer?: ")

what functions can I write that will cause "example = input("Blah blah blah: ")" to run again? If the user says no to "decision = raw_input("Are you sure this is your answer?: ")".

Sorry if I confused you all. I'm a bit of a newbie to Python, and programming altogether.

You are looking for a while loop:

decision = "no"
while decision.lower() == "no":
    example = input("Blah blah blah: ")
    if 10 < example <= 20:
        decision = raw_input("Are you sure this is your answer?: ")

A loop runs the block of code repeatedly until the condition no longer holds.

We set decision at the start to ensure it is run at least once. Obviously, you may want to do a better check than decision.lower() == "no" .

Also note the edit of your condition, as if example <= 20 and > 10: doesn't make sense syntactically (what is more than 10?). You probably wanted if example <= 20 and example > 10: , which can be condensed down to 10 < example <= 20 .

You could use a function that calls itself until the input is valid:

def test():
   example = input("Blah blah blah: ")
   if example in range(10, 21): # if it is between 10 and 20; second argument is exclusive
      decision = raw_input("Are you sure this is your answer?: ")
      if decision == 'yes' or desicion == 'Yes':
         # code on what to do
      else: test()
   else: # it will keep calling this until the input becomes valid
      print "Invalid input. Try again."
      test()

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