【问题标题】:How can I repeat a few lines of code based on an input [duplicate]如何根据输入重复几行代码[重复]
【发布时间】:2021-08-16 05:13:19
【问题描述】:

我想知道是否有某种可以导入的命令或函数允许我根据输入的值多次运行命令。这可能没有任何意义,但希望它会从这里↓

num_of_rounds = input(int("type the amount of rounds you want to play"))
for num_of_rounds:
  print("test")

这对我不起作用,我不知道如何使它起作用。

【问题讨论】:

  • 同样可以工作,但不是输入命令,而是一个函数:def rounds_func(number): for number: print("test")
  • 你的意思是int(input(...)),而不是input(int(...))

标签: python


【解决方案1】:

使用rangedummy variable _

num_of_rounds = int(input("type the amount of rounds you want to play"))
for _ in range(num_of_rounds):
    print("test")

【讨论】:

  • @Jared Python 中的de facto standard 是使用_ 作为任何未使用变量的名称。
  • 官方python文档实际上显示x被用于for循环wiki.python.org/moin/ForLoop所以你的错误_不是标准,我更相信python.org文档而不是a随机 SO 问题。
  • @Jared 那是维基,不是官方文档。但这里有一个比“一个随机的 SO 问题”更权威的来源:Pylint docs - Variables checker Options - "dummy-variables-rgx: 与虚拟变量名称匹配的正则表达式(即预计不会被使用)。默认值:_+$..."
  • @wjandrea 网站的域名是wiki.python.org python.org 是python的官方网站,你给我的链接pycqa.org是一些随机网站,不是官方来源。提供可靠来源的实际证据,否则我不会认真对待您。
  • @Jared 我刚刚查看了您发送的初始链接,实际上,所有这些循环都使用 x... 它没有被用作虚拟变量。不管怎样,IDK你为什么不相信我。 wiki 是用户可编辑的,它在主页上这样说。 Pylint 是成千上万的开发人员使用的工具。
【解决方案2】:

也许这样的事情会起作用:

def rounds():
    num_of_rounds = int(input("type the amount of rounds you want to play"))
    for i in range(num_of_rounds):
        print("test")
rounds()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-05
    • 2013-01-11
    • 2021-01-16
    • 1970-01-01
    • 1970-01-01
    • 2013-07-25
    相关资源
    最近更新 更多