如何将变量设置的范围内的所有数字相加?

时间:2018-09-04 15:18:14

标签: python sum

我必须使用sum函数,但对我不起作用。到目前为止,这是我的代码:

def main():

    print('This program will total all the numbers in a range.')


    num1 = (int(input('Enter a number.')))
    num2 = (int(input('Enter another number (smaller than the first one).')))

    for i in range(num1 - num2 + 1):

        print(i + num2)
    print(sum(range(num1, num2 + 1)))

main()

总和总是有很多错误,我想不出来必须要正确。

1 个答案:

答案 0 :(得分:0)

解决方案

def main():
    print("\nThis program will total all the numbers in a range.")

    num_1 = int(input("Enter a number: "))
    num_2 = int(input("Enter another number: "))
    something = [num_1, num_2]

    max_num = max(something)
    min_num = min(something)
    new_list = list(range(min_num, max_num+1))

    current_sum = min_num
    for i in new_list[1:]:
        print(f"{current_sum} + {i} = ", end='')
        current_sum += i
        print(f"{current_sum}")

    print(f"\nSum of all numbers in range: {current_sum}")

while True:
    main()

如果找到两个min中的maxinput,则可以消除用户以正确顺序输入它们的需要。

对于一般过程,您只需为用户指定的+=中的每个数字range取一个总和。

或者,您也可以使用以下代码来代替使用maxmin

    """Replacing min/max with sorted

    max_num = max(something)
    min_num = min(something)
    new_list = list(range(min_num, max_num+1))

    current_sum = min_num
    """

    something = sorted(something)
    new_list = list(range(something[0], something[1]+1))

    current_sum = new_list[0] 

输出

This program will total all the numbers in a range.
Enter a number: 5
Enter another number: -5
-5 + -4 = -9
-9 + -3 = -12
-12 + -2 = -14
-14 + -1 = -15
-15 + 0 = -15
-15 + 1 = -14
-14 + 2 = -12
-12 + 3 = -9
-9 + 4 = -5
-5 + 5 = 0

Sum of all numbers in range: 0

乐趣

Ran 0到1000000:)

499995500010 + 999996 = 499996500006
499996500006 + 999997 = 499997500003
499997500003 + 999998 = 499998500001
499998500001 + 999999 = 499999500000
499999500000 + 1000000 = 500000500000

Sum of all numbers in range: 500000500000

更新

在循环中整理print语句,使其具有运行时的整体外观,看起来像是您最初寻找的样子。

current_sum0更改为min_num,然后在new_list[1:]开始循环。这不会影响总和,但是会消除显示print的{​​{1}}语句。

使用0 + x = x方法添加,代替使用sortedmax