Docs
Python
Unit 4

1. What is function?

A function is a block of reusable code that performs a specific task. Functions take input arguments, process them, and return a result.

They are defined using the def keyword and can be called by their name with appropriate input arguments.


2. What is module?

A module in Python is a file that contains Python code, usually containing definitions of functions, classes, and variables that can be used in other Python scripts. Modules are imported using the import keyword followed by the name of the module.

Python comes with many built-in modules, and you can also create your own modules to organize your code.


3. What is package?

A package in Python is a collection of related modules that are organized together in a directory hierarchy. Packages are used to structure large Python projects and can contain sub-packages and modules.

Packages are imported in the same way as modules using the import keyword, but you need to specify the full path to the package or module you want to import.

The main difference between a module and a package is that a package is a directory that contains multiple Python files, whereas a module is a single Python file.


4. Define function. Write syntax to define function. Give example of function definition.

A function is a block of reusable code that performs a specific task. Functions take input arguments, process them, and return a result.

They allow us to organize our code into smaller, more manageable units, and make it more readable and modular.

Here is the syntax to define a function in Python:

vros.py
def function_name(arguments):
    # Function body
    return result
  • def keyword is used to define the function
  • function_name is the name of the function
  • arguments are the input parameters that the function takes, which are enclosed in parentheses and separated by commas
  • The function body contains the code that will be executed when the function is called
  • The return statement specifies the value that the function will return.

Here is an example of a function definition that takes two arguments and returns their sum:

vros.py
def add_numbers(a, b):
    sum = a + b
    return sum

This function takes two input arguments, a and b, adds them together, and returns the result. It can be called by its name and passing appropriate values for a and b as shown below:

vros.py
result = add_numbers(5, 7)
print(result) # Output: 12

5. Can a Python function return multiple values? If yes, how it works?

Yes, a Python function can return multiple values by returning them as a tuple. A tuple is a collection of values, separated by commas and enclosed in parentheses.

Here is an example of a function that returns two values:

vros.py
def get_name_and_age():
    name = "John"
    age = 30
    return name, age

This function returns two values, name and age, as a tuple. You can call this function and store the result in two separate variables like this:

vros.py
name, age = get_name_and_age()
print(name) # Output: John
print(age) # Output: 30

6. How function is defined and called in Python.

To define a function in Python, you use the def keyword followed by the function name, a set of parentheses that may contain arguments, and a colon.

The function body is indented under the function definition, and may contain a return statement to return a value from the function. Here is an example:

vros.py
def greet(name):
    return "Hello, " + name + "!"

To call a function, you simply use its name followed by a set of parentheses that may contain arguments. Here is an example:

vros.py
greeting = greet("John")
print(greeting) # Output: "Hello, John!"

This calls the greet function with the argument "John", and stores the result in the greeting variable. The print function then prints the value of greeting.


7. Explain about void functions with suitable examples.

Void functions are functions that do not return any value.

They are used to perform some action or task without returning any data. Void functions are defined using the def keyword and do not have a return statement. Here's an example of a void function:

vros.py
def print_hello():
    print("Hello")

This function simply prints the string "Hello" when it is called. It does not return any value. To call this function, you simply use its name followed by parentheses:

vros.py
print_hello() # Output: Hello

8. What is actual and formal parameter? Explain the difference along with example.

A formal parameter is a variable that is declared in the function definition, while an actual parameter is the value that is passed to the function when it is called.

The formal parameter is also known as the parameter variable, while the actual parameter is also known as the argument.

Here's an example to illustrate the difference between formal and actual parameters:

vros.py
def add_numbers(a, b): #here a and b are formal parameters
    sum = a + b
    return sum
 
result = add_numbers(2, 3) #here 2 and 3 are actual parameters

In the above example, a and b are the formal parameters of the function add_numbers(). When the function is called with the values 2 and 3, these values become the actual parameters or arguments that are passed to the function. The function then calculates the sum of a and b and returns the result.


9. Explain about fruitful functions with suitable examples.

Fruitful functions are functions that return a value or values. They take one or more input arguments and process them to produce a result that is returned to the caller. Here's an example of a fruitful function:

vros.py
def square(x):
    return x * x

This function takes an argument x and returns its square. To call this function, you pass a value to it and store the returned result in a variable:

vros.py
result = square(5)
print(result) # Output: 25

In this example, we call the square() function with the argument 5. The function returns the square of 5, which is 25. We store this result in the variable result and print it to the console.


10. Discuss the difference between local and global variable.

  • Local variables are variables that are declared inside a function and are only accessible within that function's scope.
  • Global variables, on the other hand, are variables that are declared outside of any function and can be accessed from anywhere within the program.

Here's an example to illustrate the difference:

vros.py
x = 10 # global variable
 
def foo():
    y = 5 # local variable
    print(x) # Accessing global variable
    print(y) # Accessing local variable
 
foo() # Output: 10 5
print(x) # Output: 10

In this example, x is a global variable that is accessible from anywhere in the program. y, on the other hand, is a local variable that is only accessible within the foo() function.


11. Explain any five basic operations performed on string.

  • Concatenation: Combining two or more strings using the + operator.
vros.py
str1 = "Hello"
str2 = "World"
result = str1 + " " + str2
print(result)
 
# Output: Hello World
  • Length: Finding the length of a string using the len() function.
vros.py
str1 = "Python is fun!"
length = len(str1)
print(length)
 
# Output: 14
  • Indexing: Accessing individual characters in a string using their index.
vros.py
str1 = "Python is fun!"
print(str1[0]) # Output: P
print(str1[6]) # Output: i
  • Slicing: Extracting a substring from a string using a range of indices.
vros.py
str1 = "Python is fun!"
substring = str1[7:9]
print(substring)
 
# Output: is
  • Formatting: Creating formatted strings using the format() method.
vros.py
name = "Alice"
age = 25
message = "My name is {} and I am {} years old.".format(name, age)
print(message)
 
# Output: My name is Alice and I am 25 years old.

12. Explain math module with its any five functions.

The math module in Python provides a range of mathematical functions that can be used in a program. Some of the functions provided by the math module include:

  • sqrt(): Returns the square root of a number.
vros.py
import math
result = math.sqrt(25)
print(result)
 
# Output: 5.0
  • pow(): Returns the result of raising a number to a power.
vros.py
import math
result = math.pow(2, 3)
print(result)
 
# Output: 8.0
  • sin(): Returns the sine of an angle in radians.
vros.py
import math
result = math.sin(math.pi/2)
print(result)
 
# Output: 1.0
  • floor(): Returns the largest integer less than or equal to a number.
vros.py
import math
result = math.floor(2.7)
print(result)
 
# Output: 2
  • log(): Returns the natural logarithm of a number.
vros.py
import math
result = math.log(10)
print(result)
 
# Output: 2.302585092994046

13. Differentiate between match() and search() function. Explain with example.

The match() and search() functions in Python's re module are used to search for a pattern in a string.

The main difference between the two functions is that match() searches only at the beginning of the string, while search() searches the entire string.

Here's an example to illustrate the difference:

vros.py
import re
 
string = "The quick brown fox jumps over the lazy dog"
 
# Using match() function
result1 = re.match('quick', string)
print(result1) # Output: None
 
# Using search() function
result2 = re.search('quick', string)
print(result2)
 
# Output: <re.Match object; span=(4, 9), match='quick'>

In this example, we are trying to find the word "quick" in the given string. The match() function searches only at the beginning of the string and returns None because "quick" does not appear at the beginning of the string. The search() function searches the entire string and returns a Match object with the details of the first occurrence of "quick" in the string.


14. Explain type conversion of variable in Python.

In Python, type conversion is the process of converting a variable from one data type to another data type. Python supports several built-in data types such as integers, floats, strings, lists, tuples, and dictionaries. The process of converting one data type to another is known as type casting.

There are several built-in functions in Python that are used to convert one data type to another. Here are some of the commonly used functions for type conversion:

  • int(): This function is used to convert a value to an integer.

Example:

vros.py
num = "10"
print(type(num)) # Output: <class 'str'>
num = int(num)
print(type(num)) # Output: <class 'int'>
  • float(): This function is used to convert a value to a float.

Example:

vros.py
num = "10"
print(type(num)) # Output: <class 'str'>
num = float(num)
print(type(num)) # Output: <class 'float'>
  • str(): This function is used to convert a value to a string.

Example:

vros.py
num = 10
print(type(num)) # Output: <class 'int'>
num = str(num)
print(type(num)) # Output: <class 'str'>
  • list(): This function is used to convert a value to a list.

Example:

vros.py
string = "Hello"
print(type(string)) # Output: <class 'str'>
lst = list(string)
print(type(lst)) # Output: <class 'list'>
  • tuple(): This function is used to convert a value to a tuple.

Example:

vros.py
string = "Hello"
print(type(string)) # Output: <class 'str'>
tpl = tuple(string)
print(type(tpl)) # Output: <class 'tuple'>

Type conversion is an important concept in Python as it allows us to work with different data types and perform various operations on them. However, it's important to note that not all types of data can be converted to each other. For example, it's not possible to convert a string that contains alphabets to an integer or float.


15. Write a function that takes single character and prints 'character is vowel’ if it is not vowel 'character is not vowel’ otherwise.

Here's an example Python function that takes a single character as input and prints whether it is a vowel or not:

vros.py
def check_vowel(ch):
    vowels = ['a', 'e', 'i', 'o', 'u']
    if ch in vowels:
        print(f"{ch} is a vowel")
    else:
        print(f"{ch} is not a vowel") #f is used for formatting

In this function, we have defined a list of vowels and then checked whether the input character is present in that list or not. If the character is in the list, it means it is a vowel and the function prints a message saying so. Otherwise, the function prints a message saying that the character is not a vowel.

To call this function, you can pass a single character as input like this:

vros.py
check_vowel('a') # Output: a is a vowel
check_vowel('b') # Output: b is not a vowel

16. Explain various string operations that can be performed using operators in Python.

In Python, various string operations can be performed using operators. Some of the common string operations that can be performed using operators are:

  • Concatenation (+): The concatenation operator (+) is used to combine two or more strings into a single string. For example, "hello" + "world" would result in "helloworld".
  • Repetition (*): The repetition operator (_) is used to repeat a string a certain number of times. For example, "hello" _ 3 would result in "hellohellohello".
  • Indexing ([]): The indexing operator is used to access a specific character or a range of characters in a string. For example, "hello"[0] would result in "h".
  • Slicing ([start:end]): The slicing operator is used to extract a substring from a string. For example, "hello"[1:4] would result in "ell".
  • Comparison (==, !=, >, <, >=, <=): The comparison operators are used to compare two strings based on their lexicographical order.
  • Membership (in, not in): The membership operators are used to check if a character or a substring is present in a string.

17. Explain with an example, how + and * operators work with strings.

Here are examples of how the + and * operators work with strings:

  • Concatenation (*):
vros.py
string1 = "Hello"
string2 = "world"
result = string1 + " " + string2
print(result) # Output: Hello world

In this example, we have two strings "Hello" and "world". We have used the concatenation operator (+) to combine them into a single string "Hello world".

  • Repetition (*):
vros.py
string1 = "Hello"
result = string1 * 3
print(result) # Output: HelloHelloHello

In this example, we have a string "Hello". We have used the repetition operator (*) to repeat it three times, resulting in the string "HelloHelloHello".


18. Explain str.find() function with suitable example.

The str.find() function in Python is used to find the index of the first occurrence of a substring within a string. If the substring is not found in the string, it returns -1. The syntax of the str.find() function is as follows:

vros.py
string.find(substring, start, end)
  • string: The original string in which we want to find the substring.
  • substring: The substring that we want to find in the string.
  • start: Optional parameter that specifies the starting index from where we want to start searching for the substring (default is 0).
  • end: Optional parameter that specifies the ending index till where we want to search for the substring (default is length of string).

Here's an example:

vros.py
string = "hello world"
substring = "world"
index = string.find(substring)
print(index) # Output: 6

In this example, we have a string "hello world" and a substring "world". We have used the str.find() function to find the index of the first occurrence of the substring in the string, which is 6.


19. Define is module? What are the advantages of using module?

In Python, a module is a file containing Python definitions and statements. It can be thought of as a library of functions, classes, and variables that can be used in a program. A module can be imported in other programs, making the code reusable and reducing the amount of code that needs to be written.

The advantages of using modules in Python are:

  • Code reusability: Modules provide a way to reuse code in different programs, reducing the amount of code that needs to be written.
  • Name spacing: Modules provide a way to avoid naming conflicts by encapsulating variables, functions, and classes within a namespace.
  • Improved code organization: Modules provide a way to organize code into logical groups, making it easier to understand and maintain.
  • Easy debugging: Modules can be tested and debugged independently, making it easier to find and fix errors in the code.
  • Enhancing functionality: Modules provide access to pre-built functions and classes, enabling programmers to add new features and functionality to their programs quickly and easily.

20. How to create a module and use it in a python program explain with an example.

To create a module in Python, we can create a new .py file and define functions, classes, or variables in it. Once the module is created, we can import it in other Python programs and use its functionality.

Here's an example of how to create and use a module:

  • Create a new file named example_module.py with the following contents:
vros.py
def add_numbers(a, b):
    return a + b
 
def multiply_numbers(a, b):
    return a * b
 
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
 
    def introduce(self):
        print("My name is", self.name, "and I am", self.age, "years old.")
  • In another Python program, we can import the example_module and use its functions and classes:
vros.py
import example_module
 
# Use the add_numbers function
result = example_module.add_numbers(10, 20)
print("Result of addition:", result)
 
# Use the multiply_numbers function
result = example_module.multiply_numbers(5, 6)
print("Result of multiplication:", result)
 
# Use the Person class
person = example_module.Person("John", 30)
person.introduce()

When we run this program, it will output:

vros.py
Result of addition: 30
Result of multiplication: 30
My name is John and I am 30 years old.

In this example, we have created a module named example_module.py with three definitions: add_numbers(), multiply_numbers(), and Person. We have then imported the example_module in another Python program and used its functions and classes.

To import a module, we use the import statement followed by the name of the module. We can then use the functions and classes in the module by prefixing them with the name of the module followed by a dot (.). For example, to use the add_numbers() function in the example_module, we write example_module.add_numbers().


21. Explain various functions of math module.

The math module is a built-in Python module that provides mathematical functions and constants. Here are some of the most commonly used functions in the math module:

  1. math.sqrt(x): Returns the square root of x. Example: math.sqrt(25) returns 5.0.
  2. math.ceil(x): Returns the smallest integer greater than or equal to x. Example: math.ceil(3.2) returns 4.
  3. math.floor(x): Returns the largest integer less than or equal to x. Example: math.floor(3.8) returns 3.
  4. math.pow(x, y): Returns x raised to the power of y. Example: math.pow(2, 3) returns 8.0.
  5. math.exp(x): Returns the exponential value of x. Example: math.exp(2) returns 7.38905609893065.
  6. math.log(x, base): Returns the logarithm of x with the given base. If base is not specified, returns the natural logarithm of x. Example: math.log(10, 2) returns 3.3219280948873626.
  7. math.radians(x): Converts x from degrees to radians. Example: math.radians(180) returns 3.141592653589793.
  8. math.degrees(x): Converts x from radians to degrees. Example: math.degrees(3.141592653589793) returns 180.0.

These are just a few examples of the many functions available in the math module. By importing and using this module, we can easily perform complex mathematical calculations in our Python programs.


22. List and explain any four built in string manipulation functions supported by python.

Python provides several built-in string manipulation functions to help manipulate and work with strings. Here are four commonly used built-in string manipulation functions:

  1. len(): The len() function returns the length of a string. This function takes a string as an argument and returns the number of characters in the string.

Example: len("hello world") will return 11.

  1. str.upper(): The upper() method converts all the characters in a string to uppercase.

Example: "hello world".upper() will return "HELLO WORLD".

  1. str.lower(): The lower() method converts all the characters in a string to lowercase.

Example: "HELLO WORLD".lower() will return "hello world".

  1. str.replace(old, new): The replace() method replaces all occurrences of a specified substring in a string with a new substring.

Example: "hello world".replace("world", "Python") will return "hello Python".

These are just a few examples of the many built-in string manipulation functions available in Python. By using these functions, we can easily manipulate and transform strings to fit our needs.


23. Explain string slicing in Python. Show with example.

In Python, string slicing refers to the process of selecting a subset of characters from a string based on their position. The syntax for string slicing is string[start:end:step], where start and end are the starting and ending positions (inclusive) of the slice, and step is the number of characters to skip between each selected character. Here's an example:

vros.py
my_string = "Hello, World!"
print(my_string[0:5])    # Output: "Hello"
print(my_string[7:12])   # Output: "World"
print(my_string[0:12:2]) # Output: "Hlo ol"

In the first example, my_string[0:5] selects the characters from position 0 up to (but not including) position 5, which gives us the substring "Hello". In the second example, my_string[7:12] selects the characters from position 7 up to (but not including) position 12, which gives us the substring "World". Finally, in the third example, my_string[0:12:2] selects every other character from position 0 up to (but not including) position 12, which gives us the substring "Hlo ol".

Note that the starting and ending positions are optional, and if they are omitted, Python will assume that we want to start from the beginning or go all the way to the end of the string, respectively. For example, my_string[:5] will give us the same result as my_string[0:5], and my_string[7:] will give us the same result as my_string[7:len(my_string)].


24. Explain the concept of namespaces with an example.

A namespace is a mapping from names to objects. It is used to avoid naming conflicts and to create a hierarchy of names. Namespaces can be thought of as containers that hold the names of objects, along with the objects themselves.

There are three types of namespaces in Python:

  1. Built-in namespace: It contains names of built-in functions, types, and exceptions.
  2. Global namespace: It contains names defined at the top level of a module or declared as global within a function.
  3. Local namespace: It contains names defined within a function.

Here's an example to illustrate the concept of namespaces:

vros.py
x = 10     # global namespace
 
def foo():
    y = 5  # local namespace
    print(x + y)
 
foo()      # Output: 15

In this example, x is defined in the global namespace, while y is defined in the local namespace of the foo() function. When we call the foo() function, it can access x from the global namespace and y from its local namespace.

It's important to note that names can only be resolved within their respective namespace. For example, if we try to access y outside of the foo() function, we will get a NameError because y only exists within the local namespace of foo(). Similarly, if we define another variable x within the foo() function, it will create a new local variable with the same name, which will shadow the global variable x.

Understanding namespaces is important for writing clear and concise code that avoids naming conflicts and follows good programming practices.


25. Write about the concept of scope of a variable in a function.

The scope of a variable in Python refers to the region of the code where the variable is accessible. In other words, it determines where the variable can be used and accessed within the code.

There are two types of variable scopes in Python:

  1. Global scope: Variables defined outside a function have a global scope, meaning they can be accessed from any part of the code, including inside functions.
  2. Local scope: Variables defined inside a function have a local scope, meaning they can only be accessed within that function.

Here's an example to illustrate the concept of scope of a variable in a function:

vros.py
x = 10    # global variable
 
def foo():
    y = 5   # local variable
    print("x inside foo():", x)   # accessing global variable
    print("y inside foo():", y)   # accessing local variable
 
foo()
print("x outside foo():", x)   # accessing global variable outside function
print("y outside foo():", y)   # accessing local variable outside function (will result in an error)

In this example, x is defined in the global scope and can be accessed both inside and outside the foo() function. y, on the other hand, is defined inside the foo() function and can only be accessed within that function. Attempting to access y outside the function will result in a NameError because it is not defined in the global scope.

It's important to note that variables in nested functions can have their own local scope, and they can also access variables from the outer function's scope using the nonlocal keyword. Understanding the concept of variable scope is important for writing clear and maintainable code, and avoiding naming conflicts or other issues that can arise from using variables with overlapping names in different parts of the code.


26. Write about different types of arguments in a function.

In Python, there are several types of arguments that can be passed to a function. These are:

  1. Positional arguments: These are the most common type of arguments, and they are passed to the function in the order that they are defined in the function's parameter list. The number of arguments passed must match the number of parameters defined in the function.
  2. Keyword arguments: These are arguments that are passed to the function by explicitly specifying the parameter name and value, rather than relying on their order. This can be useful for functions that have many parameters, or when you want to provide values for only a subset of the parameters.
  3. Default arguments: These are arguments that have a default value specified in the function definition, and will be used if no value is provided for that argument when the function is called.
  4. Variable-length arguments: These allow you to pass a variable number of arguments to a function. There are two types of variable-length arguments:
  • *args: This is used to pass a variable number of positional arguments to a function. The arguments are passed as a tuple.
  • **kwargs: This is used to pass a variable number of keyword arguments to a function. The arguments are passed as a dictionary.

Here's an example of a function that uses each type of argument:

vros.py
def example_function(positional_arg1, positional_arg2, default_arg="default_value", *args, **kwargs):
    print("Positional argument 1:", positional_arg1)
    print("Positional argument 2:", positional_arg2)
    print("Default argument:", default_arg)
    print("Variable-length positional arguments:", args)
    print("Variable-length keyword arguments:", kwargs)
 
# Call the function with positional arguments only
example_function("Hello", "world")
 
# Call the function with positional and keyword arguments
example_function("Hello", "world", default_arg="custom_value", arg3="value3", arg4="value4")
 
# Call the function with variable-length arguments
example_function("Hello", "world", "value1", "value2", arg3="value3", arg4="value4")

In this example, we define a function example_function() that takes two positional arguments, one default argument, and two variable-length arguments (*args and **kwargs). We then call the function with different combinations of arguments to demonstrate how each type of argument works.


27. What type of parameter passing is used in Python? Justify your answer with sample program.

In Python, parameters are passed by object reference. This means that when a parameter is passed to a function, a reference to the object is passed, rather than a copy of the object itself. Any changes made to the object within the function will affect the original object outside the function as well.

Here's an example to demonstrate this:

vros.py
# Define a function that modifies a list
def modify_list(my_list):
    my_list.append(4)
    print("Inside function:", my_list)
 
# Create a list and call the function with the list as an argument
my_list = [1, 2, 3]
modify_list(my_list)
print("Outside function:", my_list)

In this example, we define a function modify_list() that takes a list as a parameter and appends the value 4 to the list. We then create a list my_list with the values 1, 2, and 3, and call the function with my_list as the argument.

When we run the program, we can see that the output is:

vros.py
Inside function: [1, 2, 3, 4]
Outside function: [1, 2, 3, 4]

This demonstrates that changes made to the list within the function also affect the original list outside the function, because the function is modifying the original object rather than a copy of the object.

Therefore, we can conclude that Python uses object references to pass parameters to functions.


28. Write in brief about anonymous functions.

In Python, anonymous functions are also known as lambda functions. They are a way to create small, one-time-use functions without having to define them with a name. They are particularly useful when you need to pass a simple function as an argument to another function, such as a sorting or filtering function.

The syntax for creating a lambda function is:

vros.py
lambda arguments: expression

Here, arguments are the input arguments for the function, and expression is the output of the function. The resulting lambda function can be assigned to a variable, passed as an argument to another function, or used directly in a statement.

Here's an example that demonstrates the use of a lambda function:

vros.py
# Define a list of numbers
numbers = [1, 2, 3, 4, 5]
 
# Use a lambda function to filter out even numbers
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
 
# Print the result
print(even_numbers)

In this example, we define a list of numbers and use a lambda function with the filter() function to filter out only the even numbers. The lambda function checks if a given number is even by checking if the remainder of the number divided by 2 is 0. The resulting filtered list of even numbers is assigned to the even_numbers variable and printed.

Lambda functions are particularly useful when we need to create small, one-time-use functions that don't need a name or don't need to be reused elsewhere in our code. They can help make our code more concise and easier to read by eliminating the need for unnecessary function definitions.


29. What is the use of islower() and isupper() method?

The islower() and isupper() methods are string methods in Python that are used to check if all the characters in a string are either lowercase or uppercase, respectively. Both methods return a boolean value, either True or False, depending on whether the string meets the condition.

The islower() method checks whether all the alphabetic characters in the string are lowercase, and returns True if they are all lowercase, and False otherwise. Here's an example:

vros.py
string1 = "hello world"
string2 = "Hello World"
 
print(string1.islower())  # True
print(string2.islower())  # False

In this example, string1 contains all lowercase characters, so the islower() method returns True. On the other hand, string2 contains uppercase characters, so the islower() method returns False.

The isupper() method checks whether all the alphabetic characters in the string are uppercase, and returns True if they are all uppercase, and False otherwise. Here's an example:

vros.py
string1 = "HELLO WORLD"
string2 = "Hello World"
 
print(string1.isupper())  # True
print(string2.isupper())  # False

In this example, string1 contains all uppercase characters, so the isupper() method returns True. On the other hand, string2 contains lowercase characters, so the isupper() method returns False.

These methods are useful when we need to check if a string meets certain conditions, such as if it contains only lowercase or uppercase characters.


30. Give the syntax and significance of string functions: title() and capitalize().

The title() and capitalize() are string methods in Python used to capitalize the first letter of each word in a string.

The title() method returns a copy of the string with the first letter of each word capitalized and the rest of the letters in lowercase. Here's the syntax for using the title() method:

vros.py
string = "this is a sample string"
new_string = string.title()
print(new_string)

In this example, the title() method is applied to the string "this is a sample string". The method returns a new string with the first letter of each word capitalized and the rest of the letters in lowercase:

vros.py
This Is A Sample String

The capitalize() method, on the other hand, capitalizes only the first letter of the first word in the string, and converts all other letters to lowercase. Here's the syntax for using the capitalize() method:

vros.py
string = "this is a sample string"
new_string = string.capitalize()
print(new_string)

In this example, the capitalize() method is applied to the string "this is a sample string". The method returns a new string with the first letter of the first word capitalized and the rest of the letters in lowercase:

vros.py
This is a sample string

The title() and capitalize() methods are useful when we need to capitalize the first letter of each word in a string, such as when printing titles or headings. The main difference between the two methods is that title() capitalizes the first letter of each word, while capitalize() capitalizes only the first letter of the first word.


31. What is recursive function? Write a Python program to calculate factorial of a number using recursive function?

A recursive function is a function that calls itself repeatedly until it reaches a base case, which is a condition that stops the recursion. Recursive functions are useful for solving problems that can be broken down into smaller sub-problems that are similar in nature to the original problem.

Here's a Python program to calculate the factorial of a number using a recursive function:

vros.py
def factorial(n):
    if n == 0:
        return 1
    else:
        return n * factorial(n-1)
 
# Test the function
num = 5
fact = factorial(num)
print(f"The factorial of {num} is {fact}")

In this example, the factorial() function takes a single argument n, which is the number whose factorial we want to calculate. The function checks if n is equal to 0, which is the base case for the recursion. If n is 0, the function returns 1, which is the factorial of 0. If n is not 0, the function calculates the factorial of n-1 using the same factorial() function and multiplies it by n.

We then test the function by calling it with num = 5, which calculates the factorial of 5 using recursion. The output of the program is:

vros.py
The factorial of 5 is 120

Note that recursion can lead to very deep function calls and can be less efficient than iterative solutions for some problems. However, it can be a powerful tool for solving certain types of problems.


32. Write a python program to calculate factorial of given number using recursive function.

vros.py
def factorial(n):
    # base case: factorial of 0 is 1
    if n == 0:
        return 1
    # recursive case: calculate factorial of n-1 and multiply by n
    else:
        return n * factorial(n-1)
 
# take user input for the number
num = int(input("Enter a number: "))
 
# call the factorial function and print the result
fact = factorial(num)
print(f"The factorial of {num} is {fact}")

In this program, the factorial() function takes an integer argument n and calculates the factorial of n using recursion. The base case of the recursion is when n is 0, in which case the function returns 1. In the recursive case, the function calculates the factorial of n-1 by calling itself with n-1 as the argument and multiplies the result by n.

We then prompt the user to enter a number and store it in the variable num. We call the factorial() function with num as the argument to calculate the factorial of the number, and we store the result in the variable fact. Finally, we print the result using an f-string.

For example, if the user enters 5 as the number, the output of the program will be:

vros.py
Enter a number: 5
The factorial of 5 is 120

33. Write a python program to find reverse of a given number using user defined function.

vros.py
def reverse_number(num):
    rev = 0
    while num > 0:
        rem = num % 10
        rev = rev * 10 + rem
        num = num // 10
    return rev
 
# take input from user
num = int(input("Enter a number: "))
 
# call the function to reverse the number
rev_num = reverse_number(num)
 
# print the reversed number
print(f"The reverse of {num} is {rev_num}")

In this program, we define a user-defined function called reverse_number(), which takes an integer num as input and returns its reverse. We use a while loop to extract the digits of the number one by one from the right side using the modulo operator (%) and integer division (//). We add each digit to a variable called rev which stores the reverse of the number.

We then prompt the user to enter a number and store it in the variable num. We call the reverse_number() function with num as the argument to calculate the reverse of the number, and we store the result in the variable rev_num. Finally, we print the reversed number using an f-string.

For example, if the user enters 12345 as the number, the output of the program will be:

vros.py
Enter a number: 12345
The reverse of 12345 is 54321

34. Write a Python program that interchanges the first and last characters of a given string.

vros.py
def interchange_first_last(string):
    if len(string) <= 1:
        return string
    else:
        return string[-1] + string[1:-1] + string[0]
 
# take input from user
string = input("Enter a string: ")
 
# call the function to interchange first and last characters
new_string = interchange_first_last(string)
 
# print the new string
print(f"The new string is: {new_string}")

In this program, we define a user-defined function called interchange_first_last(), which takes a string as input and returns a new string with the first and last characters interchanged.

We first check if the length of the string is less than or equal to 1. If it is, we simply return the string as is. Otherwise, we use string slicing to extract the first and last characters of the string and concatenate them with the remaining characters of the string in the middle.

We then prompt the user to enter a string and store it in the variable string. We call the interchange_first_last() function with string as the argument to create a new string with the first and last characters interchanged, and we store the result in the variable new_string. Finally, we print the new string using an f-string.

For example, if the user enters the string "hello" as input, the output of the program will be:

vros.py
Enter a string: hello
The new string is: oellh