首页 > 解决方案 > Python:如何在计数器的开头添加一个字符串

问题描述

我试图只在 for 循环中添加一个字符串一次。我已经添加了代码和输出。并且还添加了我的预期输出。

这是我的代码:

def divisor() :
    limit = int(input(''))

    for number in range(limit) :
        i = 1
        number = int(input(''))
        terminator = number
        count = 0

        while( terminator > 0 ):
            count = count + 1
            terminator = terminator // 10

        if(count <= 100):
            while i <= number :
                if (number % i == 0):
                    print(i, end=' ', flush=True)
                i = i + 1
            print('')
        else:
            break

divisor()

电流输入和输出:

Input: 3 (How many input to take)
Input: 6
Output: 1 2 3 6
Input: 15
Output: 1 3 5 15
Input: 23
Output: 1 23

我想要以下内容:

Input: 3 (How many input to take)
Input: 6
Output: Case 1: 1 2 3 6
Input: 15
Output: Case 2: 1 3 5 15
Input: 23
Output: Case 3: 1 23

标签: python

解决方案


你需要做几件事。

不要更新循环中的变量号。相反,使用一个新变量,以便您可以跟踪迭代次数。

在 if 语句中,添加 print 语句以打印“Case”号

print ('Case',num+1,':', end = '')

完整代码如下,

def divisor() :
    limit = int(input(''))

    for num in range(limit) :
        i = 1
        number = int(input(''))
        terminator = number
        count = 0

        while( terminator > 0 ):
            count = count + 1
            terminator = terminator // 10

        if(count <= 100):
            print ('Case',num+1,':', end = '')
            while i <= number :
                if (number % i == 0):
                    print(i, end=' ', flush=True)
                i = i + 1
            print('')
        else:
            break

divisor()

推荐阅读