n = int(input("Enter a number: "))
series = " + ".join(str(i) for i in range(1, n + 1))
total_sum = sum(range(1, n + 1))
print(f"{series} = {total_sum}")
#source code --> clcoding.com
Code Explanation:
Input
n = int(input("Enter a number: "))
Prompts the user to enter an integer.
Converts the input to an integer using int() and stores it in the variable n.
Generate the Series
series = " + ".join(str(i) for i in range(1, n + 1))
Generates a string representation of the series
1+2+3+…+n:
range(1, n + 1): Creates a range of integers from 1 to 𝑛
n (inclusive).
str(i) for i in range(1, n + 1):
Converts each number in the range to a string.
" + ".join(...): Joins these strings with " + " as the separator, forming the series.
For example:
If
n=5, the result is: "1 + 2 + 3 + 4 + 5".
Calculate the Total Sum
total_sum = sum(range(1, n + 1))
Computes the sum of all integers from 1 to n:
range(1, n + 1): Creates a range of integers from 1 to 𝑛
n (inclusive).
sum(...):
Adds all the numbers in the range.
For example:
If 𝑛=5, the result is: 1+2+3+4+5=15
Output the Result
print(f"{series} = {total_sum}")
Uses an f-string to format the output.
Prints the series and the total sum in the format:
series=total_sum
For example:
If 𝑛=5, the output is:
1 + 2 + 3 + 4 + 5 = 15
0 Comments:
Post a Comment