Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
12 views

Python Ans

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

Python Ans

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

1.

Python Programming (IT11)

Unit 1: Fundamentals of Python

1. Define data types in Python. Explain how lists differ from tuples with examples.

Ans:

Summary of Key Differences:

Feature List Tuple

Mutability Mutable (can change) Immutable (cannot change)

Syntax [] ()

Performance Slower (due to mutability) Faster (due to immutability)

Use Case Dynamic collec on Fixed collec on

# Crea ng a tuple

my_tuple = (1, 2, 3, 4)

print(my_tuple) # Output: (1, 2, 3, 4)

# Crea ng a list

my_list = [1, 2, 3, 4]

print(my_list) # Output: [1, 2, 3, 4]

2. Write a Python program to find the factorial of a number using loops.

Ans:

# Func on to calculate factorial using a loop

def factorial(n):

result = 1

# Loop from 1 to n

for i in range(1, n + 1):

result *= i

return result

# Input from the user


number = int(input("Enter a number: "))

# Check if the number is non-nega ve

if number < 0:

print("Factorial is not defined for nega ve numbers.")

else:

print(f"The factorial of {number} is {factorial(number)}")

3. Explain the usage of break and con nue statements with sample code.

Ans:

Summary of break vs con nue:

Statement Descrip on Effect

break Exits the loop Loop terminates immediately

con nue Skips the current itera on The loop con nues with the next itera on

# Using con nue to skip an itera on

for i in range(1, 6):

if i == 3:

print("Skipping the itera on for i =", i)

con nue # Skip the rest of the loop when i is 3

print(i)

# Using break to exit the loop

for i in range(1, 6):

if i == 3:

print("Breaking the loop at i =", i)

break # Exit the loop when i is 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.

List Comprehension Syntax:

new_list = [expression for item in iterable if condi on]

 expression: Opera on on each element.


 item: Current element in the iterable.
 iterable: Collec on to loop over.
 condi on: Op onal filter.

# List comprehension to get squares of even numbers

numbers = [1, 2, 3, 4, 5, 6]

squares_of_even = [n**2 for n in numbers if n % 2 == 0]

print(squares_of_even) # Output: [4, 16, 36]

Comprehensions make code shorter and more readable compared to tradi onal loops.

Unit 2: Func ons, Modules & Excep on Handling


5. Differen ate between local and global variables in Python with examples.

Ans: Difference Between Local and Global Variables in Python

# 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**:

Inside the func on, x = 10

- **Explana on**: The variable `x` is defined inside `my_func on()` and is only accessible within this
func on.

# **Global Variable Example**:


python
x = 10 # Global variable

def my_func on():


print("Inside the func on, x =", x)

my_func on()
print("Outside the func on, x =", x) # Global variable can be accessed outside too

**Output**:

Inside the func on, x = 10


Outside the func on, x = 10

- **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:

| Feature | Local Variable | Global Variable |


|-----------------|-----------------------------------|-------------------------------|
| **Scope** | Inside the func on | Throughout the en re program |
| **Life me** | Exists within func on execu on | Exists for the program's life |
| **Access** | Only within its func on | Accessible in all func ons |

# Modifying Global Variable Inside Func on:


You can modify a global variable inside a func on using the `global` keyword.
python
x = 10 # Global variable

def my_func on():


global x
x = 20 # Modifying the global variable
print("Inside the func on, x =", x)

my_func on()
print("Outside the func on, x =", x) # Global variable is updated
**Output**:

Inside the func on, x = 20


Outside the func on, x = 20

6. Write a program using a lambda func on to filter out even numbers from a list.

Ans:

# Original list of numbers


numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Using filter() with a lambda func on to filter even numbers


even_numbers = list(filter(lambda x: x % 2 == 0, numbers))

# Prin ng the filtered list of even numbers


print(even_numbers)

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:

Python Modules (Short Version)


A module is a file containing Python code (func ons, variables, etc.) that can be imported into other
programs. Modules help organize and reuse code. Python has built-in modules like math, and you can
create your own.
Example: Using the math Module:
import math

# Using math func ons


print(math.sqrt(16)) # Square root: 4.0
print(math.pi) # Pi constant: 3.14159…
print(math.factorial(5)) # Factorial: 120
print(math.pow(2, 3)) # 2^3 = 8.0

 math.sqrt(): Returns square root.


 math.pi: Constant pi (≈ 3.14159).
 math.factorial(): Calculates factorial.
 math.pow(): Exponen a on (x^y).

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}")

# Handle division by zero error


except ZeroDivisionError as e:
print("Error: Cannot divide by zero.")

# Handle invalid input (non-integer values)


except ValueError as e:
print("Error: Invalid input. Please enter numbers.")

# Handle any other type of excep on


except Excep on as e:
print(f"An unexpected error occurred: {e}")

9. What are decorators in Python? Provide a simple example.

Ans:

What are Decorators in Python?


A decorator in Python is a func on that allows you to modify or enhance the behavior of another
func on or method without changing its actual code. Decorators are widely used for tasks like logging,
ming, valida on, and access control.
 Syntax: Decorators use the @decorator_name syntax, applied right above the func on
defini on.
 Simple Example of a Decorator

# A simple decorator func on


def my_decorator(func):
def wrapper():
print("Before the func on call")
func() # Call the original func on
print("A er the func on call")
return wrapper

# Using the decorator


@my_decorator
def say_hello():
print("Hello, world!")

# Calling the decorated func on


say_hello()

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:

# Define a custom excep on


class Nega veNumberError(Excep on):
def __init__(self, value):
self.value = value
super().__init__(f"Nega ve number entered: {self.value}")

# Func on to check for nega ve number


def check_number(num):
if num < 0:
raise Nega veNumberError(num) # Raise the custom excep on
else:
print(f"{num} is a posi ve number.")

# 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

You might also like