CHAPTER
– FUNCTIONS IN PYTHON
Assignment
Booklet (P- 53) - ANSWER KEY
Q1. Write a menu driven program to accept an integer and do the following on user's choice
1. multiplication Table
2. Factors
3. Check Prime or Composite
Write UDF for each option
Sol:
# Function to print multiplication table
def multtable(num):
for i in range(1, 11):
print(num, "*", i, "=", num * i)
# Function to print all factors
def factors(num):
print("Factors of", num, "are:")
for i in range(1, num + 1):
if num % i == 0:
print(i)
# Function to check prime or composite
def prime(num):
if num < 2:
print(num, "is neither prime nor composite.")
else:
for i in range(2, num // 2 + 1):
if num % i == 0:
print(num, "is Composite")
break
else:
print(num, "is Prime")
# Main Program
num = int(input("Enter number: "))
print("\n1. Multiplication Table\n2. Factors\n3. Prime/Composite")
ch = int(input("Enter your choice: "))
if ch == 1:
multtable(num)
elif ch == 2:
factors(num)
elif ch == 3:
prime(num)
else:
print("Invalid choice.")
Q2. Write a program to define a UDF which will take a string and a character as parameters .
The function should Count and display the number of times a character is appearing in a string.
Sol:
def count(string, ch):
cntch = 0
for c in string:
if c == ch: # check for user given character
cntch += 1
print("Number of times character appears:", cntch)
# Main Program
s = input("Enter string: ")
ch = input("Enter a character: ")
count(s, ch)
Q3. Write a program to define a function which takes a string as parameter.
Count and return the number of alphabets, digits and special characters present in the string.
Sol:
def count(string):
cnta = cntd = cntsp = 0
for ch in string:
if (ch >= 'a' and ch <= 'z') or (ch >= 'A' and ch <= 'Z'):
cnta += 1
elif ch >= '0' and ch <= '9':
cntd += 1
else:
cntsp += 1
return cnta, cntd, cntsp
# Main program
s = input("Enter string: ")
cnta, cntd, cntsp = count(s)
print("Number of alphabets:", cnta)
print("Number of digits:", cntd)
print("Number of special characters:", cntsp)
Q4.Write a program to define a UDF which takes a string as parameter . The function returns the count of all words having number of characters more than 5.
Sol:
def countword(text):
count = 0
for word in text.split():
if len(word) >= 5:
print("Word with length 5 or more:", word)
count += 1
return count
# Main Program
input_str = input("Enter a string: ")
print("Total words with length >= 5:", countword(input_str))
Q5. WAP to create a dictionary trainer with trainer-id as key field and name, experience, salary as value field (stored as a list). Input the trainer data from the user and assign salary on the basis of experience as follows:
Experience Salary
>=10 70000
<10 and >=5 50000
<5 30000
Write a menu driven program to do the following:
i. Count the number of trainers whose experience is more than 20 years
ii. Display the details of trainer given trainer-id.
Display appropriate message when trainer-id is not found. Write UDF for each option.
Sol:
# -*- coding: utf-8 -*-
"""
Created on Tue May 27 12:11:42 2025
@author: Kirti Hora
"""
def count(trainer):
ctr = 0
for tno in trainer:
# Check if experience > 20
if trainer[tno][1] > 20:
ctr += 1
print("Number of trainers with experience > 20:", ctr)
def searchid(trainer):
tn = int(input("Enter trainer id: "))
for tno in trainer:
if tno == tn:
print("Details are:")
print("Name:", trainer[tno][0])
print("Experience:", trainer[tno][1])
print("Salary:", trainer[tno][2])
break
else:
print("ID not found")
# Main Program
trainer = {}
n = int(input("Enter number of elements: "))
for i in range(n):
tid = int(input("Enter trainer id: ")) 0
name = input("Enter name: ") 1
exp = int(input("Enter experience: ")) 2
# Correct salary assignment conditions
if exp >= 10:
salary = 70000
elif 5 < exp < 10:
salary = 50000
else: # exp <= 5
salary = 30000
trainer[tid] = [name, exp, salary]
ch = int(input("1: Count trainers with experience > 20\n2: Search by ID\nEnter your choice: "))
if ch == 1:
count(trainer)
elif ch == 2:
searchid(trainer)
else:
print("Wrong choice")
X-------------------------------------X-------------------------------------------X
1.
Python Program to add two number through function
def
add_numbers(num1, num2):
return num1 + num2
a =
float(input("Enter first number: "))
b =
float(input("Enter second number: "))
result = add_numbers(a,
b)
print("The
sum is:", result)
2.
Python Program to find the Max of two numbers through function
def find_max(num1,
num2):
if num1 > num2:
return num1
else:
return num2
a =
float(input("Enter first number: "))
b =
float(input("Enter second number: "))
maximum =
find_max(a, b)
print("The
maximum number is:", maximum)
3.
Python Program to print the even numbers from a given list.
def
print_even(numbers):
for n in numbers:
if n % 2 == 0:
print(n)
nums = [2, 5, 8,
11, 14, 17, 20]
print_even(nums)
4.
Python Program to check whether the number is prime or not
def is_prime(num):
if num <= 1:
return False
for i in range(2, num):
if num % i == 0:
return False
return True
number =
int(input("Enter a number: "))
if
is_prime(number):
print(number, "is a prime
number.")
else:
print(number, "is not a prime
number.")
5.
Python Program to find sum all the numbers in a list
def
sum_numbers(numbers):
total = 0
for num in numbers:
total += num
return total
nums = [1, 2, 3,
4, 5]
result =
sum_numbers(nums)
print("Sum of
all numbers:", result)
6.
Python Program to reverse a string
def
reverse_string(s):
return s[::-1]
string =
input("Enter a string: ")
reversed_str =
reverse_string(string)
print("Reversed
string:", reversed_str)
7.
Python Program to checks whether a passed string is palindrome or not
def
is_palindrome(s):
return s == s[::-1]
string =
input("Enter a string: ")
if
is_palindrome(string):
print(f'"{string}" is a
palindrome.')
else:
print(f'"{string}" is not a
palindrome.')
8.
Python program that takes a list and returns a new list with unique elements of
the first list
def
unique_elements(lst):
unique_list = []
for item in lst:
if item not in unique_list:
unique_list.append(item)
return unique_list
my_list = [1, 2,
2, 3, 4, 4, 5, 1]
result =
unique_elements(my_list)
print("Unique
elements:", result)
9.
Python program to find the factorial of a given number
def factorial(n):
result = 1
for i in range(1, n + 1):
result *= i
return result
num =
int(input("Enter a number: "))
if num < 0:
print("Factorial is not defined for
negative numbers.")
else:
print(f"Factorial of {num} is
{factorial(num)}")
10. Write a function in Python, which
accepts an integer list as parameters and rearranges the list in reverse. Eg.
If a list of nine elements initially contains the elements as 4, 2, 5, 1, 6, 7, 8, 12, 10. Then the function
should rearrange the list as 10,12, 8,
7, 6, 1, 5, 2, 4
def
reverse_list(lst):
lst.reverse()
numbers
= [4, 2, 5, 1, 6, 7, 8, 12, 10]
reverse_list(numbers)
print("Reversed
list:", numbers)
11. Write a function called one_away that takes two
strings and returns True if the strings are of the same length and differ in
exactly one letter, like bike/hike or water/wafer.
def one_away(str1, str2):
if len(str1) !=
len(str2):
return
False
diff_count = 0
for i in
range(len(str1)):
if str1[i]
!= str2[i]:
diff_count += 1
if
diff_count > 1:
return False
return
diff_count == 1
print(one_away("bike", "hike")) # True
print(one_away("water", "wafer")) #
True
print(one_away("hello", "hallo")) #
True
print(one_away("test", "tent")) # True
print(one_away("test", "toast")) # False
12. Write a function called change_case that given a
string, returns a string with each upper case letter replaced by a lower case
letter and vice-versa.
def change_case(s):
result =
""
for char in s:
if
char.isupper():
result
+= char.lower()
elif
char.islower():
result
+= char.upper()
else:
result
+= char
return result
input_str = "Hello World!"
print(change_case(input_str))
13. Write a definition of a method COUNTNOW(PLACES) to find
and display those place names, in which there are more than 5
characters.
For example: If the list
PLACES contains
["DELHI",
"LONDON", "PARIS", "NEW YORK", "DUBAI"]
The following should get
displayed:
LONDON
NEW YORK
def COUNTNOW(PLACES):
for place in PLACES:
if len(place) > 5:
print(place)
PLACES =
["DELHI", "LONDON", "PARIS", "NEW
YORK", "DUBAI"]
COUNTNOW(PLACES)
14.
Write the definition of a method ZeroEnding(SCORES) to add all those values in
the list of SCORES, which are ending with zero (0) and display the sum. For example: if the SCORES contain [200, 456, 300, 100,
234, 678]. The sum should be displayed as 600
def
ZeroEnding(SCORES):
total = 0
for score in SCORES:
if str(score).endswith('0'):
total += score
print(total)
SCORES
= [200, 456, 300, 100, 234, 678]
ZeroEnding(SCORES) # Output: 600
15. Write a Python program
with the following two functions:
- calcsal(basic_salary)
This function should take the basic salary as a parameter and do the
following:
- Calculate deduction as 5.5%
of the basic salary
- Calculate allowance as 12% of
the basic salary
- Calculate net salary as:
net_salary = basic_salary + allowance - deduction
- Return the calculated net salary
- calcdesig(net_salary)
This function should take the net salary as a parameter and assign a designation
based on the following conditions:
- If net salary is greater than
100000, the designation is "Manager"
- If net salary is between 50000
(inclusive) and 100000 (inclusive), the designation is "Executive"
- If net salary is less than 50000,
the designation is "Non-executive"
- Return the assigned designation
Write code to:
- Accept the basic salary from the user
- Call the calcsal() function to
compute the net salary
- Call the calcdesig() function to
determine the designation
Display the net
salary and designation
Sol:
def calcdesig(net):
if net >= 100000:
desig = "Manager"
elif net >= 50000:
desig = "Executive"
else:
desig = "NonExecutive"
return desig
def calcsal(basic):
d = 5.5 / 100 * basic
allw = 0.12 * basic
net = basic + allw - d
print("Net Salary =", net)
print("Designation =", calcdesig(net))
# Main program
basic = float(input("Enter basic salary: "))
calcsal(basic)
16. Question:
Write a Python program
that defines a function named checkchar(). This function should:
- Take a single character as a
parameter.
- Check whether the character is:
- an Alphabet (A-Z or a-z)
- a Digit (0-9)
- a Special Character (any
character that is not an alphabet or digit)
- Print an appropriate message
indicating the type of the character.
The program should:
- Accept a character input from the
user.
- Call the checkchar() function with
the input character.
Example Output:
Enter a character: @
@ is a Special Character
Let me know if you'd like
the sample code too.
Sol:
def checkchar(ch):
if ch >= "0" and ch <= "9":
res = "Digit"
elif (ch >= "a" and ch <= "z") or (ch >= "A" and ch <= "Z"):
res = "Alphabet"
else:
res = "Special Character"
return res
# Main program
ch = input("Enter a character: ")
# Optional: Check if only one character was entered
if len(ch) == 1:
print(checkchar(ch))
else:
print("Please enter only a single character.")
17. Write a program using UDF which takes x and n as parameters and calculates x to the power of n.
Sol:
def power(x, n):
prod = 1
for i in range(1, n + 1):
prod *= x
print("x to the power of n =", prod)
# Main program
n = int(input("Enter n value: "))
x = int(input("Enter x value: "))
power(x, n)
Comments
Post a Comment