python assignment4
python assignment4
#1)normal function
def add (a, b):
addition = a + b
return addition
addition = add(a, b)
print(f"The sum of {a} and {b} is: {addition}")
#2)lambda function
add_numbers = lambda x, y: x + y
OUTPUT
Enter the first number: 2
Enter the second number: 4
The sum of 2 and 4 is: 6
Enter the first number: 2
Enter the second number: 3
The sum of 2 and 3 is 5
2.SUBTRACT
#wap in python to subtract 2 numbers
return subtract
subtract = subtract(a, b)
subtract_numbers = lambda x, y: x - y
OUTPUT-
Enter the first number: 2
Enter the second number: 3
The difference of 2 and 3 is: -1
Enter the first number: 4
Enter the second number: 2
The result of 4 - 2 is 2
3.FACTORIAL
#wap in python to implement factorial using
#1)normal function
#2)lambda function
#1)
def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)
OUTPUT-
Enter a number: 3
The factorial of 3 is 6.
Enter a number: 5
The factorial of 5 is 120.
4.PRIME
#1)
def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
number = int(input("Enter a number "))
if is_prime(number):
print(f"{number} is a prime number.")
else:
print(f"{number} is not a prime number.")
#2
is_prime_lambda = lambda n: n > 1 and all(n % i != 0
for i in range(2, int(n**0.5) + 1))
def is_prime(num):
if num <= 1:
return False
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
return False
return True
OUTPUT-
Enter a number 3
3 is a prime number.
Enter a number: 775
775 is not a prime number.
Enter the start of the range: 23
Enter the end of the range: 32
Prime numbers between 23 and 32 are:
23 29 31
5.FIBONACCI
OUTPUT-
import math
import math
OUTPUT-
Enter the value of x 3
Enter the number of terms 4
The value of cos(3.0) using the cosine series is: -1.1375
7.PALINDROME
#1)
def is_palindrome(s):
s = s.replace(" ", "").lower()
return s == s[::-1]
if is_palindrome(user_input):
print(f"'{user_input}'is a palindrome")
else:
print(f"'{user_input}'is not a palindrome")
#2)
is_palindrome_lambda = lambda word: word == word[::-1]
8.ARMSTRONG NUMBER
if is_armstrong(num):
print(f"{num} is an Armstrong number!")
else:
print(f"{num} is not an Armstrong number!")
OUTPUT-
Enter a number253
253 is not an Armstrong number!
9.CALCULATOR
print("Select operation:")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
choice = input("Enter choice(1/2/3/4): ")
if choice == '1':
print(f"{num1} + {num2} = {add(num1, num2)}")
elif choice == '2':
print(f"{num1} - {num2} = {subtract(num1, num2)}")
elif choice == '3':
print(f"{num1} * {num2} = {multiply(num1, num2)}")
elif choice == '4':
print(f"{num1} / {num2} = {divide(num1, num2)}")
else:
print("Invalid input!")
OUTPUT-
Select operation:
1. Add
2. Subtract
3. Multiply
4. Divide
Enter choice(1/2/3/4): 1
Enter first number: 3
Enter second number: 2
3.0 + 2.0 = 5.0