Assignment 4 Python
Assignment 4 Python
1. Define function.
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.
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.
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
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
python
CopyEdit
def greet(name="Guest"):
print("Hello", name)
greet() # Hello Guest
python
CopyEdit
def show(**kwargs):
for key, value in kwargs.items():
print(key, value)