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

Assignment 02 Yoheshwaran K

The document contains information about various Python functions: 1) It discusses built-in functions like print(), len(), str(), int(), max(), min() and user-defined functions. 2) The enumerate() function is described which allows iterating over elements in a sequence while keeping track of indexes. 3) Attributes of objects can be accessed and modified dynamically using getattr() and setattr(). 4) Functions like id() return unique identifiers of objects and len() returns the length of sequences. 5) Exception handling allows programs to gracefully handle errors during execution.

Uploaded by

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

Assignment 02 Yoheshwaran K

The document contains information about various Python functions: 1) It discusses built-in functions like print(), len(), str(), int(), max(), min() and user-defined functions. 2) The enumerate() function is described which allows iterating over elements in a sequence while keeping track of indexes. 3) Attributes of objects can be accessed and modified dynamically using getattr() and setattr(). 4) Functions like id() return unique identifiers of objects and len() returns the length of sequences. 5) Exception handling allows programs to gracefully handle errors during execution.

Uploaded by

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

ASSIGNMENT 02

Batch No :191
Name :Yoheshwaran K
E-mail :[email protected]
Ph No :6374577055
Gender :Male
College Name :Pavendar Bharathidasan College
of Engineering and Technology

1. What is function?
A function is a named sequence of statements that can be executed
as a single unit. It takes inputs, processes them, and produces an output.
The input to a function is known as the "arguments" or "parameters," and
the output is referred to as the "return value." Functions are defined with
a unique name, and when you want to execute that function, you "call" it
by using its name along with the necessary arguments.

Here's a simple example of a function in Python that adds two numbers


and returns the result:
def add_numbers(a, b):
result = a + b
return result

sum_result = add_numbers(5, 3)
print(sum_result) # Output: 8
2. Difference between Built-in function and user define function
Built-in Functions.
Built-in functions are pre-defined functions that come as part of the
programming language's standard library or core. They are already
available for use and don't require additional coding to access them.These
functions are typically designed to perform common tasks or operations
that are frequently needed in programming.
Examples of built-in functions in Python include ‘print()’, ‘len()’,
‘str()’, ‘int()’, ‘max()’, ‘min()’, etc.
User-Defined Functions:
User-defined functions are functions that programmers create and
define themselves to perform specific tasks or operations that are not
available as built-in functions.These functions are defined by the
programmer to meet their unique requirements and are not part of the
language's standard library.User-defined functions help break down
complex tasks into smaller, manageable parts and promote code
reusability and readability.Programmers can create functions with
meaningful names that reflect the purpose of the functionality they are
implementing.
Here's an example of a built-in function ‘(len())’ and a user-defined
function in Python:
# Built-in function (len())
sample_list = [1, 2, 3, 4, 5]
length = len(sample_list)
print(length) # Output: 5
# User-defined function
def square(x):
return x * x

result = square(3)
print(result) # Output: 9

3. What is Enumberate function?


The `enumerate()` function is a built-in function in Python that
provides an easy way to iterate over elements in a sequence (such as a
list, tuple, or string) while keeping track of the index of the current
element. It returns an iterator that generates tuples containing both the
index and the value of each element in the sequence.
The general syntax of the `enumerate()` function is as follows:
```python
enumerate(sequence, start=0)
```
Parameters:
- `sequence`: The iterable (e.g., list, tuple, string) over which you want to
iterate.
- `start` (optional): An integer specifying the starting index value for the
enumeration. By default, it is set to 0.
Here's a simple example of using `enumerate()`:
```python
fruits = ['apple', 'banana', 'cherry', 'date']
for index, fruit in enumerate(fruits):
print(f"Index: {index}, Fruit: {fruit}")
```
Output:
```
Index: 0, Fruit: apple
Index: 1, Fruit: banana
Index: 2, Fruit: cherry
Index: 3, Fruit: date
```

4. Use of getattr() and setattr() :


`getattr()` and `setattr()` are built-in functions in Python used for dynamic
attribute access and modification in objects.
1. `getattr(object, name, default=None)`:
`getattr()` retrieves the value of a named attribute from an object. It takes
three parameters: the object from which to get the attribute, the name of
the attribute, and an optional default value.If the attribute exists, it returns
its value; otherwise, it returns the default value (if provided) or raises an
`AttributeError`. Useful for accessing attributes when their names are
stored as strings or when handling optional attributes that may or may not
exist.
Example:
```python
class Person:
def __init__(self, name, age):
self.name = name
self.age = age

person = Person("Alice", 30)

name_value = getattr(person, "name")


print(name_value) # Output: "Alice"

city_value = getattr(person, "city", "Unknown")


print(city_value) # Output: "Unknown"
```
2. `setattr(object, name, value)`:
`setattr()` sets the value of an attribute in an object dynamically. It takes
three parameters: the object to modify, the name of the attribute, and the
value to assign to that attribute.If the attribute already exists, its value is
updated; if not, a new attribute is created.Useful for updating or adding
attributes to an object at runtime.
Example:
```python
class Person:
def __init__(self, name, age):
self.name = name
self.age = age

person = Person("Alice", 30)

setattr(person, "age", 35)


print(person.age) # Output: 35
setattr(person, "city", "New York")
print(person.city) # Output: "New York"
```

5. Use of Id function() and len function() :


1. `id(object)`:
The `id()` function in Python is used to get the unique identifier
(memory address) of an object. It returns an integer representing the
memory address where the object is stored in memory. The `id()` is
guaranteed to be unique and constant for a given object during its
lifetime, but it may change if the object is deleted and re-created at a
different memory location. The `id()` function is mainly used for
debugging and understanding how Python handles memory and object
references.
Example:
```python
x = 42
y = "hello"

print(id(x)) # Output: A unique integer representing the memory address


of x
print(id(y)) # Output: A different unique integer representing the
memory address of y
```
2. `len(sequence)`:
The `len()` function in Python is used to get the number of elements in a
sequence, such as a list, tuple, string, or dictionary. It returns an integer
representing the length of the sequence. For strings, `len()` returns the
number of characters in the string. For lists and tuples, it returns the
number of elements. For dictionaries, it returns the number of key-value
pairs. The `len()` function is widely used for control flow, looping, and
data validation in Python programs.
Example:
```python
my_list = [1, 2, 3, 4, 5]
my_string = "Hello, World!"
my_dict = {'a': 1, 'b': 2, 'c': 3}

print(len(my_list)) # Output: 5
print(len(my_string)) # Output: 13
print(len(my_dict)) # Output: 3
```

6. Write a code for student mark sheet creation using userdefine


function with for loop.
def calculate_total(marks):
return sum(marks)
def calculate_average(marks):
return sum(marks) / len(marks)
def create_mark_sheet():
num_students = int(input("Enter the number of students: "))
subjects = ["Maths", "Science", "English", "History"] # Assuming four
subjects
for student in range(1, num_students + 1):
print(f"\nStudent {student}:")
marks = []
for subject in subjects:
mark = int(input(f"Enter {subject} marks: "))
marks.append(mark)
total_marks = calculate_total(marks)
average_marks = calculate_average(marks)
print("\nMark Sheet:")
print(f"Subjects: {', '.join(subjects)}")
print(f"Marks: {', '.join(map(str, marks))}")
print(f"Total: {total_marks}")
print(f"Average: {average_marks:.2f}")
create_mark_sheet()

7. Difference between type() and input().


`type()` and `input()` are both built-in functions in Python, but they serve
different purposes:
1. `type()`:
The `type()` function is used to determine the type of an object or
variable in Python. It takes one argument, which can be any Python
object or variable. When `type()` is called, it returns the type of the
provided object as a class object. Common examples of types returned by
`type()` include `int`, `float`, `str`, `list`, `tuple`, `dict`, `set`, and custom-
defined classes. It is useful for debugging and checking the data type of
variables during runtime.
Example:
```python
x = 42
y = "hello"
z = [1, 2, 3]

print(type(x)) # Output: <class 'int'>


print(type(y)) # Output: <class 'str'>
print(type(z)) # Output: <class 'list'>
```
2. `input()`:
The `input()` function is used to take user input from the console in
Python. It displays a prompt to the user, waits for them to enter a value,
and then returns the entered value as a string. It is commonly used to get
user input, which can be later converted to the desired data type using
functions like `int()`, `float()`, or `str()`.- Note that all input received from
the `input()` function is considered as a string, so explicit type conversion
is necessary when dealing with numeric or other specific data types.
Example:
```python
name = input("Enter your name: ")
age = int(input("Enter your age: ")) # Converts input to an integer
height = float(input("Enter your height in meters: ")) # Converts input to
a float

print(f"Name: {name}, Age: {age}, Height: {height}")


```
8. What is Exception handling ?
Exception handling is a programming concept that allows
developers to gracefully handle and manage errors or exceptional
situations that may occur during the execution of a program. In most
programming languages, including Python, errors can disrupt the normal
flow of code execution and cause the program to terminate abruptly.
Exception handling provides a structured way to deal with these errors,
preventing program crashes and enabling developers to take appropriate
actions when errors occur.
Key components of exception handling:
1. Exception: An exception is an error or an unexpected event that occurs
during program execution. Common exceptions include division by zero,
invalid input, file not found, and out-of-bounds access to data structures.
2. Try: The code block that is suspected to raise an exception is placed
within a `try` block. The `try` block allows the program to execute
normally. If an exception occurs within the `try` block, the control is
transferred to the nearest matching `except` block.
3. Except: The `except` block contains the code that handles the
exception. It specifies the action to be taken when a specific type of
exception is encountered. Multiple `except` blocks can be used to handle
different types of exceptions.
4. Finally: The `finally` block, if specified, will be executed regardless
of whether an exception occurred or not. It is typically used to release
resources or perform cleanup operations.
Here's a simple example of exception handling in Python:
```python
try:
num1 = int(input("Enter a number: "))
num2 = int(input("Enter another number: "))
result = num1 / num2
print("Result:", result)
except ZeroDivisionError:
print("Error: Cannot divide by zero.")
except ValueError:
print("Error: Invalid input. Please enter integers.")
finally:
print("End of the program.")
```

9. What is type and except ?


1. `type`:
`type` is a built-in function in Python used to determine the type of an
object or variable. When you pass an object or variable as an argument to
`type()`, it returns the class type of that object. The class type represents
the category or data type of the object, such as `int`, `float`, `str`, `list`,
`tuple`, `dict`, `set`, etc. `type()` is particularly useful for debugging,
checking the data type of variables, or performing conditional checks
based on object types.
Example:
```python
x = 42
y = "hello"
z = [1, 2, 3]

print(type(x)) # Output: <class 'int'>


print(type(y)) # Output: <class 'str'>
print(type(z)) # Output: <class 'list'>
```
2. `except`:
except` is a keyword used in Python's exception handling mechanism. It
is part of the `try-except` block and is used to catch and handle
exceptions that occur during program execution. The `try` block contains
the code that may raise an exception. If an exception occurs within the
`try` block, the control transfers to the matching `except` block. The
`except` block contains the code that executes when a specific type of
exception is encountered. You can have multiple `except` blocks to
handle different types of exceptions. By using `except`, you can prevent
the program from crashing due to exceptions and gracefully handle
errors, allowing for better error reporting and recovery.
Example:
```python
try:
num1 = int(input("Enter a number: "))
num2 = int(input("Enter another number: "))
result = num1 / num2
print("Result:", result)
except ZeroDivisionError:
print("Error: Cannot divide by zero.")
except ValueError:
print("Error: Invalid input. Please enter integers.")
finally:
print("End of the program.")
```
10. What is lambda function ?
A lambda function in Python is a small, anonymous function
defined using the `lambda` keyword. Unlike regular functions created
with the `def` keyword, lambda functions do not have a name. Instead,
they are often used for short, one-liner operations where creating a named
function would be unnecessary or impractical.
The general syntax of a lambda function is:
```python
lambda arguments: expression
```
The `arguments` represent the input parameters of the function, and the
`expression` represents the operation that the function performs on those
arguments. The result of the expression is automatically returned as the
output of the lambda function.
Lambda functions are often used as functional arguments for higher-order
functions like `map()`, `filter()`, and `sorted()`. They can also be used to
create short, concise functions when needed for simple operations.
Here are some examples to illustrate the use of lambda functions:
1. Using lambda with `map()` to apply a function to each element of a
list:
```python
numbers = [1, 2, 3, 4, 5]
squared_numbers = map(lambda x: x**2, numbers)
print(list(squared_numbers)) # Output: [1, 4, 9, 16, 25]
```
2. Using lambda with `filter()` to filter elements based on a condition:
```python
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = filter(lambda x: x % 2 == 0, numbers)
print(list(even_numbers)) # Output: [2, 4, 6, 8, 10]
```
3. Using lambda with `sorted()` to sort a list of tuples based on a specific
element:
```python
students = [('Alice', 25), ('Bob', 22), ('Charlie', 28)]
sorted_students = sorted(students, key=lambda x: x[1])
print(sorted_students) # Output: [('Bob', 22), ('Alice', 25), ('Charlie', 28)]
```

You might also like