Python:如何在coun的开头添加字符串

2024-04-26 18:59:38 发布

您现在位置: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

Tags: numberforinputoutputifcounthowdivisor
2条回答

你需要做几件事。你知道吗

不要更新循环中的变量号。相反,使用一个新变量,这样就可以跟踪迭代次数。你知道吗

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

您可以使用format或f-string。例如:

i = 3

info = 'case {}'.format(i)
print(info)
>>>'case 3'
# or

info = f'case {i}'
print(info)
>>>'case 3'

相关问题 更多 >