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

Lecture - 4

Chapter 4 covers functions and libraries in Python, emphasizing the importance of functions for code organization, reusability, and modularity. It details user-defined and built-in functions, their characteristics, parameters, arguments, return values, and various types of functions. Additionally, the chapter discusses Python libraries, their utility in reducing coding time, and highlights popular libraries across different domains such as data analysis, machine learning, and web development.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Lecture - 4

Chapter 4 covers functions and libraries in Python, emphasizing the importance of functions for code organization, reusability, and modularity. It details user-defined and built-in functions, their characteristics, parameters, arguments, return values, and various types of functions. Additionally, the chapter discusses Python libraries, their utility in reducing coding time, and highlights popular libraries across different domains such as data analysis, machine learning, and web development.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 45

Chapter - 4

Functions and Libraries

Prepared by: Bilew A.


Year, 2024
Outline

❑ Functions
▪ User – Defined
▪ Built – in
❑ Libraries
Functions

▪ What are functions?

▪ What are they used for?

▪ A function is a block of code which only runs when it is called.


▪ You can pass data, known as parameters, into a function.
▪ A function can return data as a result.
Functions

• Functions in Python are a fundamental concept that allow you


to group a set of related statements together to perform a
specific task.

• They are a way to encapsulate and reuse code, making your


programs more organized, efficient, and maintainable.

• They are mainly used for code re-use.


Functions...

▪ Functions are a powerful tool in Python that help you write more
organized, efficient, and maintainable code.

▪ They allow you to break down complex problems into smaller,


manageable pieces, making your programs more scalable and easier
to work with.

▪ They are primarily used for:

✓ Modularity

✓ Code reuse
Functions...

▪ Analogy: Stamp of a King or

(a Stamp of an institution)

✓ Why did a King need a stamp in the ancient times?


✓ Why do we still need a Stamp in almost any institution?
✓ What significance can these stamps provide?
✓ What advantages of functions can you see from such analogy
with stamps?
Key characteristics of functions in Python

▪ Functions are defined using the def keyword, followed by the


function name, a set of parentheses (), and a colon :.

▪ The code that makes up the function's behaviour is indented and


placed within the function block.

//Example:- Creating a Function


def <function name>(parameters): def great():
<code block> print(“Python")
Key characteristics of functions in Python
Parameters: When you define a function, you can specify one or more
variables within the parentheses next to the function name. These
variables are called parameters. They act as placeholders for the values
that will be passed to the function when it's called.

def my_history(name, age):


print(f"Hello, {name}! are you {age} years old?")
my_history("Abel", 30)
Key characteristics of functions in Python
Arguments

▪ When you call a function, you provide the actual values that you want to
pass to the function's parameters. These values are called arguments.

▪ It fills the corresponding parameter with a specific value.

▪ Arguments are provided inside the parentheses during a function call.

▪ Example:

greet("Abel") # "Abel" is an argument


Key characteristics of functions in Python
Differences between Parameter and Argument
Aspect Parameter Argument
Variable in the function Value passed to the
Definition
definition function call
Defines what data the Supplies the data to the
Purpose
function can accept function
Exists only in the Exists during the
Scope
function definition function call
def greet(name): greet("Abel")
Example
(name is a parameter) ("Abel" is an argument)
Key characteristics of functions in Python:

▪ Return Values:

▪ Functions can return values back to the caller using the return keyword.

▪ The returned value can be used in the caller's code.

▪ Python functions have always a return statement.

▪ If there is no an explicit return system, an implicit default statement


will return a ‘Null’ value.

▪ Note that a ‘Null’ refers to a non-value.


Key characteristics of functions in Python:

▪ Return Values example

def sub_numbers(a, b): # 'a' and 'b' are parameters


return a - b

result = sub_numbers(6, 7) # 6 and 7 are arguments


print(result)
Key characteristics of functions in Python:

Scope:
▪ Variables defined within a function are local to that function
and can only be accessed within the function's code block.

▪ Variables defined outside of a function are global and can be


accessed throughout the program.
Types of Functions in python

▪ The major types of functions in Python can be grouped into


two broad categories:
✓Built-in Functions
✓User-defined Functions.

▪ These can be further subdivided based on their functionality and


use cases.
User Defined Functions
▪ Function might be found built-in with the Standard python package.

▪ But mostly we define functions on our own in order to provide the


different functionalities that we require.

▪ Functions created by the user for specific tasks using the def keyword.

# user defined function


# simple function
def my_function(name):
return f"Hello, Eyob {name}! "

print(my_function("Yisak"))
User Defined Functions

▪Recursive Functions
User Defined Functions

▪Lambda Functions (Anonymous Functions)

▪Higher-Order Functions
Exercises
Solution Using User-Defined Function
1) Write a function
def find_maximum(numbers):
that takes a list if not numbers:
raise ValueError # input check
of numbers as
input and returns max_value = numbers[0]
for number in numbers:
the maximum if number > max_value:
max_value = number
value in the list. return max_value

# Example
numbers_list = [31, 72, 26, 95, 47]
print(find_maximum(numbers_list))
Exercises

2) Write a function that takes a list of numbers as input and returns


the maximum value in the list.

Solution Using Built-in Function

def find_maximum(numbers):
if not numbers:
raise ValueError # list check error
return max(numbers) # max() is built-in function
Exercises...

3) Write a function def print_odd_numbers(limit):


if limit < 1:
that takes a number print("No odd numbers in the given
as input and prints range.")
return
all the odd numbers
from 1 up to (and for number in range(1, limit + 1):
including) that if number % 2 != 0:
print(number)
number.
# Example:
print_odd_numbers(18)
Exercises...

# print odd numbers


def print_odd_numbers(limit):

for num in range(1, limit + 1, 2): #starts at 1, increments by 2 each time

print(num)

# Example:

print_odd_numbers(7)
Exercises...

4) Write a function that takes a number as input and


returns True if the number is prime, and False otherwise.
Exercises...
Exercises...

Class Exercise 4

• Write a function that checks whether a numbver is perfect number.


(Note: a number is a perfect number if the sum of all the divisors of
the number, excluding the number itsef, is equal to the number it
self)
Exercises...
def is_perfect_number(num):

divisors = []
for i in range(1, num):
if num % i == 0:
divisors.append(i)

divisors_sum = sum(divisors)
return divisors_sum == num
More on Functions in Python

▪ Use of recursive function definion is allowed in Python

(Example of facorial of a number)

▪ Keyword Arguments: In addition to positional arguments, you can


also use keyword arguments when calling a function.

▪ Keyword arguments are specified by including the parameter name


and the value you want to pass, separated by an equal sign (=).

▪ Order of parameters doesn’t matter here.


Example:

def calculate_area(length, width):

return length * width

area = calculate_area(5, 10) # it is a positional way of using argumnent


# order matters here

area = calculate_area(length=5, width=10) # a keyword use of arguments


Python Library
▪ A library is a collection of pre-combined codes that can be used
iteratively to reduce the time required to code.

▪ They are particularly useful for accessing the pre-written, frequently


used codes instead of writing them from scratch every single time.

▪ A Python library is a collection of modules and packages that offer a


wide range of functionalities.

▪ These libraries enable developers to perform various tasks without


writing code from scratch.
Python Library...

▪ They contain pre-written, classes, functions, and routines


that can be used to:

✓ develop applications

✓ automate tasks

✓ manipulate data

✓ perform mathematical computations, and more.


Python Library...

▪ Python’s extensive ecosystem of libraries covers diverse areas:


✓ such as web development (e.g., Django, Flask)
✓ data analysis (e.g., pandas, NumPy)
✓ machine learning (e.g., TensorFlow , scikit-learn)
✓ image processing (e.g., Pillow, OpenCV)
✓ scientific computing (e.g., SciPy), and many others.
Python Popular Library...

▪ Python offers a vast ecosystem of libraries catering to diverse


needs, from data science to web development.

Data Analysis and Manipulation

▪ NumPy
✓Fundamental library for numerical computing, supports
arrays and matrices.
Python Popular Library...

Data Analysis and Manipulation

▪ pandas
✓ Powerful data manipulation and analysis tool; great for working with
structured data like tables.

▪ Dask
✓Parallel and distributed computing for large datasets.

▪ Polars
✓A lightning-fast Data Frame library with a Rust backend.
Python Popular Library...

2. Machine Learning and Artificial Intelligence

scikit-learn
✓Easy-to-use machine learning library with support for
regression, classification, clustering, etc.

TensorFlow
✓Open-source library for deep learning and neural networks.
Python Popular Library...

2. Machine Learning and Artificial Intelligence

PyTorch
✓Dynamic computation graph library favored for deep learning research.

XGBoost
✓Gradient boosting library for efficient and accurate machine learning models.

Keras
✓High-level neural networks API running on top of TensorFlow.
Python Popular Library...

3. Data Visualization

▪ Matplotlib: Used for creating static, interactive, and animated plots.

▪ Seaborn: Statistical data visualization built on top of Matplotlib.

▪ Plotly: Interactive plotting library for creating web-based


visualizations.

▪ Bokeh: Library for creating interactive and scalable visualizations.

▪ Altair: Declarative statistical visualization library for concise coding.


Python Popular Library...
4. Web Development

▪ Flask: Lightweight web framework for building small-scale applications.

▪ Django: High-level web framework for developing complex and scalable


web applications.

▪ FastAPI: High-performance API framework for building RESTful APIs


with modern Python.

▪ Bottle: Micro web framework ideal for smaller projects.


Python Popular Library...

5. Scientific Computing
▪ SciPy: Extends NumPy for complex scientific computations.
▪ SymPy: Library for symbolic mathematics.
▪ NetworkX: For analysing and visualizing complex networks.
Python Popular Library...

6. Cybersecurity and Cryptography


▪ cryptography: For encrypting and decrypting data
securely.
▪ paramiko: For secure SSH communication.
▪ scapy: For network packet manipulation and analysis.
Python Popular Library...

7. Testing
▪ unittest: Built-in library for unit testing.
▪ pytest: Powerful and flexible testing framework.
▪ mock: Library for creating mock objects in testing.

8. Game Development
▪ Pygame: Framework for building 2D games.
▪ Godot-Python: Integrates Python scripting into
Godot game engine.
Python Popular Library...

9. Database Interaction

▪ SQLAlchemy: SQL toolkit and Object-Relational Mapping (ORM)


library.

▪ Peewee: Lightweight ORM for simpler database applications.

▪ PyMongo: MongoDB driver for Python.

▪ Redis: Interface for the Redis in-memory database.


How to use Libraries

▪ Import Libraries

▪ Utilize Functions and Classes


Selected Libraries

▪ Math Library

▪ Random Number Generator

▪ Date Time

▪ Calendar Application
DEMONSTRATION SESSION ON THE SELECTED LIBRARIES

DEMONSTRATION SESSION ON THE SELECTED LIBRARIES


More on Libraries

• https://www.mygreatlearning.com/blog/open-source-python-
libraries/
Thank you,
Questions?

You might also like