0
How to code this in python? Find and Print the SUM of 10 consecutive Integers
A. Input an Integers (n) B. Calculate the sum of 10 consecutive integers basing on (n) C. Output sum.
3 Antworten
+ 5
Aditya Dixit it is a bad idea to name a variable "sum" because this is also a built-in function and actually it would be useful here.
you can also come up with a math solution, a simple formula for this problem that doesn't involve loops, just multiplication and addition.
n + (n+1) + (n+2) + ... + (n+9)
10 * n + (0+1+2+...+9)
10 * n + 45
5 * (2 * n + 9)
This only depends on the starting number, but you can further generalize the formula by how many numbers are added.
+ 2
n = int(input("Enter an integer: "))
sum = 0
for i in range(n, n+10):
sum += i
print("The sum of 10 consecutive integers starting from", n, "is", sum)
+ 1
Well, sum is not as function here. By saying that sum in above code can disturb the predefined function sum, you depth about programming & logical understanding is clear.
Thanks for your suggestion.