0% found this document useful (0 votes)
22 views52 pages

Python Programs for Basic Functions

The document contains a series of Python programming exercises covering various topics such as functions, loops, string manipulation, and file handling. Each exercise includes a brief description, the corresponding code, and expected outputs. The exercises range from calculating areas and averages to handling exceptions and working with tuples and classes.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views52 pages

Python Programs for Basic Functions

The document contains a series of Python programming exercises covering various topics such as functions, loops, string manipulation, and file handling. Each exercise includes a brief description, the corresponding code, and expected outputs. The exercises range from calculating areas and averages to handling exceptions and working with tuples and classes.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Python programs

[Link] a program to compute to compute area


of a rectangle using function .The function
should accept two parameters (l,b),length is a
default parameter with value =5.5.
def main():
l=eval(input("enter the length:"))
b=eval(input("enter the breadth:"))
c=compute_area(b)
print("the area of rectangle using default length
is,",c)
d=compute_area(b,l)
print("the area of rectangle : ",d)
def compute_area(b,l=5.5):
a=l*b
return a
main()

#OUTPUT:

[Link] area of a square.


def main():
s=eval(input("The side of a square:"))
b=compute_area(s)
print("the area of square is,", b)
def compute_area(s):
a=s*s
return a
main()

#OUTPUT:
[Link] a program to input 10 integers from a
user as an integer if it is an odd no print the
value of that list element otherwise print BYE.
l=[]
for i in range(0,10):
a=int(input("enter the integers:"))
[Link](a)
for j in l:
if j%2==0:
print("BYE")
else:
print(j)

#OUTPUT:
[Link] a programme to create a function to
calculate average marks obtained by a student in
5 subjects.
(a) for loop
(b) while loop
a. def average(marks):
total = 0
for mark in marks:
total += mark
average = total / len(marks)
return average

if __name__ == "__main__":
marks = []
print("Enter marks for 5 subjects:")
for i in range(5):
mark = int(input("Enter mark for subject:"))
[Link](mark)

avg_marks = average(marks)
print("Average using for loop: ",avg_marks)

#OUTPUT:
b. def average(marks):
total = 0
i=0
while i < len(marks):
total += marks[i]
i += 1
average = total / len(marks)
return average
if __name__ == "__main__":
marks = []
print("Enter marks for 5 subjects:")
for i in range(5):
mark = int(input("Enter mark for subject:"))
[Link](mark)

avg_marks = average(marks)
print("Average using while loop: ",avg_marks)
#OUTPUT:

[Link] a python function to print the


multiplication table of the number containing 1st
n multiples.
def multiplication(n):
m=int(input("how many times you want
multiplication:"))
for i in range(1,m+1):
a=n*i
print(n,"*",i,"=", a)
n=int(input("Enter the number:"))
multiplication(n)

#OUTPUT:
[Link] a program for python function which
contain name ,roll no and total marks of five
students ,these function will read function
without any data and also create all these
function in main.

def main():

students = []
for i in range(5):
print("Enter details for student ",(i+1),":")
name = input("Enter name of the student : ")
roll_no = input("Enter roll number: ")
total_marks = int(input("Enter total marks: "))
[Link]({"name": name, "roll_no":
roll_no, "total_marks": total_marks})
return students

if __name__ == "__main__":
students = main()

# Display student data


print("\nDetails of Students:")
for student in students:
print(f”Name: {student['name']}, Roll No:
{student['roll_no']}, Total Marks:
{student['total_marks']}")

#OUTPUT:
[Link] a program to count the no of digits in a
number.

def count_digits(number):
number = abs(number)
count = len(str(number))
return count
num = int(input("Enter a number: "))
digit_count = count_digits(num)

print(f"The total number of digits in the number {num}


is {digit_count}.")

#OUTPUT:
[Link] a program to find factorial of a number.

def factorial(n):
if n < 0:
return "Factorial does not exist for negative
numbers."
elif n == 0 or n == 1:
return 1
else:
result = 1
for i in range(2, n + 1):
result *= i
return result
number = int(input("Enter a number: "))
print(f"The factorial of {number} is
{factorial(number)}")

#OUTPUT:
[Link] a program to calculate the sum of all the
odd number within the given range ,two values
(a,b) and find sum.

def sum_of_odds(a, b):


if a > b:
a, b = b, a
odd_sum = 0
for number in range(a, b + 1):
if number % 2 != 0:
odd_sum += number

return odd_sum
try:
a = int(input("Enter the start of the range (a): "))
b = int(input("Enter the end of the range (b): "))
result = sum_of_odds(a, b)
print(f"The sum of all odd numbers between {a} and
{b} is: {result}")
except:
print("invalid range")

#OUTPUT:

[Link] a program to create a function


assigngrade() which takes agg. marks of a
student as input parameter and assign a grade
on the basis of marks obtained as per the
following table:

RANGE OF MARKS GRADE

90-100 A
80-89 B
70-79 C
60-69 D
LESS THAN 60 F

def assign_grade(agg_marks):

if agg_marks >= 90:


return "Grade A"
elif agg_marks >= 80:
return "Grade B"
elif agg_marks >= 70:
return "Grade C"
elif agg_marks >= 60:
return "Grade D"
else:
return "Grade F"
try:
marks = float(input("Enter the aggregate marks (0-
100): "))

if 0 <= marks <= 100:


grade = assign_grade(marks)
print(f"The grade assigned for marks {marks} is:
{grade}")
else:
print("Please enter marks between 0 and 100.")
except :
print("Invalid input")
#OUTPUT:

[Link] pass=’pwd’ then only enter “welcome to the


system” otherwise “login unsuccessful”.
def authenticate():
if password=="pwd":
print("welcome to the system")
else:
print
password=input("enter the password:")
authenticate()

#OUTPUT:
[Link] a program to create a function that
modulates the marks of a student .It takes as
input student marks and passing marks.
The moderation is done by max of 1 or 2
[Link] function then return the moderated
updated marks.

def moderate_marks(student_marks, passing_marks):


if student_marks < passing_marks and
passing_marks - student_marks <= 2:
return passing_marks
return student_marks
try:
student_marks = int(input("Enter the student's
marks: "))
passing_marks = int(input("Enter the passing marks:
"))
moderated_marks =
moderate_marks(student_marks, passing_marks)
print(f"The moderated marks are:
{moderated_marks}")
except :
print("Invalid input")

#OUTPUT:
13. Write a program to create a function to find
maximum of 3 [Link] function maximum
should take 3 integers as input parameter and
return the maximum of three values
(parameter) .

def maximum(num1, num2, num3):


return max(num1, num2, num3)
try:
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
num3 = int(input("Enter the third number: "))
max_value = maximum(num1, num2, num3)
print(f"The maximum of {num1}, {num2}, and
{num3} is: {max_value}")
except :
print("Invalid input")
#OUTPUT:

[Link] a program to print the following pattern


while/for loop:

*
**
***
****
*****
rows = 5
for i in range(1, rows + 1):
print('*' * i)
print("\nUsing a while loop:")
i=1
while i <= rows:
print('*' * i)
i += 1
#OUTPUT:

[Link] a function to reverse a string.


def my_function(x):
return x[::-1]
txt=my_function(" I wonder how this text looks like
backwards")
print(txt)

#OUTPUT:
[Link] the number of common character in 2
given strings str 1 and str 2.
s1=input("Enter first string:")
s2=input("Enter second string:")
a=list(set(s1)&set(s2))
print("the common letters are:")
for i in a:
print(i)

#OUTPUT:
[Link] to perform the following operations on a
string :
(a) Replace the character by another character in
a string.
(b) Remove the 1st occurance of a character from
a string.
(c) Remove all occurrances of a character from a
string.
def string_operations():
str1 = input("Enter the original string: ")
#(a)Replace a character with another character
a = input("Enter the character to replace: ")
b = input("Enter the replacement character: ")
replace_ = [Link](a, b)
print(f"(a) String after replacing '{a}' with '{b}':
{replace_}")

# (b) Remove the first occurrence of a character


c = input("Enter the character to remove (first
occurrence): ")
removed_string = [Link](c, '', 1)
print(f"(b) String after removing the first occurrence
of '{c}': {removed_string}")

# (c) Remove all occurrences of a character


d = input("Enter the character to remove (all
occurrences): ")
all_removed_string = [Link](d, '')
print(f"(c) String after removing all occurrences of
'{d}': {all_removed_string}")

string_operations()
#OUTPUT:

[Link] and filter out odd and even number of


given list.
a = [1,2,3,4,5,6,7,8,9,14,32]
even = 0
odd = 0

for num in a:
if num % 2 == 0:
even += 1
else:
odd += 1
print("Even numbers:", even)
print("Odd numbers:", odd)
#OUTPUT:
[Link] a program to square each element of a
list and input from user and print the list in
reverse order.

a = input("Enter numbers separated by spaces: ")


num = list(map(int, [Link]()))
sqn= [x**2 for x in num]
reverse = sqn[::-1]
print("Reversed list of squared numbers:", reverse)

#OUTPUT:
20. Write a program to accept a name from a
user. Raise and handle exception if the text
entered by the user contains digits and /or
special characters.

class InvalidNameError(Exception):
"""Custom exception for invalid name input"""
pass

def validate_name(name):
"""
Validate if the name contains only alphabets and
spaces
Raises InvalidNameError if name contains digits or
special characters
"""
if not [Link]():
raise InvalidNameError("Name cannot be empty")

for char in name:


if not ([Link]() or [Link]()):
raise InvalidNameError("Name can only contain
letters and spaces")

return True

def get_valid_name():
"""Get and validate name input from user"""
try:
name = input("Enter your name: ")
validate_name(name)
print(f"\nValid name entered: {name}")
return name

except InvalidNameError as e:
print(f"\nError: {e}")
print("Please enter a name using only letters and
spaces.")

except Exception as e:
print(f"\nAn unexpected error occurred: {e}")

while True:
get_valid_name()

try_again = input("\nWould you like to try again?


(yes/no): ").lower()
if try_again != 'yes':
print("Goodbye!")
break

#OUTPUT:
[Link] a tuple t1=(1,2,5,7,9,2,4,6,8,10)
write a program to perform following
operations:
(a). Print half the values of tuple in one line and
the other half is the next.
(b). Print another tuple whose values are even
numbers in the given tuple.
(c).concatenate a tuple t2=(11,13,15) with t1.
(d). Return maximum and minimum value from
this tuple.

t1 = (1, 2, 5, 7, 9, 2, 4, 6, 8, 10)
def operations():
# (a) Print half the values of tuple in one line and the
other half in the next
midpoint = len(t1) // 2
first_half = t1[:midpoint]
second_half = t1[midpoint:]
print("First half of the tuple:", first_half)
print("Second half of the tuple:", second_half)

# (b) Print another tuple whose values are even


numbers in the given tuple
even_numbers = tuple(x for x in t1 if x % 2 == 0)
print("Tuple of even numbers:", even_numbers)

# (c) Concatenate a tuple t2=(11, 13, 15) with t1


t2 = (11, 13, 15)
concatenated_tuple = t1 + t2
print("Concatenated tuple:", concatenated_tuple)

# (d) Return maximum and minimum value from this


tuple
max_value = max(t1)
min_value = min(t1)
print("Maximum value in t1:", max_value)
print("Minimum value in t1:", min_value)
operations()
#OUTPUT:

[Link] a function that prints a dictionary where


the keys are numbers between 1 and 5 and the
values of cubes of the keys.

def create_cube_dict():
cube_dict = {num: num**3 for num in range(1, 6)}
return cube_dict

def print_cube_dict():
cube_dict = create_cube_dict()
print("Number : Cube")
print("-" * 15)
for number, cube in cube_dict.items():
print(f"{number:^6} : {cube:^6}")

if __name__ == "__main__":
print_cube_dict()

#OUTPUT:

[Link] a program to define a class point with


coordinates x and y as attributes. create relevant
methodsand print objects. Also define a method
distance to calculate distance between any two
point objects.

import math

class Point:
def __init__(self, x, y):
self.x = x
self.y = y

def __repr__(self):

return f"Point({self.x}, {self.y})"

def distance(self, other):

return [Link]((self.x - other.x)**2 + (self.y -


other.y)**2)

#for example
if __name__ == "__main__":
point1 = Point(3, 4)
point2 = Point(7, 1)

print("Point 1:", point1)


print("Point 2:", point2)

# Calculate and print the distance between the two


points
print("Distance between Point 1 and Point 2:",
[Link](point2))

#OUTPUT:
[Link] a program to read a file and
(a) Print the total number of characters ,words
and lines in the file.
(b)calculate the frequency of each character in a
file .Use a variable of a dictionary type to
maintain the count.
(c) Print the words in reverse order.
(d) Copy even lines of a file to a file named ‘File1’
and odd lines to another file named ‘File2’.

def process_file(file_path):
# Define the variables
total_characters = 0
total_words = 0
total_lines = 0
char_frequency = {}
words_list = []

# Open and read the file


with open(file_path, 'r') as f:
lines = [Link]()
total_lines = len(lines)

for line_number, line in enumerate(lines):


# Count characters
total_characters += len(line)

# Count words
words = [Link]()
total_words += len(words)
words_list.extend(words)

# Count the character frequency


for char in line:
if [Link](): # Count only alphanumeric
characters
char_frequency[char] =
char_frequency.get(char, 0) + 1

# Write the lines that are even-numbered to


one file and the odd-numbered lines to another file
if line_number % 2 == 0:
with open('[Link]', 'a') as file1:
[Link](line)
else:
with open('[Link]', 'a') as file2:
[Link](line)

# Finally, print the total characters, words, and lines


print('Total Characters:', total_characters)
print('Total Words:', total_words)
print('Total Lines:', total_lines)

# Print the frequency of characters


print('Character Frequency:')
for k in char_frequency.keys():
print(k, ':', char_frequency[k])

# Print words in reverse


print('Words in Reverse Order:')
for w in words_list[::-1]:
print(w)

#OUTPUT:
[Link] a program to create a list of cubes of
only the even integers appearing in the input list
using the following:
(a) ‘for’ loop
(b) list comprehension

# Sample list
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# (a) Using a 'for' loop
cubes_of_even_numbers = []
for number in a:
if number % 2 == 0:
cubes_of_even_numbers.append(number ** 3)

print("Cubes of even numbers using for loop:",


cubes_of_even_numbers)

# (b) Using list comprehension


cubes_of_even_numbers_list_comprehension =
[number ** 3 for number in a if number % 2 == 0]

print("Cubes of even numbers using list


comprehension:",
cubes_of_even_numbers_list_comprehension)

#OUTPUT:

26. Write a program to swap first n characters of


two strings.

def swap(str1, str2, n):

if n > len(str1) or n > len(str2):


print("Error: n is greater than the length of one or
both strings.")
return None, None
# Swap the first n characters
swapped_str1 = str2[:n] + str1[n:]
swapped_str2 = str1[:n] + str2[n:]

return swapped_str1, swapped_str2

str1 = input("Enter the first string: ")


str2 = input("Enter the second string: ")
n = int(input("Enter the number of characters to swap:
"))

result1, result2 = swap(str1, str2, n)

if result1 is not None and result2 is not None:


print("After swapping:")
print("First string:", result1)
print("Second string:", result2)

#OUTPUT:
[Link] a program that accepts two strings and
return indices of all occurrences of the second
string in the first string as a list. If the second
string is not present in the first string then it
should return -1.

def occurrences(main_string, sub_string):


indices = []
sub_length = len(sub_string)

for i in range(len(main_string) - sub_length + 1):


if main_string[i:i + sub_length] == sub_string:
[Link](i)
return indices if indices else -1

main_string = input("Enter the main string: ")


sub_string = input("Enter the substring to find: ")

result = occurrences(main_string, sub_string)


print("Indices of occurrences:", result)

#OUTPUT:

[Link] a program to create a pyramid of a


character ’*’ and reverse pyramid.
def pyramid(n):
pyramid_pattern = ""
for i in range(1, n + 1):
pyramid_pattern += " " * (n - i) + "*" * (2 * i - 1) +
"\n"
return pyramid_pattern

def reverse_pyramid(n):
reverse_pyramid_pattern = ""
for i in range(n, 0, -1):
reverse_pyramid_pattern += " " * (n - i) + "*" * (2
* i - 1) + "\n"
return reverse_pyramid_pattern

if __name__ == "__main__":
rows = 5
print("Pyramid:\n")
print(pyramid(rows))
print("Reverse Pyramid:\n")
print(reverse_pyramid(rows))
#OUTPUT:

[Link] a program to accept a number ‘n’ :


(a) Check if ‘n’ is prime .
(b) Genearte all prime numbers till’n’.
(c) Generate first ‘n’ prime numbers.

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
def primes_till_n(n):

return [i for i in range(2, n + 1) if is_prime(i)]

def first_n_primes(n):

primes = []
candidate = 2
while len(primes) < n:
if is_prime(candidate):
[Link](candidate)
candidate += 1
return primes

if __name__ == "__main__":
n = int(input("Enter a number: "))

# (a) Check if n is prime


if is_prime(n):
print(f"{n} is a prime number.")
else:
print(f"{n} is not a prime number.")

# (b) Generate all prime numbers till n


print(f"Prime numbers up to {n}: {primes_till_n(n)}")
# (c) Generate first n prime numbers
print(f"First {n} prime numbers:
{first_n_primes(n)}")

#OUTPUT:
30. Write a program to find the roots of a
quadratic equation.

import cmath

def find_roots(a, b, c):


D = b**2 - 4*a*c
root1 = (-b + [Link](D)) / (2 * a)
root2 = (-b - [Link](D)) / (2 * a)

return root1, root2

if __name__ == "__main__":
a = float(input("Enter coefficient a (for ax^2): "))
b = float(input("Enter coefficient b (for bx): "))
c = float(input("Enter constant c: "))

if a == 0:
print("Coefficient 'a' cannot be zero in a quadratic
equation.")
else:
roots = find_roots(a, b, c)
print(f"The roots of the quadratic equation are:
{roots[0]} and {roots[1]}")

#OUTPUT:
[Link] a program that accepts a character and
performs the following:
(a) print whether the character is a letter or
numeric digit or a special character.
(b) if the character is a letter , print whether the
character is uppercase or lowercase.
(c) if the character is numeric digit ,print its
name in text.

def character_info(char):

if [Link]():
print(f"{char} is a letter.")
if [Link]():
print(f"{char} is uppercase.")
else:
print(f"{char} is lowercase.")
elif [Link]():
digit_names = {
'0': 'zero',
'1': 'one',
'2': 'two',
'3': 'three',
'4': 'four',
'5': 'five',
'6': 'six',
'7': 'seven',
'8': 'eight',
'9': 'nine'
}
print(f"{char} is a numeric digit, which is
'{digit_names[char]}'.")
else:
print(f"{char} is a special character.")

if __name__ == "__main__":
character = input("Enter a character: ")

if len(character) == 1:
character_info(character)
else:
print("Please enter exactly one character.")

#OUTPUT:
[Link] str 1 and str 2 of alphabet find out the
count of character in str 1 , that matches a
Character in str 2, ignoring
any difference in case
If a character - ch 1 in str 1 appears more than in
str 2 , then energy occurrence of ch 1 in str2
should be counted

Matching char (str 1 and str2)

def count(str1, str2):


str1 = [Link]()
str2 = [Link]()

frequency_str2 = {}
for char in str2:
if [Link]():
if char in frequency_str2:
frequency_str2[char] += 1
else:
frequency_str2[char] = 1

# Count matching characters from str1


count = 0
for char in str1:
if [Link]() and char in frequency_str2:
count += min([Link](char),
frequency_str2[char])

return count

str1 = input(“Enter string 1:”)


str2 = input(“Enter string 2:”)
result = count(str1, str2)
print(result)

#OUTPUT:

You might also like