3. Scientific problems using Conditionals and Iterative loops. (Number series, Number Patterns, pyramid pattern)
3. Scientific problems using Conditionals and Iterative loops. (Number series, Number Patterns, pyramid pattern)
NUMBER SERIES
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()
# Program to display the Fibonacci sequence up to n-th term
nterms = int(input("How many terms? "))
# first two terms
n1, n2 = 0, 1
count = 0
# check if the number of terms is valid
if nterms <= 0:
print("Please enter a positive integer")
# if there is only one term, return n1
elif nterms == 1:
print("Fibonacci sequence upto",nterms,":")
print(n1)
# generate fibonacci sequence
else:
print("Fibonacci sequence:")
while count < nterms:
print(n1)
nth = n1 + n2
# update values
n1 = n2
n2 = nth
count += 1
Output
How many terms? 7
Fibonacci sequence:
0
1
1
2
3
5
8
Python Program to compute sum of following series: 12+22+32.....102
sum
=0
fori
inrange
(12,103,
10)
:
print(
i
,end
="")
if(
i
<102):
print("+",
end
="")
sum
=sum
+i
print("\nSum is : ",sum
)
Output :
12+22+32+42+52+62+72+82+92+102
Sum is : 570
PYRAMID PATTERN
# Example of print simple pyramid pattern
n = int(input("Enter the number of rows"))
# outer loop to handle number of rows
for i in range(0, n):
# inner loop to handle number of columns
# values is changing according to outer loop
for j in range(0, i + 1):
# printing stars
print("* ", end="")
# ending line after each row
print()
Output:
*
* *
* * *
* * * *
* * * * *
# Printing Triangle Pyramid
Code -
n = int(input("Enter the number of rows: "))
m = (2 * n) - 2
for i in range(0, n):
for j in range(0, m):
print(end=" ")
m = m - 1 # decrementing m after each loop
for j in range(0, i + 1):
# printing full Triangle pyramid using stars
print("* ", end=' ')
print(" ")
Output:
Enter the number of rows: 10
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * * * *
* * * * * * * * *
* * * * * * * * * *
Pattern - 1: Number Pattern
Code -
rows = int(input("Enter the number of rows: "))
# Outer loop will print number of rows
for i in range(rows+1):
# Inner loop will print the value of i after each iteration
for j in range(i):
print(i, end=" ") # print number
# line after each row to display pattern correctly
print(" ")
Output:
Enter the number of rows: 5
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
NUMBER PATTERN 2 : Multiplication Number in Column
rows = int(input("Enter the number of rows: "))
for i in range(1, rows):
for j in range(1, i + 1):
# It prints multiplication or row and column
print(i * j, end=' ')
print()
Output:
Enter the number of rows: 8
1
2 4
3 6 9
4 8 12 16
5 10 15 20 25
6 12 18 24 30 36
7 14 21 28 35 42 49
Comments
Post a Comment