Unit 3 and 4 , 2mark Questions

Admin
By -
18 minute read
0

 1. Define recursive function.

In Python, a recursive function is a function that calls itself during its execution. Here's a simple example:

def factorial(n):
    if n == 0 or n == 1:
        return 1
    else:
        return n * factorial(n-1)

This is a recursive function for calculating the factorial of a number. The base case (n == 0 or n == 1) provides the stopping condition for the recursion, preventing an infinite loop.


2.How to create a list in python? Illustrate the use of negative indexing of list with example.

You can create a list in Python using square brackets []. Here's an example:

my_list = [1, 2, 3, 4, 5]

To illustrate negative indexing, consider the following:

# Accessing elements using positive indexing

first_element = my_list[0]  # 1

second_element = my_list[1]  # 2

# Accessing elements using negative indexing

last_element = my_list[-1]   # 5 (last element)

second_last_element = my_list[-2]  # 4 (second-to-last element)

Negative indexing allows you to access elements from the end of the list, with -1 representing the last element, -2 representing the second-to-last element, and so on.



3. Mention the types of arguments in python.

In Python, there are several types of arguments that can be used when defining a function:

  1. positional arguments:
    • These are the most common type of arguments.
    • The values are assigned based on their position in the function call.

def example_function(arg1, arg2):
# Function implementation

     2. Keyword Arguments:

    • Values are passed to a function using the parameter names.

example_function(arg1=value1, arg2=value2)
    3. Default arguments:
    • Parameters in a function can have default values, which are used when the value is not provided in the function call.
def example_function(arg1, arg2=0):
    # Function implementation

    4. Arbitary arguments:

    • In Python, arbitrary arguments refer to the ability of a function to accept a variable number of arguments. This is achieved using the *args syntax, where "args" is a convention, and the * operator is used to allow the function to accept any number of positional arguments.

Here's a simple example:

def my_function(*args):
    for arg in args:
        print(arg)

my_function(1, 2, 3, 'hello')

4. Compare 'return value' and 'composition'.

"Return value" and "composition" in Python are concepts that refer to different aspects of programming:

1. Return value:

  • The return value of a function is the result that the function provides after it has been executed.
  • It is the data or object that a function sends back to the calling code.
  • The return value is specified using the return keyword in a function.
Example:
def add_numbers(a, b):
    return a + b

result = add_numbers(3, 4)  # Here, `result` will be 7, the return value of the function.

2. Composition:

  • Composition, in a broader sense, refers to combining simpler elements to create more complex ones.
  • In the context of software design, composition often involves building complex objects or systems by combining smaller, independent components.
  • It's a way to create relationships between objects without relying on inheritance.
Example:
class Engine:
    def start(self):
        print("Engine started")

class Car:
    def __init__(self):
        self.engine = Engine()

    def start(self):
        print("Car starting...")
        self.engine.start()

my_car = Car()
my_car.start()  # This involves the composition of a `Car` object with an `Engine` object.

In summary, "return value" is related to the output of a function, while "composition" is a broader concept referring to combining simpler elements to create more complex structures or systems. They are not directly comparable, as they address different aspects of programming and design.


5. Define String immutability.

In Python, string immutability refers to the property of strings that once a string is created, its contents cannot be changed or modified. Any operation that appears to modify a string actually creates a new string. Strings in Python are considered immutable objects.

Here's a simple illustration of string immutability:

# Creating a string
original_string = "Hello"

# Attempting to modify the string by changing a character
# This will result in an error because strings are immutable
# original_string[0] = 'J'  # Uncommenting this line will raise a TypeError

# Creating a new string instead
modified_string = 'J' + original_string[1:]

print("Original String:", original_string)  # Output: Original String: Hello
print("Modified String:", modified_string)  # Output: Modified String: Jello

In this example, instead of modifying the original string, a new string is created by concatenating the letter 'J' with the rest of the characters from the original string. This is a common pattern when working with strings in Python.


The immutability of strings has implications for memory management and performance. It ensures the integrity of the original string and avoids unexpected changes. If you need to perform a series of modifications on a string, using other data structures like lists and then converting them back to strings can be a more efficient approach.


6. Define Cloning in list.

In Python, cloning a list refers to creating a new list that is a copy of an existing list. There are various ways to achieve this, and it's important to understand the distinction between a shallow copy and a deep copy.

Here are different methods for cloning a list in Python:

Slicing:

original_list = [1, 2, 3, 4, 5]
cloned_list = original_list[:]

List Constructor:

original_list = [1, 2, 3, 4, 5]
cloned_list = list(original_list)

'copy' module (shallow copy)

import copy

original_list = [1, 2, 3, 4, 5]
cloned_list = copy.copy(original_list)

'copy' module (deep copy)

import copy

original_list = [[1, 2], [3, 4], [5, 6]]
cloned_list = copy.deepcopy(original_list)

It's important to note the difference between a shallow copy and a deep copy:

  • Shallow Copy: Creates a new list, but does not create new objects for the elements within the list. If the list contains mutable objects (e.g., other lists), changes to the mutable objects within the original list will affect the cloned list, and vice versa.
  • Deep Copy: Creates a new list as well as new objects for the elements within the list. Changes to the mutable objects within the original list will not affect the cloned list, and vice versa. Deep copy is necessary when dealing with nested mutable objects.

Choose the method that best fits your requirements based on whether you need a shallow or deep copy.


7. What is the benefits of using tuple assignment in python?

Tuple assignment in Python provides several benefits, making code more readable, concise, and often more efficient. Here are some advantages of using tuple assignment:

1. Conciseness:

  • Tuple assignment allows you to assign multiple variables in a single line, making the code more concise and reducing the number of lines needed.

x, y, z = 1, 2, 3

2. Swapping Values:

  • Tuple assignment provides an elegant way to swap the values of two variables without needing a temporary variable.

a = 5
b = 10
a, b = b, a  # Swapping values
3. Multiple Return Values:
  • Functions can return multiple values as a tuple, and tuple assignment can be used to unpack these values.
def get_coordinates():
    return 3, 4

x, y = get_coordinates()
4. Parallel Assignment:
  • Tuple assignment can be used for parallel assignment, allowing multiple variables to be assigned values at the same time.
name, age, city = "Alice", 30, "Wonderland"
5. Iterable Assignment:

  • Tuple assignment works well with iterable unpacking, allowing you to extract values from iterable objects like lists or strings.

my_list = [1, 2, 3]
a, b, c = my_list


                Overall, tuple assignment is a versatile feature in Python that contributes to code readability, simplicity, and expressive power. 


8. What is Recursion?

In Python, recursion refers to the concept where a function calls itself during its execution. A function that uses recursion is known as a recursive function. The idea is to break down a problem into smaller, more manageable instances and solve them recursively. A recursive function generally has two components:

Base Case:

  • A condition that specifies when the recursion should stop. It defines the simplest version of the problem and provides a result without making further recursive calls.

Recursive Case:

  • The part of the function where it calls itself with a reduced or simpler version of the original problem. This step contributes to breaking down the problem into smaller subproblems.

>> Here's a simple example of a recursive function in Python to calculate the factorial of a non-negative integer:

def factorial(n):
    if n == 0 or n == 1:
        return 1
    else:
        return n * factorial(n-1)

In this example:

  1. The base case is when n is 0 or 1, and the function returns 1.
  2. The recursive case multiplies n with the factorial of n-1, effectively breaking down the problem into smaller subproblems.

When using recursion, it's crucial to have a well-defined base case to prevent infinite recursion. Infinite recursion occurs when the base case is not reached, leading to a stack overflow.


While recursion can be a powerful and elegant approach to problem-solving, it may have performance implications for very deep recursions, and in some cases, iterative solutions might be more efficient. Understanding the nature of the problem and choosing the appropriate technique is essential for writing effective and efficient code.


9. What is a List in Python? Give Examples...

In Python, a list is a versatile and mutable data structure that can hold a collection of elements. Lists are ordered, meaning the elements are stored in a specific order, and they can contain items of different data types. Lists are defined using square brackets [] and elements are separated by commas.


Here are some types of lists given below,.

  1. List of numbers
  2. List of Strings
  3. List of Mixed Data Types
  4. Nested List
  5. Empty List
  6. List with Repetition
  7. List Comprehension

Lists in Python are quite flexible and can be modified after creation. You can add, remove, or modify elements in a list, making them a fundamental and commonly used data structure in Python.


10. Write the Syntax for Concatenating two lists in python.

In Python, you can concatenate two lists using the + operator. Here's the syntax:

new_list = list1 + list2

In this syntax:

  • list1 and list2 are the two lists you want to concatenate.
  • The + operator concatenates the elements of list1 followed by the elements of list2 to create a new list (new_list).
  • Alternatively, you can use the extend() method or the += operator to achieve the same result:
  • Both of these methods modify the original list (list1) in place by adding the elements of list2.


11. Illustrate the use of  *  and  +  operators in string with example.

The * and + operators are used with strings in Python for repetition and concatenation, respectively.

  1. * Operator (Repetition):Example: "Hello" * 3 results in "HelloHelloHello". It repeats the string "Hello" three times.
  2. + Operator (Concatenation):Example: "Hello" + " " + "World" results in "Hello World". It concatenates the strings "Hello," a space, and "World."
These operators provide flexibility when working with strings, allowing you to repeat or combine them as needed.

12. Comment with an example on the local and global variable with the same identifier name.

In Python, you can have both local and global variables with the same identifier name. The variable scope determines which variable is being referred to in a particular part of the code. Here's an example to illustrate this concept:

# Global variable
identifier_name = "Global Variable"

def example_function():,
    # Local variable with the same identifier name as the global variable
    identifier_name = "Local Variable"
    
    # Accessing the local variable
    print("Inside the function:", identifier_name)

# Call the function
example_function()

# Accessing the global variable outside the function
print("Outside the function:", identifier_name)
Output:
Inside the function: Local Variable
Outside the function: Global Variable

This demonstrates the concept of variable scope, where the local variable inside the function takes precedence over the global variable with the same name within the function's scope.


13. Define Fruitful function in Python.

In Python, a fruitful function is a function that returns a value. Unlike void functions, which perform a task but do not produce a result, fruitful functions are designed to compute and return a value that can be used elsewhere in the program.

Here's an example of a fruitful function in Python:

def add_numbers(x, y):
    """
    This function takes two parameters, x and y,
    and returns their sum.
    """
    result = x + y
    return result

# Call the function and store the result in a variable
sum_result = add_numbers(5, 3)

# Print the result
print("Sum:", sum_result)
Output:
Sum:8
In this example, the add_numbers function takes two parameters (x and y), calculates their sum, and returns the result using the return keyword. When the function is called with arguments 5 and 3, the result is stored in the variable sum_result, and the final sum is printed.

This is a simple illustration, but fruitful functions can perform complex computations and return various types of values, such as numbers, strings, lists, or even custom objects. The key is that they produce a result that can be used elsewhere in the program.


14. Relate string and list.

In Python, strings and lists share some similarities because they are both sequences, but they also have distinct differences. Here are some ways in which strings and lists are related:

1.Sequential Data Types:

  • Both strings and lists are sequential data types, meaning they represent an ordered collection of elements.

  • 2. Indexing:
    • You can access individual elements of a string or a list using indexing. The first element has index 0, the second has index 1, and so on.
    my_string = "Hello"
    my_list = [1, 2, 3, 4]
    
    print(my_string[0])  # Output: 'H'
    print(my_list[1])    # Output: 2
    3.Slicing:
    • Both strings and lists support slicing, allowing you to extract a portion of the sequence.
    4. Iterability:
    • You can iterate over the elements of a string or a list using loops.
    5. Mutability:
    • Strings in Python are immutable, meaning you cannot change individual characters once the string is created. In contrast, lists are mutable, and you can modify, add, or remove elements.
    6. Type of Elements:
    • Strings are sequences of characters, while lists can hold elements of any data type, including other lists or complex objects.

    Understanding these similarities and differences helps in choosing the appropriate data type based on the requirements of your program. If you need an ordered collection of characters, a string might be more appropriate. If you need a mutable, ordered collection of diverse elements, a list is a better choice.


    16. Name the two types of iterative statements supported by python.

    In Python, there are two types of iterative statements (or loops): for and while. These statements allow you to repeatedly execute a block of code, making it easier to work with repet,itive tasks.

    1. 'for' loop:

    • The for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string) or other iterable objects.
    fruits = ['apple', 'banana', 'cherry']
    for fruit in fruits:
        print(fruit)
    Output:
    apple
    banana
    cherry
    2. 'while' loop:
    • The while loop is used for repeated execution of a block of statements as long as the condition specified in the loop remains true.
    count = 0
    while count < 5:
        print(count)
        count += 1

    Both for and while loops are fundamental to controlling the flow of a program and are used in various situations to automate repetitive tasks or perform iterations based on certain conditions.


    17. How the value stored in a list are accesed? Should the elements of a list be of the same data type.

    In Python, you can access the values stored in a list using indexing. Lists are ordered collections of elements, and each element in a list has a unique index. The index starts at 0 for the first element, 1 for the second element, and so on.

    Here's an example of how to access values in a list:

    my_list = [10, 20, 30, 40, 50]
    
    # Accessing individual elements using indexing
    first_element = my_list[0]      # 10
    second_element = my_list[1]     # 20
    third_element = my_list[2]      # 30
    
    # Negative indexing can be used to access elements from the end of the list
    last_element = my_list[-1]      # 50
    second_last_element = my_list[-2]  # 40

    Regarding the data type of elements in a list, Python allows lists to contain elements of different data types. Unlike some other programming languages, Python lists are heterogeneous, meaning the elements can be of various types. For example:

    mixed_list = [1, 'two', 3.0, [4, 5]]
    
    # Elements can be integers, strings, floats, and even other lists

    So, it is not necessary for the elements in a list to be of the same data type. Python provides flexibility in this regard, allowing you to create versatile and dynamic lists that can hold different types of data.


    18. How to slice a list in python.

    In Python, you can use slicing to extract a portion of a list. Slicing allows you to create a new list containing a subset of the original list. The general syntax for slicing a list is as follows:

    new_list = original_list[start:stop:step]
  • start: The index of the first element you want to include in the slice (inclusive).
  • stop: The index of the first element you want to exclude from the slice (exclusive).
  • step (optional): The step or stride between elements. If not provided, it defaults to 1.
  • Here are some examples:

    my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    
    # Slicing from index 2 to 5 (exclusive)
    slice_1 = my_list[2:5]
    print(slice_1)  # Output: [2, 3, 4]
    
    # Slicing from the beginning to index 7 (exclusive)
    slice_2 = my_list[:7]
    print(slice_2)  # Output: [0, 1, 2, 3, 4, 5, 6]
    
    # Slicing from index 3 to the end
    slice_3 = my_list[3:]
    print(slice_3)  # Output: [3, 4, 5, 6, 7, 8, 9]
    
    # Slicing with a step of 2
    slice_4 = my_list[1:8:2]
    print(slice_4)  # Output: [1, 3, 5, 7]

    Remember that when slicing, the original list remains unchanged, and a new list is created with the specified elements. Additionally, if you omit start, stop, or step, the default values are used (start defaults to the beginning, stop defaults to the end, and step defaults to 1).


    19. Present the flow of execution for a while statement.

    The flow of execution for a while statement in Python is as follows:

    1. Evaluate the Condition:

    • The condition specified in the while statement is evaluated. If the condition is True, the block of code inside the while loop is executed. If the condition is False initially, the loop is skipped, and the program proceeds to the next statement after the while block.

    2. Execute the Code Inside the Loop:

    • If the condition is True, the code inside the while loop is executed. This block of code can contain one or more statements.

    3. Re-evaluate the Condition:

    • After executing the code inside the loop, the condition is re-evaluated. If the condition is still True, the loop goes back to step 2 and repeats. If the condition is now False, the program exits the while loop, and control moves to the next statement after the while block.

    4. Repeat or Exit:

    • Steps 2 and 3 are repeated until the condition becomes False. Once the condition is False, the while loop is exited, and the program continues with the next statement after the while block.

    Here's a simple example to illustrate the flow of execution for a while statement:

    count = 0
    
    while count < 5:
        print("Count:", count)
        count += 1
    
    print("End of program")
    Output:
    
    Count: 0
    Count: 1
    Count: 2
    Count: 3
    Count: 4
    End of program
    

    In this example, the while loop will iterate as long as the count is less than 5. The flow of execution involves checking the condition, executing the loop body, updating the count variable, and repeating until the condition is no longer true. 


    20. State the reason to divide program into functions.

    Dividing a program into functions provides several benefits, contributing to better code organization, readability, and maintainability. Here are some key reasons to divide a program into functions:

    1. Modularity:

    • Functions allow you to break down a large and complex program into smaller, more manageable modules. Each function can represent a specific task or functionality, making it easier to understand and maintain.
    2. Code Reusability:
    • Once you've defined a function for a specific task, you can reuse that function in different parts of your program or even in other programs. This promotes code reusability and reduces redundancy.
    3. Readability:
    • Dividing a program into functions enhances code readability. Instead of having a long, monolithic block of code, functions provide a clear structure, and each function can be understood in isolation. This makes it easier for you and others to comprehend the logic of the program.
    4. Abstraction:
    • Functions provide a level of abstraction. When you call a function, you don't necessarily need to know how it's implemented internally; you only need to understand its input parameters and the result it produces. This abstraction allows you to focus on the high-level functionality without getting bogged down by implementation details.
    5. Testing and Debugging:
    • Functions simplify testing and debugging. Since each function performs a specific task, you can test and debug individual functions independently. This isolation makes it easier to identify and fix issues without affecting the entire program.
    6. Collaboration:
    • In collaborative development, dividing a program into functions facilitates teamwork. Different team members can work on different functions concurrently, and as long as the functions' interfaces remain consistent, integration becomes smoother.
    7. Scoping and Variable Isolation:
    • Functions introduce scope in Python, which means variables defined within a function are local to that function. This helps prevent naming conflicts and unintended side effects by isolating variables to the specific function where they are needed.

    8. Maintainability:

    • Programs with well-defined functions are generally easier to maintain over time. When changes or updates are required, you can focus on the specific function that needs modification, rather than navigating through a large, monolithic codebase.

    In summary, dividing a program into functions promotes modularity, code reusability, readability, and maintainability, contributing to the overall quality and efficiency of software development.



    Post a Comment

    0Comments

    Post a Comment (0)

    #buttons=(Ok, Go it!) #days=(20)

    Our website uses cookies to enhance your experience. Learn more
    Ok, Go it!