我想从用户那里得到一个整数输入,然后让for循环遍历该数字,然后调用一个函数多次

2024-09-29 16:27:02 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

for i in timestoprint:
    printHello()

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


Tags: to代码用户程序helloforworldinput
3条回答

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

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

然后您必须使用range内置生成器并使用它

for x in range(timestoprint):
    printHello()

射程是如何工作的

您可以选择在以下任何配置中为range提供参数:

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

range(start, stop)以1的增量生成从开始到停止的计数-1

range(start, stop, step)在步进增量处生成从开始到停止的计数-1

您可能还希望验证用户输入,这可以通过使用永久while循环替换input语句来完成,该循环在用户提供有效输入后中断

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()

相关问题 更多 >

    热门问题