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

Assignment 4 Python

The document provides an overview of functions in Python, including their definition, creation, parameter passing, and return values. It discusses local vs global variables, default arguments, keyword arguments, nested functions, and variable-length arguments. Additionally, it covers built-in functions, data conversion functions, module creation, and examples of using libraries like matplotlib for data visualization.

Uploaded by

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

Assignment 4 Python

The document provides an overview of functions in Python, including their definition, creation, parameter passing, and return values. It discusses local vs global variables, default arguments, keyword arguments, nested functions, and variable-length arguments. Additionally, it covers built-in functions, data conversion functions, module creation, and examples of using libraries like matplotlib for data visualization.

Uploaded by

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

Assignment 4

1. Define function.

1. A function is a reusable block of code designed to perform a specific task.


It allows you to organize your code into smaller, logical sections.
2. Functions are defined using the def keyword, followed by the function name and
parameters.
The code inside the function is written with indentation.
3. Functions avoid code repetition by letting you write once and use multiple times.
This makes your program more modular and easier to maintain.
4. You can pass values to a function using parameters, and get results using return.
If no return is used, the function returns None by default.
5. Python has built-in functions (like print()), user-defined functions, and anonymous
functions.
Each type is used depending on the need of the task.

2. How to create user-defined function in Python.

1. You start with the def keyword, followed by the name of the function.
Inside parentheses, you define any parameters needed.
2. The function block is indented and may contain logic and operations.
You can use the return keyword to return a value from the function.
3. Example:

python
CopyEdit
def add(a, b):
return a + b

4. You can call the function anywhere in your code by using its name and passing
arguments.
This improves modularity and reusability.
5. Python allows flexibility with parameters, including default, keyword, and variable-
length ones.
This makes user-defined functions more powerful.

3. Parameter passing in Python

1. Python functions support four types of parameter passing: positional, keyword, default,
and variable-length.
Each provides different ways to control input to functions.
2. Positional arguments are passed in the order of parameters defined.
It’s the most straightforward method but can lead to errors if the order is wrong.
3. Keyword arguments are passed using key=value format, making the order flexible.
This increases readability and avoids confusion.
4. Default arguments provide a fallback value if no value is given during the call.
This helps make function calls optional or minimal.
5. Variable-length arguments use *args (tuple) or **kwargs (dictionary).
They allow passing unlimited inputs, making functions more dynamic.

4. Can Python functions return values? Justify with example.

1. Yes, Python functions can return values using the return keyword.
This allows the result to be stored or used later.
2. If no return value is specified, the function returns None by default.
This is Python’s way of indicating “no value.”
3. A function can return any data type — string, list, number, or even another function.
This flexibility makes functions very powerful.
4. You can also return multiple values at once using tuple packing.
Example: return x, y, z
5. Example:

python
CopyEdit
def square(n):
return n * n
print(square(5)) # Output: 25

5. Local vs Global Variables

1. A local variable is defined inside a function and accessible only within it.
It is created when the function is called and destroyed after.
2. A global variable is defined outside functions and accessible anywhere in the script.
It retains its value across function calls.
3. To modify a global variable inside a function, use the global keyword.
Otherwise, Python treats it as a new local variable.
4. Using too many global variables is discouraged as it can make code harder to debug.
Local variables are safer and reduce side effects.
5. Example:

python
CopyEdit
x = 10
def change():
global x
x = 5
📘
6. Functions with default arguments

1. Default arguments allow a function to assign default values to parameters.


They are used when arguments are not passed during function calls.
2. These defaults are assigned at the time of function definition.
Only the last parameters can have defaults; otherwise, it leads to an error.
3. This helps reduce the need to always pass every argument.
Makes function calls simpler and more flexible.
4. Example:

python
CopyEdit
def greet(name="Guest"):
print("Hello", name)
greet() # Hello Guest

7. What is kwargs in Python?

1. **kwargs stands for keyword arguments in Python functions.


It lets you pass any number of keyword arguments as a dictionary.
2. It is used when you don't know beforehand how many named arguments will be passed.
This adds flexibility to your function.
3. Inside the function, kwargs behaves like a dictionary.
You can access keys and values using standard dict methods.
4. Example:

python
CopyEdit
def show(**kwargs):
for key, value in kwargs.items():
print(key, value)

8. Does Python allow nested functions?

1. Yes, Python allows defining functions inside other functions.


These are called nested or inner functions.
2. Inner functions can access variables from the outer function.
This is useful for encapsulation and closures.
3. Nested functions help in hiding functionality that shouldn't be accessed globally.
It supports better code organization and security.
9. Variable Length Arguments (Program)
python
CopyEdit
def add(*args):
result = 0
for i in args:
result += i
return result

print(add(2, 3, 4)) # Output: 9

 *args allows passing multiple numbers to the function.


 The function adds all values, showing how flexible arguments can be.

10. Built-in Functions

 all(): Returns True if all elements in iterable are true.


 hasattr(): Checks if object has a specified attribute.
 oct(): Converts integer to octal string.
 eval(): Evaluates a string as a Python expression.
 issubclass(): Checks if a class is subclass of another.

11. Data Conversion Functions

 int(): Converts value to integer.


 float(): Converts value to floating point number.
 str(): Converts object to string.
 list(): Converts iterable to a list.

12. input() and print() Functions

 input() reads data from the user as a string.


 print() displays output to the console and supports sep, end options.

13. Creating a Module in Python


 A module is simply a Python file (.py) that contains functions, classes, or variables.
 It can be imported into other programs using import module_name.

14. from ... import Statement

 This allows you to import specific parts of a module.


 Example: from math import sqrt lets you use sqrt() directly.

15. Built-in module: random

 The random module provides functions to generate random numbers.


 Functions include random(), randint(), choice(), etc.

16. Lambda Expression

 A lambda is a small anonymous function with a single expression.


 Syntax: lambda x: x * 2

17. map() Function

 map() applies a function to each item in an iterable.


 Example: map(lambda x: x*2, [1,2,3]) returns [2,4,6].

18. Bar Chart using matplotlib


python
CopyEdit
import matplotlib.pyplot as plt
x = ['A', 'B', 'C']
y = [10, 20, 15]
plt.bar(x, y)
plt.show()

You might also like