PROGRAM 1
PROGRAM 1
nuMbeR
def factorial(n):
if n < 0:
return None # Factorial is not defined for negative numbers
elif n == 0 or n == 1:
return 1
else:
result = 1
for i in range(2, n + 1):
result *= i
return result
# Example usage:
n = int(input("Enter a natural number: "))
result = factorial(n)
if result is not None:
print(f"The factorial of {n} is {result}")
else:
print("Factorial is not defined for negative numbers.")
OutPut :
PROGRAM 2 : find the suM All eleMents Of A
list
numbers = [1, 2, 3, 4, 5]
total_sum = sum(numbers)
print("Sum of all elements:", total_sum)
OutPut :
PROGRAM 3 : find cOde tO cOMPute the nth
fibOnAcci nuMbeR
def fibonacci_iterative(n):
if n <= 0:
return None
elif n == 1:
return 0 # First Fibonacci number is 0
elif n == 2:
return 1
a, b = 0, 1
for _ in range(3, n + 1):
c=a+b
a=b
b=c
return b
n = int(input("Enter the value of n to compute nth Fibonacci number: "))
result = fibonacci_iterative(n)
if result is not None:
print(f"The {n}th Fibonacci number is {result}")
else:
print("Fibonacci sequence is not defined for n <= 0")
OutPut :
PROGRAM 4 : cAlculAte the siMPle inteRest
by usinG functiOn
OutPut :
PROGRAM 5 : PROGRAM tO cAlculAte the
ARithMetic OPeRAtORs by usinG functiOn
def add(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b
def divide(a, b):
if b != 0:
return a / b
else:
return "Division by zero is not allowed"
def arithmetic_operations(a, b):
print("Addition:", add(a, b))
print("Subtraction:", subtract(a, b))
print("Multiplication:", multiply(a, b))
print("Division:", divide(a, b))
# Example usage:
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
arithmetic_operations(num1, num2)
OutPut :
PROGRAM 6 : PROGRAM tO enteR tO nuMbeRs
And swAP theiR vAlues by usinG functiOn
def swap(a, b):
# Swapping values
a, b = b, a
return a, b
# Example usage:
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
print("Before swapping:")
print("num1 =", num1)
print("num2 =", num2)
num1, num2 = swap(num1, num2)
print("After swapping:")
print("num1 =", num1)
print("num2 =", num2)
OutPut :