In this simple python program, we have to print a pattern. It is a pattern python program.
To understand this example, you should have knowledge of the following Python programming topics:
This basic python program is to accept a number n and print the series up to the number n and calculate the sum of the pattern. Suppose the number is 5 then we need the output as 1 + 2 + 3 + 4 + 5 = 15.
To apply the logic in python language, using a for loop
from 1 to the number using the range
method and we use the print
statement to print the pattern. In this simple python program, we use the sep parameter, which is called the separator parameter, which is the default is a space. We can use the sep parameter in python 3 or more.
Then we use an if condition in python to check the selected element is less than the number and print the pattern with the 'end=' method and separator parameter. after that, we have to append the elements to a list. We use the sum function to get the sum of the elements in the list.
STEP 1: Accept the number from the user using the input method and convert that to an integer using int()
in python language.
STEP 2: Initialize a list in python.
STEP 3: Use a for loop
from 1 to the number and print the value of i.
STEP 4: Check the I is less than n using if
condition in python and print the sign + and use sep parameter for print space and end= to add to the end.
STEP 5: Append the numbers to a python list using the append
method.
STEP 6: Print the value of sum of the list using sum() function in the python programming language.
n=int(input("Enter a number: "))
a=[]
for i in range(1,n+1):
print(i,sep=" ",end=" ")
if(i<n):
print("+",sep=" ",end=" ")
a.append(i)
print("=",sum(a))
print()
Enter a number: 4 1 + 2 + 3 + 4 = 10