Passing Mutable and Immutable Objects to Functions
Using String Objects as Parameters and Arguments in Python
-
Strings in Python are sequences of character data represented as Unicode characters.
-
String literals can be enclosed in:
-
Single quotes
' '
-
Double quotes
" "
-
Triple quotes
''' '''
or""" """
(for multi-line strings)
-
-
The
str
data type in Python is an example of an immutable data type.
This means that once a string is created, it cannot be changed (modified in place). - IMMUTABILITY
EXAMPLE
str = "Python"
str[3] = "H" # Attempt to change the 4th character
OUTPUT: TypeError: 'str' object does not support item assignment
- IMMUTABILITY
EXAMPLE
1.
Write a Python program that defines a function to display a person's full name. Follow the requirements below:
- The
function should have two parameters to accept the first name
and last name.
- Concatenate
the first name and last name using the + operator with a space in
between.
- Display
the full name from within the function.
The program should also take input from the user for the
first name and last name, and call the function to display the full name.
Sol:
# Function definition with two parameters
def display_full_name(first_name, last_name):
full_name = first_name + "
" + last_name
print("Full Name:",
full_name)
# Main program
# Accept input from user
fname = input("Enter first name: ")
lname = input("Enter last name: ")
# Call the function with user input
display_full_name(fname, lname)
2. Write a program to define a UDF which takes a string as
parameter. The function should count and return the number of words which are
starting with a consonant
Sol:
def countwords(str):
cnt=0
for ch in str.split():
if ch[0] >= 'a' and ch[0] <= 'z' or ch[0]>='A' and ch[0]<='Z' :
if ch[0] not in "AEIOUaeiou":
cnt+= 1
return cnt
str1 = input("Enter string")
print(countwords(str1))
3. #Write a program to define a UDF which takes a string as parameter .
#The function should return the count of all the palindrome words in it.
def countpalin(str):
count=0
for ch in str.split():
if ch== ch[::-1]:
count+=1
return count
str=input("Enter a string")
print(countpalin(str))
4.Write a program to Input a string and write equivalent codes in a user defined function for functions:
a. len () b. tolower() c.isalnum()
Sol:
def tolower(str):
newstr=" "
for ch in str:
if ch>="A" and ch<= "Z":
newstr+=chr(ord(ch) + 32)
else:
newstr+=ch
print(newstr)
s="ABC"
tolower(s)
List object as parameter
Lists are sequence data type where each element can be
accessed using index
•List is heterogeneous in nature i.e the elements of a list
are of mixed data type.
•List is Mutable which implies the changes can take in place
in each index .
Example –lobj= [“Computer”,70,30,”083”]
lobj[1] = 100
•List elements can be accessed either moving left to right
(using 0 to positive index) or right to left (using negative index from -1).
Example –print(lobj[1], lobj[-2]
Output –Computer 30
•An empty list can be created assigning the list object to
[] or by using list()
1. Write a program to define a UDF which takes a list as parameter. The function should return the list with reversed contents.
# Function to reverse a list
def rev(list1):
list1 = list1[::-1]
return list1
l1 = eval(input("Enter list elements (e.g. [1, 2, 3, 4]): "))
print("Original list:", l1)
# Call the function
revlist = rev(l1)
print("Reversed list:", revlist)
For example,
if the SCORES contain [200,456,300,105,235,678]
The sum should be displayed as 340
Tuple Object as Parameter
•Tuples are sequence data type where each element can
be accessed using index
•Tuples are heterogeneous in nature i.e the elements
of a tuple are of mixed data type.
•Tuples are IMMUTABLE which implies the changes cannot
take in place
Example –tobj= (“Computer”,70,30,”083”)
tobj[1] = 100 # will give error
•Tuple elements can be accessed either moving left to
right (using 0 to positive index) or right to left (using negative index from
-1).
Example–print(tobj[1], tobj[-1]
Output–70 ‘083’
•An empty tuple can be created assigning the tuple
object to ( ) or by using tuple()
Example –tup= ( ) or tup= tuple( )
1. # Function that takes a tuple as parameter and
displays its elements
def display_tuple(t):
print("Tuple elements:")
for item in
t:
print(item)
# Main program
my_tuple = (10, 20, 30, 40, 50)
# Passing the immutable tuple to the function
display_tuple(my_tuple)
Trying to Modify the Tuple (Example):
def try_modify_tuple(t):
t[0] =
100 # This will raise an error
my_tuple = (1, 2, 3)
try_modify_tuple(my_tuple)
OUTPUT:
TypeError: 'tuple' object does not support item assignment
2. WAP to input elements in a tuple and pass it to a function to determine the total number of even and odd numbers in it.
Sol:
# Function to count even and odd numbers in a tuple
def count_even_odd(t):
even = 0
odd = 0
for num in t:
if num % 2 == 0:
even += 1
else:
odd += 1
return even, odd
# Input from user
n = int(input("Enter number of elements: "))
elements = []
for i in range(n):
val = int(input("Enter element " + str(i+1) + ": "))
elements.append(val)
# Convert list to tuple
my_tuple = tuple(elements)
# Call the function
even_count, odd_count = count_even_odd(my_tuple)
# Display results
print("Total Even Numbers:", even_count)
print("Total Odd Numbers:", odd_count)
Dictionary Object as Parameter
•Dictionary data type of Python is a Mutable data type
i.e new element can be added and value of an existing element can be changed at
the same memory location.
•Python Dictionary is an unordered collection of
elements where each element is a key-value pair.
•The element of dictionary can be accessed by its key
field using the syntax : dictionary_name[keyfield]
•An empty dictionary can be created assigning the
dictionary object to {} or by using dice()
Example –d1 = {} or d1 = dict( )
Function Returning Multiple Values
2. Write a program using UDF which accepts seconds as parameter and converts seconds to its equivalent hours, minutes and seconds . The converted hours, minutes and seconds should be returned from the function.
def convertsec(sec):
hr= sec // 3600
sec = sec % 3600
min = sec // 60
sec = sec % 60
return hr, min, secv #Multiple objects returned
seconds = int(input("Enter seconds value"))
h, m, s = convertsec(seconds) #Fun call statement
print("The converted hours,minutesand seconds are:",h,m,s)
1. 3.Write a program to define and call a function intcalc() which will take principal, rate of interest and time period from user. The function should return the calculated simple interest.
2. 4. Write a function to display the sum square of of first n natural number. The function should take n as parameter.
3. 5.Write a program to accept two numbers and calculate quotient using a function.
4. 6. Write a program to input an integer. Calculate and display factorial of that integer using a function.
5. 7. Write a function fun_even() to display first 10 even number.
"Flow of Execution" refers
to the order in which a computer executes the lines of code in a program.
#Flow of execution in program to generate first 10 even numbers
def calcint(p,r,t): # Statement 1
si = (p*r*t)/100 # Statement 2
return si # Statement 3
pr = float(input("enter Pricipal amount-")) # Statement 4
rt = float(input("enter interest –")) # Statement 5
time = float(input("enter time period –")) # Statement 6
iamt = calcint(pr,rate,time) # Statement 7
print("Calculated interest – ",iamt) # Statement 8
Determining Flow of execution
1. Statement 1 is executed and determined that it is a correct function header and then statement 2 and 3 constituting function body are ignored.
2. Statement 4, 5 and 6 (first 3 statements of __main__ segment) are executed.
3. Statement 7 has a function call statement, so control jumps to statement 1 (function header statement of calcint()) and then statement 2 and 3 (statement in function body) are executed.
In statement 3 when Python interpreter encounters return statement, Control goes back to statement 7 (containing function call statement and the calculated returned value is assigned to the object iamt.
4. Then Statement 8 will be executed to display the calculated result.
So the flow of execution for the above program can be represented as:
Statement 1 Statement 4, 5, 6 and 7 Statement 1, 2 and 3 statement 8
1. From the program code given below, give the order of execution of code?
def square(s): #1
return s**2 #2
def area(s): #3
ar=power(s) #4
return ar #5
side = float(input(“Enter side - “)) #6
print(area(side)) #7
Comments
Post a Comment