0% found this document useful (0 votes)
5 views30 pages

Understanding Python Functions and Usage

This document provides an overview of functions in Python, including their definitions, rules for naming and defining them, and the importance of functions for code reusability and readability. It also covers built-in versus user-defined functions, function parameters, lambda functions, and higher-order functions like map, filter, and reduce. Additionally, it discusses function decorators and type hints, along with a practical example of a logic error in a function.

Uploaded by

firaafx
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views30 pages

Understanding Python Functions and Usage

This document provides an overview of functions in Python, including their definitions, rules for naming and defining them, and the importance of functions for code reusability and readability. It also covers built-in versus user-defined functions, function parameters, lambda functions, and higher-order functions like map, filter, and reduce. Additionally, it discusses function decorators and type hints, along with a practical example of a logic error in a function.

Uploaded by

firaafx
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

CH-5

Methods or Functions
[Link] is function
2. i don’t know 2.2 good job

1.1 try
1.2 try ....
2.1 okay is that f(x)
f(x) f(x) = x² + 2x + 1
Input/Output Relationship:

Math: f(2) = 2² + 2×2 + 1 = 9


f(x)
f(x, y) = x + y
f(2, 3) = 2 + 3=5
f(x, y, z) = x + y +z
so what is function in .py
A function is a block of reusable code that performs a specific task. Functions help in organizing code,
improving readability, and reducing redundancy.

block reusable
DRY
specific
one role
let’s first set rule Rules
1. Definition Rules
Must start with def keyword:
Require parentheses() after the name, even if no parameters:
End with a colon and indented block--> aha!
2. Naming Rules
Follow the same rules as variable names:
Can contain letters, numbers, underscores
Cannot start with a number
Case-sensitive (greet ≠ Greet)
Cannot use Python keywords (def, if, else, etc.)
Convention: Use lowercase with underscores (calculate_area)
f(x) = x² + 2x + 1 Key Similarities
Input/Output Relationship:
Math: f(2) = 2² + 2×2 + 1 = 9
Python: f(2) print 9
Parameters as Variables:
Math: x is the independent variable
Python: x is the parameter
Return Value as Output:
Math: The equation computes the output
Python: The return statement provides
output
{ x + 2 if x < 0
h(x) = {
{ x² if x ≥ 0
💡 Real-World Analogy for a Function in Programming:
Blender is the function.
You give fruits and milk (input).
You press the button (call the function).
The blender mixes it (does something with input).
It gives you a smoothie (output).
Importance of Functions in Programming
Code reusability ⟶ DRY
Modularity
Improved readability
Easier debugging and maintenance

DRY ⟶ don’t repeat yourself


Defining and Calling Functions
Built-in vs. User-Defined Functions
Built-in functions: Predefined functions like print(), len(), sum()
User-defined functions: Created by the programmer to perform custom operations

✂️ ⟶ split() 📏 ⟶ len()
🧮 ⟶ sum() 🔍 ⟶ find()
User-Defined Functions
Function Parameters and Arguments
Parameters → Placeholders in the Function Definition
Arguments → Actual Values Passed to the Function
Default Parameter Values Variable-Length Arguments (*args and **kwargs)
*args: For multiple positional arguments
**kwargs: For multiple keyword arguments

Syntax Meaning

Everything before it is
/
positional-only

Everything after it is
*
keyword-only

You must pass it


name=/
without naming it

Positional vs Keyword Arguments


Return Statement and Scope
Variable Scope
Local Variable: Declared inside a function
Global Variable: Declared outside a function
Lambda Functions (Anonymous Functions)
Python lambda (anonymous) function is a no-name function declared in a single line. It is
defined using the lambda keyword and is similar to a regular function (defined by using the
def keyword).

lambda parameter(s) : expression

A lambda function is created using the lambda keyword.


The keyword is followed by one or many parameters.
Lastly, an expression is provided for the function. This is the part of the code that gets
executed/returned.

The parameter(s) and expression are separated by a colon.


Lambda functions Regular functions

Defined using the lambda Defined using the def


keyword keyword

Requires more than one line


Can be written in one line
of code

Return statement must be


No return statement
defined when returning
required
values

Regular functions must be


Can be used anonymously
given a name
map(), filter(), and reduce()
Map
The map() function in python has the following syntax:
map(func, *iterables)
Where func is the function on which each element in iterables (as many as they are) would be applied on. Notice the
asterisk(*) on iterables? It means there can be as many iterables as possible, in so far func has that exact number as
required input arguments.

When you use map([Link], ls), you're telling Python:


"Take each element in ls and apply the upper method to it."
eg-1
eg-2

When you use map([Link], my_pets), you're telling Python:


"Take each element in ls and apply the upper method to it."

This is a reference to the upper method of the str class. It's the method
itself, not a call to the method.
filter(func, iterable)
The following points are to be noted regarding filter():
Unlike map(), only one iterable is required.
The func argument is required to return a boolean type. If it doesn't, filter simply returns the
iterable passed to it. Also, as only one iterable is required, it's implicit that func must only take
one argument.
filter passes each element in the iterable through func and returns only the ones that evaluate to
true. I mean, it's right there in the name -- a "filter".
reduce() Function
The reduce() function (from the functools module) applies a function of two arguments
cumulatively to the items of an iterable, from left to right, so as to reduce the iterable to a single
value.
from functools import reduce
reduce(function, iterable[, initializer])
Key Differences:
map():
Applies a function to every item
Returns an iterator of the same length
Transforms each element
filter():
Applies a boolean function to each item
Returns an iterator with only items that evaluate to True
Selects elements based on a condition
reduce():
Applies a function cumulatively
Returns a single value
Aggregates elements into one result
Function Decorators
Decorators modify function behavior without changing the function itself.
A decorator is a function that takes another function as input, adds some extra behavior to it,
and returns a new function.
Function Annotations & Type Hints
Python allows you to annotate function parameters and return values to show their expected
types. These are called function annotations.

Type Hint Description

List[int] A list of integers

A dictionary with
Dict[str, str]
string keys and values

A tuple with two


Tuple[int, int]
integers

Optional[str] Either a string or None

Union[int, str] Either an int or a string


A Small Logic Error, A Big Financial Disaster 😬
def cbe_atm_withdrawal(balance, withdraw_amount):
initial_balance = balance
print(f"Initial balance: {balance}")

if balance >= withdraw_amount:


balance -= withdraw_amount

print(f" Withdrawal allowed. {balance}")
else:
print("⚠️ Not enough balance, ")
return "insufficient balance"


# New feature mistake: automatic redeposit for everyone
🔁
print(" System tries to redeposit .")
balance = initial_balance + withdraw_amount

💰
print(f" Final balance: {balance}")
print("----\n")

# Test cases
cbe_atm_withdrawal(balance=1000, withdraw_amount=500)
cbe_atm_withdrawal(balance=300, withdraw_amount=200)
cbe_atm_withdrawal(balance=2000, withdraw_amount=10000)
Final Function Call!

You might also like