Q1) Write a Python program to calculate the sum of series : 1^2+2^2 + 3^2 +.........+ n^2
Q2)Display Fibonacci series for 0 1 1 2 3 5 ...... n (in Python programming language)
Q3)Write a python program to find the factorial of a given number.
Answers
Explanation:
########### 1 ###############
# Python Program to calculate Sum of Series 1²+2²+3²+….+n²
number = int(input("Please Enter any Positive Number : "))
total = 0
total = (number * (number + 1) * (2 * number + 1)) / 6
for i in range(1, number + 1):
if(i != number):
print("%d^2 + " %i, end = ' ')
else:
print("{0}^2 = {1}".format(i, total))
########### 2 ###########
# 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")
elif nterms == 1:
print("Fibonacci sequence upto",nterms,":")
print(n1)
else:
print("Fibonacci sequence:")
while count < nterms:
print(n1)
nth = n1 + n2
# update values
n1 = n2
n2 = nth
count += 1
############# 3 ##############
# Python 3 program to find
# factorial of given number
def factorial(n):
if n < 0:
return 0
elif n == 0 or n == 1:
return 1
else:
fact = 1
while(n > 1):
fact *= n
n -= 1
return fact
# Driver Code
num = 5;
print("Factorial of",num,"is",
factorial(num))