繁体   English   中英

我想从用户那里获得 integer 输入,然后让 for 循环遍历该数字,然后多次调用 function

[英]I want to get an integer input from a user and then make the for loop iterate through that number, and then call a function that many times

所以我已经为此苦苦挣扎了一段时间。 我希望我的程序询问用户“打印 Hello world 多少次?” 然后从中获取数字并在for循环中使用它来调用function。 这是我的 Python 代码:

timestoprint = input("How many times to print hello?")

for i in timestoprint:
    printHello()

任何帮助将不胜感激。 谢谢!

首先,您需要将输入转换为 integer:

timestoprint = int(input("How many times to print hello?"))

然后你必须使用range构建生成器并使用它

for x in range(timestoprint):
    printHello()

范围如何工作?

您可以选择提供 arguments 以适应以下任何配置:

range(number)以 1 为增量生成从 0 到 number-1 的计数

range(start, stop)以 1 为增量生成从 start 到 stop-1 的计数

range(start, stop, step)以步长为单位生成从 start 到 stop-1 的计数

您可能还想验证用户输入,这可以通过将输入语句替换为永远的 while 循环来完成,一旦用户提供有效输入,该循环就会中断

while True:
    timestoprint = input("How many times to print hello?")
    if timestoprint.isnumeric():  # Check if input is a number
        timestoprint = int(timestoprint)  # Convert it to number
        break  # Break the while loop
    else:  # if it is not a number
        print("The input is not a number.")

你写了

for i in timestoprint:
    printHello()

代替

for i in range(timestoprint):
    printHello()

您还忘记将timestopprint转换为int

这对我有用:

timestoprint = int(input("How many times to print hello?"))

for i in range(timestoprint):
    print("hello")

首先, input返回一个字符串,而您需要一个int 您需要进行转换。 其次, for 循环只接受iterables ,而不是整数,所以你想使用range来获取要迭代的值。

timestoprint = int(input("How many times to print hello?"))

for i in range(timestoprint):
    printHello()

实际上,您必须遍历 Python 中的timestoprint range的 integer 部分:

timestoprint = input("How many times to print hello?")

for i in range(int(timestoprint)):
    printHello()

暂无
暂无

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

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