CBSE Class 12 Computer Science Question 101 of 105

Python Revision Tour — Question 7

Back to all questions
7
Question

Question 7

Write a program that reads an integer N from the keyboard computes and displays the sum of the numbers from N to (2 * N) if N is nonnegative. If N is a negative number, then it's the sum of the numbers from (2 * N) to N. The starting and ending points are included in the sum.

Solution
n = int(input("Enter N: "))
sum = 0
if n < 0:
    for i in range(2 * n, n + 1):
        sum += i
else:
    for i in range(n, 2 * n + 1):
        sum += i

print("Sum =", sum)
Output
Enter N: 5
Sum = 45

Enter N: -5
Sum = -45
Answer