7. What is string in Python? How to slice the string.
UNIT 3 - Python Programming - Answer Key Ans: A string in Python is a sequence of characters. Slicing is done using the syntax:
string[start:end]. Example: 'hello'[0:2] returns 'he'.
PART-A (2 Marks Questions)
1. What is a function in Python. How do you define a function in Python? 8. Create a function with default parameters to compute simple interest.
Ans: A function in Python is a reusable block of code that performs a specific task. It is Ans: def simple_interest(p, r=5, t=2):
defined using the 'def' keyword followed by the function name and parentheses (). return (p * r * t) / 100
Example: def my_function(): print(simple_interest(1000))
print("Hello from a function")
9. List out the parameter passing methods in Python
2. Write a function greet(name) that takes a name as an argument and prints
"Hello, <name>!" Ans: Python uses pass-by-object-reference (also called pass-by-assignment). Arguments
are passed by reference to the object. It supports positional, keyword, default, and
Ans: def greet(name): variable-length arguments.
print(f"Hello, {name}!")
This function accepts a name as argument and greets it. 10. Write a program to demonstrate the difference between formal and actual
parameters.
3. What is the difference between a function definition and a function call?
Ans: def add(a, b): # a, b are formal
Ans: Function definition is the creation of the function using 'def'. Function call is the return a + b
execution of that function using its name followed by parentheses. Example: def x=5
hello(): ... and hello() is the call. y=3
print(add(x, y)) # x, y are actual
4. Define a function “calculate_area(length, width)” that returns the area of a
rectangle. Call it with two numbers and print the result. 11. Write a program to demonstrate keyword arguments in Python
Ans: def calculate_area(length, width): Ans: def student(name, age):
return length * width print(name, age)
print(calculate_area(5, 3)) student(age=21, name='Alice')
5. What is recursion? Write a recursive function to calculate factorial of a number. 12. Write a Python program to slice the string "PythonProgramming" and print
"Python" and "Programming" separately.
Ans: Recursion is a method where the function calls itself to solve a problem. def
factorial(n): Ans: s = "PythonProgramming"
return 1 if n == 0 else n * factorial(n-1) print(s[:6])
print(s[6:])
6. Write a recursive function to calculate the factorial of a number.
Output:
Ans: def factorial(n):
if n == 0: Python
return 1
else: Programming
return n * factorial(n-1) 13. List out five string methods in python.
Ans: 1. upper() – Converts to uppercase Ans: A regular expression is a special sequence of characters that helps match patterns in
2. lower() – Converts to lowercase strings. They are used for validation, searching, and pattern-based string manipulation.
3. find() – Searches for a substring
4. replace() – Replaces a string PART-B (15 Marks Questions)
5. split() – Splits into list 21. Write a Python program that performs the following operations for a student
record processing system: Accept input from the user in the format: "Name,
14. Write a function count_vowels(s) that counts the number of vowels in a string s. Email, Department, Marks" (e.g., John Doe, [email protected], CSE, 87)
Use string slicing and functions to: Extract the first name and last name
Ans: def count_vowels(s): separately. Convert the department name to uppercase. Check whether the
return sum(1 for char in s if char.lower() in 'aeiou') email is valid using a regular expression.
15. What is the purpose of *args and **kwargs in Python function definitions? Ans:
Ans: *args allows variable number of positional arguments. **kwargs allows variable def process_student_record(record):
number of keyword arguments. They help in creating flexible functions. import re
name, email, department, marks = map(str.strip, record.split(","))
16. Write a program using regular expressions to validate if an input string is a first_name, last_name = name.split(" ", 1)
valid email address. department = department.upper()
email_pattern = r'^[\w\.-]+@[\w\.-]+\.\w{2,}$'
Ans: import re
is_valid_email = bool(re.match(email_pattern, email))
pattern = r'^[\w\.-]+@[\w\.-]+\.\w{2,}$'
print(f"First Name: {first_name}")
email = '[email protected]'
print(f"Last Name: {last_name}")
print(bool(re.match(pattern, email)))
print(f"Department: {department}")
17. Differentiate between positional arguments and keyword arguments with print(f"Email Valid: {is_valid_email}")
examples
record_input = "John Doe, [email protected], CSE, 87"
Ans: Positional arguments are based on position: func(10, 20). Keyword arguments are process_student_record(record_input)
named: func(a=10, b=20). Keyword arguments can be used in any order. Explanation:
- The function splits the input string into components.
18. Write a recursive function in Python to calculate the sum of first n natural
- String slicing is used for name separation.
numbers.
- The department is converted to uppercase.
Ans: def sum_n(n): - A regex checks if the email is valid.
return 1 if n == 1 else n + sum_n(n-1)
22. Define formal parameters and local variables in the context of Python functions.
19. Write a program to demonstrate default arguments in Python Write a function calculate_total(price, quantity) that: Uses price and quantity as
formal parameters. Calculates and returns the total cost using a local variable
Ans: def greet(name="Guest"): total. Show how the function can be called with actual values and print the result
print(f"Hello, {name}")
greet() Ans:
greet("Alice") def calculate_total(price, quantity):
total = price * quantity # 'total' is a local variable
20. What is a regular expression? return total
# Calling the function with actual parameters - s[:6] gets characters from index 0 to 5.
print("Total Cost:", calculate_total(50, 3)) - s[6:] gets from index 6 to the end.
- s[-11:-4] uses negative indexing to slice from the end.
Explanation:
- Formal parameters are variables listed in a function definition (price, quantity). 25. Write a recursive Python function to compute the sum of squares of integers
- Local variables are defined inside a function and used only there (total). from 1 to n. The function should accept n as a parameter. Use recursion to
- Actual parameters are values passed when calling the function (50, 3). calculate the sum of squares.
23. Explain the use of default arguments and keyword arguments in Python Ans:
functions. Write a function student_info(name, age=18, city='Unknown') that def sum_of_squares(n):
prints student details and Call the function in three different ways if n == 1:
return 1
Ans: else:
def student_info(name, age=18, city='Unknown'): return n**2 + sum_of_squares(n-1)
print(f"Name: {name}, Age: {age}, City: {city}")
print("Sum of squares:", sum_of_squares(5))
student_info("Alice")
student_info("Bob", 20) Explanation:
student_info("Charlie", city="Chennai") - The function recursively adds n squared to the sum of squares of (n-1).
- Base case is when n == 1.
Explanation:
- Default arguments allow functions to be called with fewer arguments. 26. Why are strings designed to be immutable in Python? Discuss the advantages
- Keyword arguments improve readability and allow out-of-order specification. and give real-world programming implications
- The function demonstrates all three ways: with default values, overriding defaults, and Ans:
using keywords. Strings are immutable to enhance performance and safety:
24. Explain the concept of string slicing in Python. How does negative indexing 1. Security: Immutable objects are safe from unintended modifications.
work? Provide examples demonstrating slicing from the start, middle, and end 2. Hashing: Immutable strings can be used as keys in dictionaries.
of a string. 3. Thread Safety: Immutable objects are safe in concurrent programs.
4. Performance: Memory reuse is more efficient with immutable strings.
Ans:
String slicing allows extracting a portion of a string using [start:end] syntax. Real-world implication:
Negative indexing counts from the end of the string, starting at -1. - Using + to concatenate strings creates new strings each time.
- Better to use join() for multiple concatenations for performance.
Examples:
s = "PythonProgramming" 27. Write a Python program that demonstrates the use of at least five string
print(s[:6]) # Output: Python (start) methods: upper(), lower(), replace(), find(), and split(). Explain what each does.
print(s[6:]) # Output: Programming (end) Ans:
print(s[6:13]) # Output: Program (middle) text = "Hello, Python Programming!"
print(s[-11:-4]) # Output: Program (negative indexing)
print(text.upper()) # Converts all to uppercase
Explanation: print(text.lower()) # Converts all to lowercase
print(text.replace("Python", "Java")) # Replaces a word 30. Write a Python program that uses a regular expression to check whether a
print(text.find("Python")) # Finds position of substring given email address is valid. The email should meet the following criteria:
print(text.split()) # Splits into list of words Contains exactly one "@" symbol. Contains at least one "." after the "@"
symbol. The domain name should have at least two characters after the last dot.
Explanation:
- upper() and lower() change case. Ans:
- replace() substitutes one substring with another. import re
- find() locates substring's index.
- split() breaks string into list based on spaces. def validate_email(email):
pattern = r'^[\w\.-]+@[\w\.-]+\.\w{2,}$'
28. Explain the difference between *args and **kwargs in Python. Write a function return bool(re.match(pattern, email))
summarize(*args, **kwargs) that Prints the sum of all numbers passed in args.
email = "[email protected]"
Ans: print("Valid Email:" if validate_email(email) else "Invalid Email")
def summarize(*args, **kwargs):
print("Sum of args:", sum(args)) Explanation:
- The pattern checks for a valid structure of email.
summarize(1, 2, 3, 4) - Includes one '@', dot after it, and 2+ characters in domain extension.
summarize(5, 10, a=1, b=2)
Explanation:
- *args allows passing variable number of positional arguments.
- **kwargs allows passing variable number of keyword arguments.
- args is a tuple, kwargs is a dictionary.
29. Write a Python function that accepts a string and attempts to modify it. Show
that strings are immutable by demonstrating that the changes do not reflect
outside the function.
Ans:
def modify_string(s):
s = "Modified"
print("Inside function:", s)
original = "Original"
modify_string(original)
print("Outside function:", original)
Explanation:
- Even though the string is modified inside the function, it does not affect the original.
- This is because strings are immutable and a new object is created inside the function.