Skip to main content

GRADE XII - CS - PYTHON FUNCTIONS - NOTES | 19-05-2025


 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

1.  Function to Display Full Name

Write a Python program that defines a function to display a person's full name. Follow the requirements below:

  1. The function should have two parameters to accept the first name and last name.
  2. Concatenate the first name and last name using the + operator with a space in between.
  3. 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)


 String Object as Parameter to User Defined function

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)


def string_length(s):
    count = 0
    for i in s:
        count += 1
    return count

s="LOTUS"
print(string_length(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()

Example –lst= [] or lst= 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)

2.  Write a program to define a UDF which takes a list as parameter. The function should add all those values in the list SCORES, which are ending with five(5) and display the sum.

For example,

if the SCORES contain [200,456,300,105,235,678]

The sum should be displayed as 340

def SCORES(list1):
    sum=0
    for k in list1:
        if k%10==5:
            sum+=k
    print("Sum of all numbers ending with 5:",sum)
    
l1=eval(input("Enter listelements"))
SCORES(l1)


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

Popular posts from this blog

GRADE XII - Python Connectivity with MySQL

  Python Connectivity with MySQL In real-life applications, the data inputted by the user and processed by the application needs to be saved permanently, so that it can be used for future manipulation. Usually, input and output data is displayed during execution but not stored, as it resides in main memory , which is temporary — i.e., it gets erased once the application is closed. This limitation can be overcome by sending the data to be stored in a database , which is made accessible to the user through a Front-End interface . Key Concepts Database A database is an organized collection of data that is stored and accessed electronically from a computer system. DBMS (Database Management System) A DBMS is software that interacts with end-users, applications, and the database to capture and analyze data. Front-End The Front-End is the user interface of the application, responsible for input/output interaction with the user. Back-End The Back-End refe...

GRADE XII - CSV FILE

CSV FILE (COMMA SEPERATED VALUE) CSV NOTES LINK :  CSV NOTES - CLICK HERE Writing data to a CSV file involves the following steps: Import the csv module Open the CSV file in write mode ( "w" ) using open() Create the writer object Write the data into the file using the writer object Close the file using close() writerow() Method This method is used to write a single row to a CSV file. It takes a sequence (list or tuple) as its parameter, and writes the items as a comma-separated line in the file. You do not need to add a newline character (\n) — it automatically places the end-of-line marker.     EXAMPLE 1: import csv  # Importing the csv module # CSV file opened using relative path csv_fobj = open("emp.csv", "w")   # Writer object created wtr_obj = csv.writer(csv_fobj) # Record with field heading is written wtr_obj.writerow(["Empno", "Name", "Salary"]) # Records with data are...