Python编程PTA题解——求整数段和

Python编程PTA题解大全——索引

Description:给定两个整数A和B,输出从A到B的所有整数以及这些数的和。
Input:输入仅一行,输入2个整数A和B,其中−100≤A≤B≤100,其间以空格分隔。
Output:首先顺序输出从A到B的所有整数,每5个数字占一行,每个数字占5个字符宽度,向右对齐。最后在一行中按Sum = X的格式输出全部数字的和X。
Sample Input:-3 8
Sample Output

   -3   -2   -1    0    1
    2    3    4    5    6
    7    8
Sum = 30

注意每5个数字一个空格,并且Sum为新一行的输出

a, b = map(int, input().split())
sum = 0
i = 0
while a <= b:
    print('{:5}'.format(a), end='')
    i += 1
    if i % 5 == 0 or a == b: #换行,a=b时,结束循环,所以也要换行
        print()
    sum += a
    a += 1
print("Sum =", sum)

猜你喜欢

转载自blog.csdn.net/qq_43479432/article/details/104989857