如何编写输出如下的 Python 程序: 限制:18 连续和:1 + 2 + 3 + 4 + 5 + 6 = 21

How to write Python program with output like this: Limit: 18 The consecutive sum: 1 + 2 + 3 + 4 + 5 + 6 = 21

目前我的代码如下所示:

    limit = int(input("Limit:"))
    number = 1
    sum = 1

    while sum < limit:
        number = number + 1
        sum = sum + number

    print(f"The consecutive sum:{sum}")

在单独的列表中添加您正在使用的号码。然后使用 str.join() 将这些数字与 ' + '.

连接起来
limit = int(input("Limit:"))
number = 1
total = number
numbers = [str(number)]

while total < limit:
    number = number + 1
    total = total + number
    numbers.append(str(number)) # Need to convert to string here because str.join() wants a list of strings

print(f"The consecutive sum: {' + '.join(numbers)} = {total}")

打印所需的输出:

The consecutive sum: 1 + 2 + 3 + 4 + 5 + 6 = 21
limit = int(input("Limit:"))
number = 1
sum = 1
print("The consecutive sum: 1", end = " ")
while sum < limit:
    number += 1
    sum +=  number
    print(f'+ {number}', end = " ")

print(f'= {sum}')

输出将是:

Limit:18 
The consecutive sum: 1 + 2 + 3 + 4 + 5 + 6 = 21