1. Define functions.
Demonstrate the working of functions with parameters and
return statements with suitable code snippets.
A function in Python is a block of reusable code that performs a specific task. It helps in
breaking a program into smaller, modular parts, making it more organized and efficient.
Defining a Function
• A function is defined using the def keyword.
• It can take parameters (inputs) and return a value using the return statement.
def function_name(parameters):
# Function body
return value # (Optional)
1. Function Without Parameters and Return Statement
A function that simply prints a message.
def greet():
print("Hello! Welcome to Python Functions.")
# Calling the function
greet()
Explanation:
• greet() is a simple function that prints a message.
• It does not take any parameters and does not return a value.
2. Function with Parameters
A function that takes two numbers as input and prints their sum.
def add_numbers(a, b): # a and b are parameters
sum_value = a + b
print(f"The sum of {a} and {b} is {sum_value}")
# Calling the function with arguments
add_numbers(5, 10)
add_numbers(8, 2)
Explanation:
• The function add_numbers(a, b) takes two inputs (a and b).
• It calculates their sum and prints it.
• Arguments (5, 10) and (8, 2) are passed while calling the function.
3. Function with Return Statement
A function that takes two numbers, adds them, and returns the result.
def add_numbers(a, b):
return a + b # Returning the sum
# Calling the function and storing the returned value
result = add_numbers(7, 3)
print("Returned Sum:", result)
Explanation:
• add_numbers(a, b) returns the sum instead of printing it.
• The result is stored in the variable result and printed.
4. Function with Default Parameters
A function where one parameter has a default value
def greet(name="Guest"):
print(f"Hello, {name}!")
# Calling function with and without passing an argument
greet("Alice")
greet() # Uses the default value "Guest"
Explanation:
• If a name is provided, it is used.
• If no name is provided, the default value "Guest" is used.
2. Define exception handling. How are exceptions handled in Python? Write a Python
program using the exception to convert Fahrenheit temperature to Celsius.
Exception handling in Python is a mechanism to handle runtime errors and prevent the
program from crashing. It allows us to detect and respond to errors gracefully.
How are Exceptions Handled in Python?
Python provides the try-except block to handle exceptions.
• try block: Contains the code that may cause an exception.
• except block: Handles the exception if it occurs.
• finally block (optional): Always executes, whether an exception occurs or not.
Syntax:
try:
# Code that might cause an exception
except ExceptionType:
# Code to handle the exception
finally:
# (Optional) Cleanup code that runs no matter what
Python Program: Convert Fahrenheit to Celsius with Exception Handling
def fahrenheit_to_celsius():
try:
# Get user input
fahrenheit = float(input("Enter temperature in Fahrenheit: "))
# Convert to Celsius
celsius = (fahrenheit - 32) * 5 / 9
print(f"Temperature in Celsius: {celsius:.2f}")
except ValueError:
print("Invalid input! Please enter a numeric value.")
# Call the function
fahrenheit_to_celsius()
3. Write a Python program to accept n numbers and store them in a list. Then, print the
list with EVEN numbers in it.
# Accept n numbers and store in a list
n = int(input("Enter how many numbers: "))
numbers = []
for i in range(n):
num = int(input("Enter a number: "))
numbers.append(num)
# Print even numbers
print("Even numbers in the list:")
for num in numbers:
if num % 2 == 0:
print(num)
4. Write the syntax for get() and setdefault() dictionary methods. Develop a Python
program demonstrating the get() and setdefault() methods in a dictionary.
get() Method
The get() method retrieves the value of a key in the dictionary. If the key does not exist, it
returns None or a specified default value.
Syntax
dictionary.get(key, default_value)
• key: The key whose value needs to be fetched.
• default_value (optional): The value returned if the key is not found (default is None).
Ex:
student = {"name": "Alice", "age": 20}
# Using get() method
print(student.get("name")) # Output: Alice
print(student.get("grade")) # Output: None (key doesn't exist)
print(student.get("grade", "Not Available")) # Output: Not Available (default value)
setdefault() Method
The setdefault() method checks if a key exists:
• If the key exists, it returns its value.
• If the key does not exist, it adds the key with a default value and returns it.
Syntax
dictionary.setdefault(key, default_value)
• key: The key to check in the dictionary.
• default_value (optional): The value assigned if the key does not exist.
Ex:
student = {"name": "Alice", "age": 20}
# Using setdefault() method
print(student.setdefault("course", "Math")) # Adds "course": "Math"
print(student.setdefault("age", 25)) # Doesn't change "age" since it exists
# Final dictionary
print(student) # Output: {'name': 'Alice', 'age': 20, 'course': 'Math'}
Program :
# Creating a dictionary
student = {"name": "Alice", "age": 20}
# Using get() method
print("Name:", student.get("name")) # Gets the value of 'name'
print("Grade:", student.get("grade", "Not Available")) # 'grade' key does not exist, returns
default
# Using setdefault() method
student.setdefault("course", "Math") # Adds 'course' key with value 'Math' if not present
print("Course:", student["course"]) # Prints the value of 'course'
# Final dictionary
print("Updated Dictionary:", student)
Output:
Name: Alice
Grade: Not Available
Course: Math
Updated Dictionary: {'name': 'Alice', 'age': 20, 'course': 'Math'}
5. Write a Python program to read input from the console and then, check whether the
given string is a palindrome or not without using any inbuilt functions.
def isPalindrome(str):
# Run loop from 0 to len/2
for i in range(0, int(len(str)/2)):
if str[i] != str[len(str)-i-1]:
return False
return True
# main function
s = "malayalam"
ans = isPalindrome(s)
if (ans):
print("Yes")
else:
print("No")
OR
# function which return reverse of a string
def isPalindrome(s):
return s == s[::-1]
# Driver code
s = "malayalam"
ans = isPalindrome(s)
if ans:
print("Yes")
else:
print("No")
6. Write a Python program that accepts a sentence, extracts a substring, and
calculates the number of words, digits, lowercase and uppercase letters
# Python program to analyze a sentence and find details
# Input from the user
sentence = input("Enter a sentence: ")
# Extract a substring
start_index = int(input("Enter the start index: "))
end_index = int(input("Enter the end index: "))
substring = sentence[start_index:end_index]
# Count words, digits, lowercase, and uppercase letters
words = len(sentence.split())
digits = sum(char.isdigit() for char in sentence)
lowercase = sum(char.islower() for char in sentence)
uppercase = sum(char.isupper() for char in sentence)
# Display the results
print(f"Extracted substring: '{substring}'")
print(f"Number of words: {words}")
print(f"Number of digits: {digits}")
print(f"Number of lowercase letters: {lowercase}")
print(f"Number of uppercase letters: {uppercase}")
7. Develop a Python program to get the file size and print the contents of a text file(.txt).
import os
def display_file_info(file_path):
try:
# Get the file size in bytes
file_size = os.path.getsize(file_path)
print(f"File Size: {file_size} bytes\n")
# Open and read the file contents
with open(file_path, 'r') as file:
contents = file.read()
print("File Contents:\n")
print(contents)
except FileNotFoundError:
print(f"Error: The file '{file_path}' does not exist.")
except OSError as e:
print(f"Error: {e}")
# Example usage
file_path = 'example.txt' # Replace with the path to your text file
display_file_info(file_path)