Saturday, 7 December 2024

Day 28 : Python program to print the natural numbers summation pattern

 


def print_summation_pattern(n):

    for i in range(1, n + 1):

        print("+".join([str(x) for x in range(1, i + 1)]))

n = int(input("Enter a number: "))

print_summation_pattern(n)

Code Explanation:

1. Function Definition

def print_summation_pattern(n):
    for i in range(1, n + 1):
        print("+".join([str(x) for x in range(1, i + 1)]))

Purpose:
The function generates and prints a pattern where each line contains a sequence of numbers from 1 to the current line number, separated by +.

Logic Breakdown:
Outer Loop (for i in range(1, n + 1)):
Iterates from 1 to n (inclusive).
Each iteration corresponds to one line in the pattern.
The variable i determines how many numbers will appear on the current line.

Generate Numbers for the Current Line:
[str(x) for x in range(1, i + 1)]
A list comprehension is used to create a list of numbers from 1 to i.
range(1, i + 1) generates numbers from 1 to i (inclusive).
Each number is converted to a string using str(x) for proper formatting with +.

Join Numbers with +:
"+".join([...])
The join method combines the strings in the list, using + as the separator.
Print the Result:
The formatted string is printed, displaying the numbers separated by +.

2. User Input and Function Call

n = int(input("Enter a number: "))
The user is prompted to enter an integer (n).
int(input(...)) converts the input string into an integer.

print_summation_pattern(n)
The print_summation_pattern function is called with n as the argument to generate and print the pattern.

#source code --> clcoding.com 

0 Comments:

Post a Comment

Popular Posts

Categories

100 Python Programs for Beginner (28) AI (33) Android (24) AngularJS (1) Assembly Language (2) aws (17) Azure (7) BI (10) book (4) Books (173) C (77) C# (12) C++ (82) Course (67) Coursera (223) Cybersecurity (24) data management (11) Data Science (127) Data Strucures (8) Deep Learning (20) Django (14) Downloads (3) edx (2) Engineering (14) Excel (13) Factorial (1) Finance (6) flask (3) flutter (1) FPL (17) Google (34) Hadoop (3) HTML&CSS (47) IBM (25) IoT (1) IS (25) Java (93) Leet Code (4) Machine Learning (59) Meta (22) MICHIGAN (5) microsoft (4) Nvidia (1) Pandas (4) PHP (20) Projects (29) Python (923) Python Coding Challenge (318) Python Quiz (4) Questions (2) R (70) React (6) Scripting (1) security (3) Selenium Webdriver (2) Software (17) SQL (42) UX Research (1) web application (8)

Followers

Person climbing a staircase. Learn Data Science from Scratch: online program with 21 courses