Explain Lambda function with a suitable example.
A *lambda function* in Python is a small, anonymous function defined using the lambda keyword.
It can take any number of arguments but can only have one expression.
### Syntax # Lambda function to add 10 to a given
number
python
add_ten = lambda x: x + 10
lambda arguments: expression
# Using the lambda function
### Example
print(add_ten(5)) # Output: 15
python
In this example, add_ten is a lambda function that takes one argument x and returns x + 10. When
we call add_ten(5), it returns 15.
### Use Case
Lambda functions are often used in situations where you need a small function for a short period
of time, such as in functional programming constructs like map, filter, and reduce.
Write a Python program to find the substrings within a string
python [Link](s[i:j])
def find_substrings(s): return substrings
substrings = [] # Example usage
length = len(s) input_string = "abc"
# Generate all possible substrings result = find_substrings(input_string)
for i in range(length): print("All substrings:", result)
for j in range(i + 1, length + 1):
### Explanation
1. *Function Definition*: The function find_substrings(s) takes a string s as input.
2. *Initialization*: An empty list substrings is initialized to store all substrings.
3. *Nested Loops*: Two nested loops are used to generate all possible substrings:
- The outer loop iterates over the starting index i.
- The inner loop iterates over the ending index j, ensuring j is always greater than i.
4. *Appending Substrings*: Each substring s[i:j] is appended to the substrings list.
5. *Return*: The function returns the list of all substrings.
Write a Python program to find Reverse of given number using user defined function.
python n = n // 10
def reverse_number(n): return reversed_num
reversed_num = 0 # Example usage
while n > 0: number = int(input("Enter a number: "))
remainder = n % 10 result = reverse_number(number)
reversed_num = reversed_num * 10 + print("Reversed number:", result)
remainder
### Explanation
1. *Function Definition*: The function reverse_number(n) takes an integer n as input.
2. *Initialization*: A variable reversed_num is initialized to 0 to store the reversed number.
3. *While Loop*: The loop runs as long as n is greater than 0:
- *Remainder Calculation*: The last digit of n is obtained using n % 10.
- *Reversing*: The last digit is added to reversed_num after shifting its digits to the left by
multiplying by 10.
- *Removing Last Digit*: The last digit is removed from n using integer division n // 10.
4. *Return*: The function returns the reversed number.
Briefly describe the methods of Regular Expression.
Regular expressions (regex) are powerful tools for pattern matching and text manipulation.
1. [Link]()- *Purpose*: Checks for a match only at the beginning of the string.
Python - import re -pattern = r"hello" - result = [Link](pattern, "hello world")
print(result) # Output: <[Link] object; span=(0, 5), match='hello'>
2. [Link]()- *Purpose*: Searches the string for a match and returns the first match it finds.
Python- import re - pattern = r"world" - result = [Link](pattern, "hello world")
print(result) # Output: <[Link] object; span=(6, 11), match='world'>
3. [Link]()- *Purpose*: Returns a list of all matches in the string.
Python- import re- pattern = r"\d+" - result = [Link](pattern, "There are 2 apples and 5
oranges")- print(result) # Output: ['2', '5']
4. [Link]()- *Purpose*: Returns an iterator yielding match objects for all matches.
Python- import re- pattern = r"\d+"- matches = [Link](pattern, "There are 2 apples and 5
oranges")
Explain Classical Cipher in Python with Example.
Classical ciphers are traditional methods of encrypting and decrypting messages. One of the
simplest and most well-known classical ciphers is the *Caesar Cipher*. It involves shifting each
letter in the plaintext by a fixed number of positions down the alphabet.
python result += chr((ord(char) + shift - 97) %
26 + 97)
def caesar_cipher(text, shift):
else:
result = ""
result += char # Non-alphabetic
# Traverse the text
characters remain unchanged
for char in text:
return result
# Encrypt uppercase characters
plaintext = "Hello, World!"
if [Link]():
shift = 3
result += chr((ord(char) + shift - 65) %
ciphertext = caesar_cipher(plaintext, shift)
26 + 65)
print("Plaintext:", plaintext)
# Encrypt lowercase characters
print("Ciphertext:", ciphertext)
elif [Link]():
Explain Exception Handling in Python with Example.
Exception handling in Python is a way to handle errors gracefully and ensure the program can
continue running or terminate cleanly. The primary keywords used for exception handling are try,
except, else, and finally.
python
try: else:
# Code that might raise an exception # Code to run if no exception occurs
except ExceptionType: finally:
# Code to handle the exception # Code to run no matter what (optional)
Example
python except TypeError:
def divide_numbers(a, b): print("Error: Both arguments must be
numbers.")
try:
else:
result = a / b
print(f"The result is {result}")
except ZeroDivisionError:
finally: print("Execution completed."
print("Error: Cannot divide by zero.")
Explain List and Tuple in Python.
Lists - *Mutable*: Lists can be modified after Tuples - *Immutable*: Tuples cannot be
creation (i.e., you can add, remove, or change modified after creation .
items).
- *Syntax*: Defined using parentheses ().
- *Syntax*: Defined using square brackets [].
python
python
my_tuple = (1, 2, 3, 4)
my_list = [1, 2, 3, 4]
# my_tuple[0] = 5 # This would raise a
my_list.append(5) # Adds 5 to the list TypeError
print(my_list) # Output: [1, 2, 3, 4, 5] print(my_tuple) # Output: (1, 2, 3, 4)
Key Differences 1. *Mutability*: Lists are mutable, while tuples are immutable¹².
2. *Syntax*: Lists use square brackets [], while tuples use parentheses `()`².
3. *Performance*: Tuples can be slightly faster than lists due to their immutability³.
4. *Use Cases*:
- *Lists*: Suitable for collections of items that may change (e.g., a list of tasks).
- *Tuples*: Suitable for collections of items that should not change (e.g., coordinates of a point).
Write a note on Tkinter widget: Entry, Menu , Text , Button , menu , menu buttons.
1. Entry- *Purpose*: The Entry widget is used to create a single-line text input field
Python - from tkinter import Tk, Entry - root = Tk() -entry = Entry(root) - [Link]()
[Link]()
2. Menu- *Purpose*: The Menu widget is used to create a menu bar at the top of the window,
which can contain multiple submenus and commands.
python filemenu.add_command(label="Open")
from tkinter import Tk, Menu filemenu.add_command(label="Save")
root = Tk() menubar.add_cascade(label="File",
menu=filemenu)
menubar = Menu(root)
[Link](menu=menubar)
filemenu = Menu(menubar, tearoff=0)
[Link]()
3. Text- *Purpose*: The Text widget is used to create a multi-line text input field.
Python - from tkinter import Tk, Text - root = Tk() - text = Text(root) - [Link]()
[Link]()
4. Button- *Purpose*: The Button widget is used to create a clickable button.
Python - from tkinter import Tk, Button def on_click(): - print("Button clicked!")
root = Tk() - button = Button(root, text="Click Me", command=on_click)
[Link]()- [Link]()
5. Menu Button- *Purpose*: The Menubutton widget is a button that, when clicked, displays a
menu.
python
from tkinter import Tk, Menubutton, Menu
root = Tk()
menubutton = Menubutton(root, text="Menu Button")
[Link]()
menu = Menu(menubutton, tearoff=False)
menu.add_command(label="Option 1")
menu.add_command(label="Option 2")
[Link](menu=menu) [Link]()
Write a python program that shows the concept of Inheritance
python
# Define the parent class
class Animal:
def __init__(self, name):
[Link] = name
def eat(self):
print(f"{[Link]} is eating.")
# Define the child class that inherits from Animal
class Dog(Animal):
def bark(self):
print(f"{[Link]} is barking.")
# Create an instance of the Dog class
my_dog = Dog("Buddy")
# Call methods from both the parent and child class
my_dog.eat() # Inherited from Animal class my_dog.bark() # Defined in Dog class
Is String a mutable data type? Also explain the string operations length, indexing and
slicing in detail with small example
once a string is created, its content cannot be changed. If you try to modify a string, a new string
object is created instead.
1. Length The len() function is used to find the length of a string, which is the number of
characters it contains.
Python - my_string = "Hello, World!" - print(len(my_string)) # Output: 13
2. Indexing Indexing allows you to access individual characters in a string using their position
(index). Python uses zero-based indexing, so the first character has an index of 0.
Python - my_string = "Hello, World!" - print(my_string[0]) # Output: H -print(my_string[7]) #
Output: W - print(my_string[-1]) # Output: !
3. Slicing Slicing allows you to obtain a substring by specifying a start and end index. The syntax
is string[start:end], where start is inclusive and end is exclusive.
Python - my_string = "Hello, World!" - print(my_string[0:5]) # Output: Hello -
print(my_string[7:12]) # Output: World -print(my_string[:5]) # Output: Hello -
print(my_string[7:]) # Output: World! -print(my_string[:]) # Output: Hello, World!
Discuss Encryption and Decryption Method in python for data security.
Encryption and decryption are essential techniques for securing data. In Python, there are several
libraries available for implementing these methods. Here, I'll discuss two popular methods:
*Fernet symmetric encryption* and *AES encryption* using the cryptography and pycryptodome
libraries, respectively.
1. Fernet Symmetric Encryption - Fernet is a part of the cryptography library and provides
easy-to-use symmetric encryption. Symmetric encryption means the same key is used for both
encryption and decryption.
Bash - pip install cryptography
2. AES Encryption - AES (Advanced Encryption Standard) is a widely used encryption standard.
The pycryptodome library provides a comprehensive collection of cryptographic modules,
including AES.
Bash - pip install pycryptodome
Which are the different types of operators in python language? Explain membership and
identity operators with examples.
1. *Arithmetic Operators*: Perform mathematical operations like addition, subtraction,
multiplication, etc.
2. *Comparison (Relational) Operators*: Compare values and return a boolean result.
3. *Assignment Operators*: Assign values to variables.
4. *Logical Operators*: Perform logical operations like AND, OR, and NOT.
5. *Bitwise Operators*: Perform bit-level operations.
6. *Membership Operators*: Test for membership in a sequence.
7. *Identity Operators*: Compare the memory locations of two objects.
Membership Operators - Membership operators are used to test if a sequence is present in an
object. The two membership operators are:
- in: Returns True if a sequence with the specified value is present in the object.
- not in: Returns True if a sequence with the specified value is not present in the object.
Identity Operators - Identity operators are used to compare the memory locations of two
objects. The two identity operators are:
- is: Returns True if both variables point to the same object.
- is not: Returns True if both variables do not point to the same object.
How to define a class method and a static method?
Class Method - A class method is a method that is bound to the class and not the instance of the
class. It can modify the class state that applies across all instances of the class.
python @classmethod
class MyClass: def class_method(cls):
class_variable = 0 cls.class_variable += 1
def __init__(self, instance_variable): print(f"Class variable is now
{cls.class_variable}")
self.instance_variable = instance_variable
Static Method - A static method is a method that does not operate on an instance or the class
itself. It is defined using the @staticmethod decorator and does not take self or cls as the first
parameter. Static methods are used to perform utility functions.
Python (class MyClass: )
@staticmethoD def static_method (param1, param2): return param1 + param2
What is constructor? Explain with example various types of constructors in python.
A constructor in Python is a special method used to initialize the attributes of an object when it is
created. The constructor method is called __init__(), and it is automatically invoked when an
object of the class is instantiated.
1. Default Constructor - A default constructor is a constructor that does not accept any
arguments except self. It initializes the object with default values.
Python - class DefaultConstructor: - def __init_(self):-[Link] = "This is a default constructor"
2. Non-Parameterized Constructor - A non-parameterized constructor is similar to the default
constructor but is explicitly defined without any parameters other than self.
Python - class NonParameterizedConstructor - def __init__(self): - [Link] = 42
3. Parameterized Constructor - A parameterized constructor accepts arguments in addition to
self and uses them to initialize the object's attributes.
Python - class ParameterizedConstructor:- def __init__(self, name, age): - [Link] = name self.
What is the difference between error and exception? Explain exception handling in python
with example.
- *Errors* are typically caused by fundamental problems in the program or system, such as out-
of-memory errors or stack overflow. They are usually unrecoverable and can lead to the
termination of the program².
- *Exceptions* are unexpected events that occur during the program's execution but can be
handled and recovered from. They allow for graceful error handling and can prevent the program
from crashing².
Exception Handling in Python result = numerator / denominator
python print(result)
try: except ZeroDivisionError:
numerator = 10 print("Error: Denominator cannot be 0.")
denominator = 0
Explain map, reduce and filter in python with example.
1. map() = The map() function applies a given function to all items in an input list (or any other
iterable) and returns a map object (an iterator).
python uppercased_fruits = map([Link], fruits)
# Convert a list of strings to uppercase print(list(uppercased_fruits)) # Output:
['APPLE', 'BANANA', 'CHERRY']
fruits = ['apple', 'banana', 'cherry']
2. filter() - The filter() function constructs an iterator from elements of an iterable for which a
function returns true.
python even_numbers = filter(lambda x: x % 2 == 0,
numbers)
# Filter out even numbers from a list
print(list(even_numbers)) # Output: [2, 4, 6]
numbers = [1, 2, 3, 4, 5, 6]
3. reduce() - The reduce() function applies a rolling computation to sequential pairs of values in
a list. It is part of the functools module.
python numbers = [1, 2, 3, 4]
from functools import reduce product = reduce(lambda x, y: x * y, numbers)
# Compute the product of a list of numbers print(product) # Output: 24
Compare method overloading and overriding in python.
Method Overloading refers to defining multiple methods with the same name but different
parameters within the same class. However, Python does not support method overloading in the
traditional sense as seen in languages like Java or C++. Instead, you can achieve similar
functionality using default arguments or variable-length arguments.
python else:
class MyClass: print(a)
def my_method(self, a, b=None): obj = MyClass()
if b is not None: obj.my_method(10) # Output: 10
print(a + b) obj.my_method(10, 20) # Output: 30
Method overriding occurs when a subclass provides a specific implementation of a method that
is already defined in its superclass. The method in the subclass should have the same name and
parameters as the method in the superclass.
python def speak(self):
class Animal: print("Dog barking")
def speak(self): obj = Dog()
print("Animal speaking") [Link]() # Output: Dog barkin
class Dog(Animal):
Write a python program to implement is Palindrome() function to check given string is
palindrome or no.
Certainly! A palindrome is a string that reads the same forward and backward. Here's a simple
Python program that implements the is_palindrome() function to check if a given string is a
palindrome:
python # Test the function
def is_palindrome(s): if __name__ == "__main__":
# Normalize the string by removing spaces test_strings = ["A man a plan a canal
and converting to lowercase Panama", "Hello", "Racecar", "Python"]
normalized_str = ''.join([Link]()).lower() for string in test_strings:
# Check if the string is equal to its if is_palindrome(string):
reverse
print(f'"{string}" is a palindrome.')
return normalized_str ==
else:
normalized_str[::-1]
print(f'"{string}" is not a palindrome.')
Which are the different ways of creation of threads? Explain each with an example.
1. Using the threading Module a. Creating a Thread by Instantiating Thread Class
You can create a thread by instantiating the Thread class and passing a target function to it.
python thread =
[Link](target=print_numbers)
import threading
# Start the thread
def print_numbers():
[Link]()
for i in range(5):
# Wait for the thread to complete
print(i)
[Link]()
# Create a thread
2. Using the _thread Module
The _thread module provides a lower-level interface for working with threads.
Example: print(f"{thread_name}: {i}")
python # Create two threads
import _thread _thread.start_new_thread(print_numbers,
("Thread-1", 1))
import time
_thread.start_new_thread(print_numbers,
def print_numbers(thread_name, delay):
("Thread-2", 2))
for i in range(5):
# Keep the main thread alive
[Link](delay)
[Link](10)
Report the string operations length, indexing and slicing in detail with an appropriate
example.
1. Length - The length of a string can be obtained using the built-in len() function. This function
returns the number of characters in the string, including spaces and punctuation.
python length = len(string)
string = "Hello, World!" print(f"The length of the string is: {length}")
2. Indexing In Python, strings are indexed starting from 0. You can access individual characters in
a string using their index. Negative indexing allows you to count from the end of the string .
python last_char = string[-1] # Last character
string = "Hello, World!" print(f"First character: {first_char}")
first_char = string[0] # First character print(f"Last character: {last_char}")
3. Slicing
Slicing allows you to extract a substring from a string. The syntax for slicing is
string[start:end:step], where:
- start is the index where the slice starts (inclusive).
- end is the index where the slice ends (exclusive).
- step is the interval at which to take elements (optional).
Recall a recursion to generate the Fibonacci series.
Certainly! The Fibonacci series is a sequence where each number is the sum of the two preceding
ones, typically starting with 0 and 1. The sequence looks like this: 0, 1, 1, 2, 3, 5, 8, 13, ...
python series = fibonacci(n - 1)
def fibonacci(n): [Link](series[-1] + series[-2])
if n <= 0: return series
return []
elif n == 1: # Test the function
return [0] num_terms = 10
elif n == 2: fib_series = fibonacci(num_terms)
return [0, 1] print(f"Fibonacci series with {num_terms}
terms: {fib_series}")
else:
Output When you run this code with num_terms set to 10, it produces: Fibonacci series with 10
terms: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
Summarize Tuples, Lists and Dictionaries with example.
1. Tuples - Tuples are immutable sequences, meaning that once they are created, their elements
cannot be changed, added, or removed. They are typically used to store related pieces of data.
- *Syntax*: Created using parentheses ().
python my_tuple = (1, 2, 3, 'a', 'b')
# Creating a tuple print(my_tuple)
2. Lists - Lists are mutable sequences, meaning that they can be changed after creation. They are
commonly used to store collections of items.
- *Syntax*: Created using square brackets [].
python my_list = [1, 2, 3, 'a', 'b']
# Creating a list print(my_list)
3. Dictionaries - Dictionaries are mutable mappings that store key-value pairs. They are
unordered collections, and the keys must be unique.
- *Syntax*: Created using curly braces {} with keys and values separated by colons.
python my_dict = {'name': 'Alice', 'age': 25, 'city':
'New York'}
# Creating a dictionary
print(my_dict)
List built-in data types of python.
Python has several built-in data types that are essential for programming. Here’s a list of the most
commonly used built-in data types:
1. Numeric Types - *int*: Represents integers (whole numbers). Python a = 10
- *float*: Represents floating-point numbers (decimal numbers) b = 3.14
- *complex*: Represents complex numbers, with a real and imaginary part. c = 2 + 3j
2. Sequence Types - *str*: Represents strings, which are sequences of characters. text = "Hello,
World! - *list*: Represents mutable sequences of elements (can contain mixed types) my_list =
[1, 2, 3, 'a', 'b'] - *tuple*: Represents immutable sequences of elements. my_tuple = (1, 2, 3)
- *Numeric Types*: int, float, complex
- *Sequence Types*: str, list, tuple
- *Mapping Type*: dict
- *Set Types*: set, frozenset
- *Boolean Type*: bool
- *None Type*: NoneType
Demonstrate Stack and Queue in Python with Example.
1. Stack (LIFO - Last In, First Out) - A stack is a data structure where the last item added is the
first one to be removed. It follows the principle of LIFO (Last In, First Out). In Python, you can use
a list to implement a stack, using append() to push an item and pop() to remove the last item.
# Stack implementation [Link](3) print("Stack after pop:",
using list stack)
print("Stack after pushes:",
stack = [] stack) Output:
# Adding elements to the # Removing elements from Stack after pushes: [1, 2, 3]
stack (Push) the stack (Pop)
Popped element: 3
[Link](1) print("Popped element:",
Stack after pop: [1, 2]
[Link]())
[Link](2)
2. Queue (FIFO - First In, First Out) - A queue is a data structure where the first item added is
the first one to be removed. It follows the principle of FIFO (First In, First Out). In Python, you can
use [Link] to implement a queue, using append() to enqueue an item and popleft() to
dequeue.
from collections import [Link](2) print("Queue after
deque dequeue:", list(queue))
[Link](3)
# Queue implementation Output:
print("Queue after
using deque
enqueues:", list(queue)) Queue after enqueues: [1, 2,
queue = deque() 3]
# Removing elements from
# Adding elements to the the queue (Dequeue) Dequeued element: 1
queue (Enqueue)
print("Dequeued element:", Queue after dequeue: [2, 3]
[Link](1) [Link]())
Develop a Python program to Demonstrate Multithreading.
import threading def print_letters(): thread2 =
[Link](target=pr
import time for letter in 'abcde':
int_letters)
# Function to print print(f"Letter:
# Starting the threads
numbers {letter}")
[Link]()
def print_numbers(): [Link](1)
[Link]()
for i in range(1, 6): # Creating threads for each
function # Waiting for both threads
print(f"Number: {i}")
to complete
thread1 =
[Link](1)
[Link](target=pr [Link]()
# Function to print letters int_numbers)
[Link]()
Define compiler and Interpreter? Explain how python interpreter works.
A compiler and an interpreter are both programs that translate high-level programming code
(like C, Java, or Python) into machine code that a computer can understand. However, they differ
in how they handle the translation:
Compiler - A compiler translates the entire high-level code into machine code or an intermediate
form (such as bytecode) at once before executing it.
The process of compilation is done beforehand, and if there are errors, the code won’t execute
until the errors are corrected.
Compilers generally produce an independent executable file that can be run multiple times
without the need for recompilation.
Examples of compiled languages include C, C++, and Rust.
Interpreter - An interpreter translates high-level code into machine code line-by-line or
statement-by-statement and executes it immediately.
It translates and executes simultaneously, which means the code can be executed as soon as the
interpreter encounters it. Interpreters do not produce an independent executable file; the
interpreter must be present each time the code is run.
1. Source Code to Bytecode:
2. Bytecode Execution by the Python Virtual Machine (PVM):
3. Just-In-Time (JIT) Compilation (Optional):
Compare append () and extend () are different with reference to list in Python.
1. append() Functionality: The append() method adds its argument as a single element to the
end of the list. Effect on List: The list increases in length by one, regardless of the type or size of
the argument
my_list = [1, 2, 3] print(my_list) # Output: [1, 2, 3, [4, 5]]
my_list.append([4, 5])
2. extend() Functionality: The extend() method adds all elements from the given iterable (e.g., a
list, tuple, or string) to the list individually, not as a single element. Effect on List: The list
increases in length by the number of elements in the iterable.
my_list = [1, 2, 3] print(my_list) # Output: [1, 2, 3, 4, 5]
my_list.extend([4, 5])
1. append() adds the entire object as a single element, while extend() adds each element from the
iterable individually.
2. append() increases the length of the list by 1 (since it adds a single object), whereas extend()
increases the length by however many elements are in the iterable.
What are the differences between C and Python?
1. Syntax and Readability C: C has a more complex syntax, involving a lot of curly braces {},
semicolons ;, and data type declarations.
Python: Python has a simple and readable syntax, using indentation to define code blocks instead
of braces. It's designed to be easy to read and write, making it more accessible for beginners.
2. Level of Abstraction C: C is a low-level language, meaning it is closer to machine code and
provides direct access to memory through pointers.
Python: Python is a high-level language that abstracts away many details of the computer system.
It handles memory management automatically and does not use pointers explicitly.
3. PerformancE C: C is generally much faster than Python because it is compiled directly into
machine code.
Python: Python is an interpreted language, which usually makes it slower than C. However,
Python is optimized for productivity and ease of development.
4. Memory Managemen C: C requires manual memory management using functions like
malloc() and free().
Python: Python has automatic memory management with garbage collection, meaning it
automatically handles memory allocation and deallocation.
Explain while loop & for loop with syntax and example in detail. (In term of python)
1. While Loop The while loop repeatedly executes a block of code as long as a specified condition
is true. It’s typically used when the number of iterations isn’t known in advance.
Syntax: while condition: Let’s print numbers from 1 to 5 using a while
loop:
# Code to execute repeatedly
count = 1
# Optional: update condition to avoid
infinite loop while count <= 5:
condition: This is a Boolean expression. If it print(count)
evaluates to True, the loop will continue; if it
count += 1 # increment count to
evaluates to False, the loop will stop.
eventually break the loop
Example:
2. For Loop The for loop in Python is used for iterating over a sequence (like a list, tuple, string,
or range). It is generally used when you know the number of iterations in advance.
Syntax: for variable in sequence:
# Code to execute repeatedly
variable: This takes the value of each element in the sequence on each iteration.
sequence: This can be any iterable, such as a list, tuple, string, or range.