【问题标题】:Repitition of a same block of code in Python在 Python 中重复相同的代码块
【发布时间】:2021-11-09 22:16:19
【问题描述】:

一周前我才开始学习 Python。我决定创建一个带有笑话的应用程序。我的应用程序要求一些笑话来显示它。我应该写什么来让我的应用一次又一次地问一些笑话? image of code

*a1-a10 - 带有笑话的变量

【问题讨论】:

    标签: python-3.x windows


    【解决方案1】:

    要重复一段代码,可以使用 while 循环,只要条件正确,它就会重复一段代码。

    while(true):
        num = int(input("text here"))
        if num == 1:
           doSomething()
        else:
           doSomethingElse()
    

    只要条件为真,(在这种情况下总是如此)程序将重复该代码块。

    上面的循环是一个无限循环,因为条件总是为真,所以程序需要一种退出方式,也许是添加退出条件。

    Python docs

    【讨论】:

      【解决方案2】:

      循环可能是最基本的编程概念之一,因此我建议先深入了解这些概念。

      如果您想要求用户输入特定次数的数字,您可以使用for loop

      for i in range(10):
          #Perform action here
      

      如果您想反复询问用户直到他们自己结束,while loop 是更好的选择。

      userInput = ""
      while(userInput != "done"):
          userInput = input("Enter the number of the joke: ")
          #Get user input and do what you want with it
          #This loop will terminate when the user inputs 'done'
      

      【讨论】:

        猜你喜欢
        • 2019-02-26
        • 2020-12-31
        • 2017-02-21
        • 2015-07-19
        • 2022-07-07
        • 2019-08-03
        • 2023-03-27
        • 2010-11-24
        • 2012-06-29
        相关资源
        最近更新 更多