0% found this document useful (0 votes)
7 views

Python Quations

Uploaded by

Abhishek Rathore
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Python Quations

Uploaded by

Abhishek Rathore
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

1. What is a lambda function in Python?

o Answer: A lambda function is a small anonymous function


defined using the lambda keyword. It can have any number of
arguments but only one expression. Example:

Python

add = lambda x, y: x + y

print(add(2, 3)) # Output: 5

2. How do you handle exceptions in Python?

o Answer: Exceptions in Python are handled using


the try, except, else, and finally blocks. Example:

Python

try:

result = 10 / 0

except ZeroDivisionError:

print("Cannot divide by zero")

else:

print("Division successful")

finally:

print("Execution completed")

3. What are Python decorators?

o Answer: Decorators are a way to modify or extend the


behavior of functions or methods without changing their
actual code. They are defined with
the @decorator_name syntax. Example:

Python

def my_decorator(func):

def wrapper():

print("Something is happening before the function is called.")

func()

print("Something is happening after the function is called.")

return wrapper
@my_decorator

def say_hello():

print("Hello!")

say_hello()

4. What is the difference between __str__ and __repr__ methods


in Python?

o Answer: The __str__ method is used to return a human-


readable string representation of an object, while __repr__ is
used to return an “official” string representation that can
ideally be used to recreate the object. Example:

Python

import datetime

now = datetime.datetime.now()

print(str(now)) # Output: '2024-08-27 17:34:23.123456'

print(repr(now)) # Output: 'datetime.datetime(2024, 8, 27, 17, 34, 23,


123456)'

AI-generated code. Review and use carefully.

5. How do you create a virtual environment in Python?

o Answer: A virtual environment in Python can be created using


the venv module. Example:

o python -m venv myenv

source myenv/bin/activate # On Windows use `myenv\Scripts\activate`

You might also like