Here this example introduces how to read a number N and output the result of “1+2+ … + n = “. In Python, it can be processed through loop and judgment statements.
Source Code
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
n = int(input("Enter a number: "))
a = range(1, n + 1)
for i in a:
print(i, sep=" ", end=" ")
if i < n:
print("+", sep=" ", end=" ")
print("=", sum(a))
Output:
Enter a number: 10
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55