0% found this document useful (0 votes)
2 views8 pages

Ex 8 Functions

The document outlines a Python program that includes various functions for arithmetic operations, factorial calculation, list summation, and operations on sets, tuples, and dictionaries. It also demonstrates concepts of call by value and call by reference, as well as checking for palindromes. Sample outputs for each function are provided to illustrate their functionality.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views8 pages

Ex 8 Functions

The document outlines a Python program that includes various functions for arithmetic operations, factorial calculation, list summation, and operations on sets, tuples, and dictionaries. It also demonstrates concepts of call by value and call by reference, as well as checking for palindromes. Sample outputs for each function are provided to illustrate their functionality.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

Ex 8) Implement a python program using functions.

Aim:

The aim of this program is to create a function that accepts two numbers and a
mathematical operation (add, subtract, multiply, divide) as inputs, then performs
the corresponding arithmetic operation and returns the result.

Algorithm:

1.​ Define a function that takes three inputs: two numbers (num1, num2) and
an operation type (operation).
2.​ Use conditional checks to determine which operation to perform.
3.​ Perform the corresponding operation and return the result.
4.​ Handle division by zero by displaying an error message when attempting
to divide by zero.

def calculator(num1, num2, operation):


# Check if the operation is addition
if operation == 'add':
return num1 + num2

# Check if the operation is subtraction


elif operation == 'sub':
return num1 - num2

# Check if the operation is multiplication


elif operation == 'multiply':
return num1 * num2

# Check if the operation is division


elif operation == 'divide':
if num2 == 0:
return "Error: Cannot divide by zero"
return num1 / num2

# If the operation is not recognized, return an error message


else:
return "Error: Invalid operation"

print(calculator(10, 5, 'add'))
print(calculator(10, 5, 'sub'))
print(calculator(10, 5, 'multiply'))
print(calculator(10, 5, 'divide'))
print(calculator(10, 0, 'divide')) # Output: Error: Cannot divide by zero
print(calculator(10, 5, 'unknown')) # Output: Error: Invalid operation

Sample Outputs:

15
5
50
2.0
Error: Cannot divide by zero
Error: Invalid operation

# Recursive function to find factorial


def factorial(n):
# Base case: if n is 0 or 1, return 1

if n == 0 or n == 1:
return 1
# Recursive case: n * factorial of (n-1)
else:
return n * factorial(n - 1)

number = 5
result = factorial(number)

print("The factorial of {number} is {result}")


# Function to calculate the sum of a list of numbers
def sum_of_list(numbers):
total = sum(numbers)
return total

# List of numbers
num_list = [1, 2, 3, 4, 5]

# Calling the function and storing the result


result = sum_of_list(num_list)

# Output the result


print("The sum of the list is:", result)

The sum of the list is: 15

1. Using Functions with Sets


A set is an unordered collection of unique elements. You can use functions like
adding, removing, or checking membership in a set.
Example Function for Sets:
# Function to add an element to a set
def add_element_to_set(s, element):
s.add(element)
return s

# Function to remove an element from a set


def remove_element_from_set(s, element):
s.discard(element) # discard doesn't raise an error if element is not found
return s

# Creating a set
my_set = {1, 2, 3}

# Adding an element
my_set = add_element_to_set(my_set, 4)
print("After adding 4:", my_set)

# Removing an element
my_set = remove_element_from_set(my_set, 2)
print("After removing 2:", my_set)
Output:
After adding 4: {1, 2, 3, 4}
After removing 2: {1, 3, 4}
2. Using Functions with Tuples
Tuples are immutable collections. You can't directly modify a tuple like a list,
but you can create a new one from existing tuples. Here's how you might use
functions with tuples.
Example Function for Tuples:
# Function to concatenate two tuples
def concatenate_tuples(tuple1, tuple2):
return tuple1 + tuple2

# Function to get an element from a tuple by index


def get_element_from_tuple(t, index):
if index < len(t):
return t[index]
return "Index out of range"

# Creating tuples
tuple1 = (1, 2, 3)
tuple2 = (4, 5)

# Concatenating tuples
result_tuple = concatenate_tuples(tuple1, tuple2)
print("Concatenated tuple:", result_tuple)

# Accessing an element
element = get_element_from_tuple(tuple1, 1)
print("Element at index 1:", element)
Output:
Concatenated tuple: (1, 2, 3, 4, 5)
Element at index 1: 2
3. Using Functions with Dictionaries
Dictionaries in Python are key-value pairs. You can use functions to add,
remove, or modify dictionary items.
Example Function for Dictionaries:
# Function to add or update a key-value pair in a dictionary
def add_or_update_dict(d, key, value):
d[key] = value
return d

# Function to remove a key from the dictionary


def remove_key_from_dict(d, key):
if key in d:
del d[key]
return d

# Creating a dictionary
my_dict = {'name': 'Alice', 'age': 25}

# Adding or updating a dictionary item


my_dict = add_or_update_dict(my_dict, 'age', 26) # update age
print("After updating age:", my_dict)

# Removing a key
my_dict = remove_key_from_dict(my_dict, 'name')
print("After removing 'name':", my_dict)
Output:
After updating age: {'name': 'Alice', 'age': 26}
After removing 'name': {'age': 26}
# Function to demonstrate "call by value" with immutable objects (integer)

def call_by_value(x):
print("Inside call_by_value function, before change:", x)
x = 100 # Changing the local copy of x, does not affect the original
print("Inside call_by_value function, after change:", x)

# Function to demonstrate "call by reference" with mutable objects (lists)


def call_by_reference(lst):
print("Inside call_by_reference function, before change:", lst)
lst.append(4) # Modifying the original list object
print("Inside call_by_reference function, after change:", lst)

# Main program

# Immutable object example (call by value)


num = 10
print("Before call_by_value:", num)
call_by_value(num) # Passing an integer (immutable)
print("After call_by_value:", num) # The original value of num does not
change

# Mutable object example (call by reference)


my_list = [1, 2, 3]
print("\nBefore call_by_reference:", my_list)
call_by_reference(my_list) # Passing a list (mutable)
print("After call_by_reference:", my_list) # The original list is modified

Output:-

Before call_by_value: 10
Inside call_by_value function, before change: 10
Inside call_by_value function, after change: 100
After call_by_value: 10

Before call_by_reference: [1, 2, 3]


Inside call_by_reference function, before change: [1, 2, 3]
Inside call_by_reference function, after change: [1, 2, 3, 4]
After call_by_reference: [1, 2, 3, 4]

def modify_number(x):
x = 10 # Local assignment, does not affect the original variable

# main program
a=5
modify_number(a)
print(a) # Output: 5, original value of 'a' is unchanged
def modify_list(lst):
lst.append(4) # Modifies the original list

my_list = [1, 2, 3]
modify_list(my_list)
print(my_list) # Output: [1, 2, 3, 4], the original list is modified

Output:-
5
[1,2,3,4]
Palindrome or not:-

def isPalindrome(string):
if (string == string[::-1]) :
return "The string is a palindrome."
else:
return "The string is not a palindrome."

#Enter input string


string = input ("Enter string: ")

print(isPalindrome(string))

You might also like