简体   繁体   English

如果“this”是答案,请返回上一行

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

I'm currently learning Python, and was wondering something. 我正在学习Python,并且想知道一些事情。 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? 我可以编写哪些函数会导致“example = input(”Blah blah blah:“)”再次运行? If the user says no to "decision = raw_input("Are you sure this is your answer?: ")". 如果用户拒绝“decision = raw_input(”你确定这是你的答案吗?:“)”。

Sorry if I confused you all. 对不起,如果我困惑你们。 I'm a bit of a newbie to Python, and programming altogether. 我有点像Python的新手,还有编程。

You are looking for a while loop: 你正在寻找一个while循环:

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" . 显然,您可能希望做出比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?). 还要注意你的条件的编辑, if example <= 20 and > 10:语法上没有意义(什么超过10?)。 You probably wanted if example <= 20 and example > 10: , which can be condensed down to 10 < example <= 20 . if example <= 20 and example > 10:您可能想要,可以将其压缩为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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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