首页 > 解决方案 > 玩循环

问题描述

我试图弄清楚如何在 Python 中使用循环,我需要一些帮助。我写的代码只是我在玩的东西。这不是任务或类似的东西。

我想弄清楚的是如何循环程序,以便它要求用户输入一些东西来重新开始问题。这是我到目前为止所拥有的:

def monkeys():
  apes = "This is not a monkey!"
  monkey_yes = "This is a monkey!"
  is_it_a_monkey = apes + monkey_yes
  monkey_question = input("Type in Gorilla, Chimp or Macaque and make sure they're capitalized: ")

  for question in is_it_a_monkey:
    if monkey_question == 'Gorilla' or monkey_question == "Chimp":
      print(apes)
      continue
    else:
      print(monkey_yes)
      break

def main():
  while True:

    if again not in {"y","n"}:
      print("Please enter valid input")
    elif again == "n":
      return "Good bye!"
    elif again == "y":
      return monkeys()

monkeys()

我正在努力main()完成大部分作业,因为这是我的老师在我们的作业中想要的。下面的所有main()内容都是我复制的内容,以查看是否可行,但它只返回以下内容:

Type in Gorilla, Chimp or Macaque and make sure they're capitalized: Gorilla
This is not a monkey!
This is not a monkey!
This is not a monkey!
This is not a monkey!

它比 4 行要长得多,但这不是我想要的。

标签: pythonloops

解决方案


我在这里看到几个问题......

首先,你要连接两个字符串......

    apes = "This is not a monkey!"
    monkey_yes = "This is a monkey!"
    is_it_a_monkey = apes + monkey_yes

当您进入 for 循环时,解释器正在查看该连接字符串的每个字符。这就是为什么你输出 38 行“这不是猴子!” 对于您要执行的操作,您不需要 for 循环。试试这个:

    def monkeys():
        apes = "This is not a monkey!"
        monkey_yes = "This is a monkey!"
        monkey_question = input("Type in Gorilla, Chimp or Macaque and make sure they're capitalized: ")

        if monkey_question == 'Gorilla' or monkey_question == "Chimp":
            print(apes)
        else:
            print(monkey_yes)

我看到的下一个问题是您根本不调用 main 函数。不要在代码底部调用 moneys(),而是调用 main()。

下一个问题是使用“while True:”。如果您打算使用布尔值作为 while 条件,请确保在代码中添加逻辑以更改该条件。将其更改为“False”应该退出您的 main,而不是 return 语句。你的 main() 最好这样开始:

def main():
    keep_going = True
    while keep_going:
        monkeys()

注意你应该首先调用你的 monkeys() 函数,否则程序启动时没有人会知道要输入什么。您还需要代码询问他们是否要继续运行该程序。在你的 monkey() 调用之后,立即执行以下操作:

    monkeys()
    again = input("Would you like to try again? (y/n) ")

下一个问题是您对 return 语句的使用。而不是这样做:

    elif again == "n":
        return "Good bye!"

做这个...

    elif again == "n":
        print("Good bye!")
        keep_going = False

最后,您有“如果再次不在 {"y","n"}:" 中。您必须为“再次”分配一个值,否则您会得到更多错误。如果您使用上面的示例,它应该可以满足您的需求。

继续努力,不要失去希望。你已经接近理解它了。


推荐阅读