Python Ans
Python Ans
1. Define data types in Python. Explain how lists differ from tuples with examples.
Ans:
Syntax [] ()
# Crea ng a tuple
my_tuple = (1, 2, 3, 4)
# Crea ng a list
my_list = [1, 2, 3, 4]
Ans:
def factorial(n):
result = 1
# Loop from 1 to n
result *= i
return result
if number < 0:
else:
3. Explain the usage of break and con nue statements with sample code.
Ans:
con nue Skips the current itera on The loop con nues with the next itera on
if i == 3:
print(i)
if i == 3:
print(i)
4. What is a comprehension? Illustrate a list comprehension example.
Ans:
Comprehension in Python
A comprehension is a concise way to create sequences (like lists) using loops and op onal condi ons
in a single line of code.
numbers = [1, 2, 3, 4, 5, 6]
Comprehensions make code shorter and more readable compared to tradi onal loops.
# 1. **Local Variables**:
- **Defined inside a func on**.
- **Scope**: Only accessible within the func on in which they are declared.
- **Life me**: Created when the func on is called and destroyed when the func on exits.
# 2. **Global Variables**:
- **Defined outside any func on**.
- **Scope**: Accessible throughout the en re program, including inside func ons (unless shadowed).
- **Life me**: Exists for the dura on of the program's execu on.
Examples:
# **Local Variable Example**:
python
def my_func on():
x = 10 # Local variable
print("Inside the func on, x =", x)
my_func on()
# print(x) # This will raise an error because x is not defined outside the func on
**Output**:
- **Explana on**: The variable `x` is defined inside `my_func on()` and is only accessible within this
func on.
my_func on()
print("Outside the func on, x =", x) # Global variable can be accessed outside too
**Output**:
- **Explana on**: The variable `x` is defined outside of any func on, so it's accessible both inside and
outside the func on.
Key Differences:
my_func on()
print("Outside the func on, x =", x) # Global variable is updated
**Output**:
6. Write a program using a lambda func on to filter out even numbers from a list.
Ans:
output:
[2, 4, 6, 8, 10]
Explana on:
filter(): Takes two arguments: a func on (in this case, a lambda) and an iterable (the list
numbers). It filters elements based on the func on.
lambda x: x % 2 == 0: A lambda func on that returns True if x is even, filtering out odd numbers.
7. What are Python modules? Explain with the usage of the math module.
Ans:
8. Illustrate how to handle mul ple excep ons using a try-except block.:
Ans:
In Python, you can handle mul ple excep ons in a single try-except block by specifying mul ple
excep on types. This is useful when you want to catch and handle different types of errors that may
occur in your code.
Syntax for handling mul ple excep ons:
try:
# Code that might raise an excep on
pass
except (Excep onType1, Excep onType2) as e:
# Code to handle Excep onType1 or Excep onType2
print(f"Error occurred: {e}")
Example: Handling mul ple excep ons
try:
# Code that may raise different types of excep ons
num1 = int(input("Enter a number: "))
num2 = int(input("Enter another number: "))
result = num1 / num2
print(f"Result: {result}")
Ans:
output:
Before the func on call
Hello, world!
A er the func on call
Explana on:
my_decorator: A decorator that adds func onality before and a er the say_hello func on.
@my_decorator: Applies the my_decorator to say_hello. When say_hello() is called, the
wrapper func on is executed instead, adding extra behavior.
Decorators allow you to wrap func ons and extend their behavior in a clean and reusable way.
10. Write a program to raise a user-defined excep on when a nega ve number is entered.
Ans:
# Main program
try:
number = int(input("Enter a number: "))
check_number(number)
except Nega veNumberError as e:
print(e)
Explana on:
Nega veNumberError: A custom excep on class that inherits from Excep on. It is raised when a
nega ve number is entered.
check_number(num): A func on that checks if the number is nega ve and raises the custom
excep on.
try-except block: Handles the Nega veNumberError and prints the custom error message if a
nega ve number is entered.
Output:
Enter a number: -5
Nega ve number entered: -5