Introduction to python
Functions
Functions are named blocks of code designed
to do one specific job.
or
When you want to perform a particular task that
you’ve defined in a function, you call the
function responsible for it.
or
A function is a group of statements that execute
upon request.
Functions
If you need to perform that task multiple times
throughout your program, you don’t need to type all the
code for the same task again and again you just call the
function dedicated to handling that task, and the call
tells Python to run the code inside the function.
or
A function is a set of lines (i.e. a block of code), working
as a single unit and carrying out a specific task only
when it is called. A function:
can return data
can have data (known as parameters or arguments)
passed into it
Functions
Advantages:
You’ll find that using functions makes your
programs easier to write, read, test, and fix
Code in a function body may be faster than
at a module’s top level
Clarity and readability
The ability to reuse code
Disadvantages:
there are no disadvantages to organizing
your code into functions versus leaving the
code at module level.
Type of Functions
Built in Functions or predefined Functions
Create / define your on function
Built-in Functions / pre defined functions
Python provides a number of important built-in functions that we
can use without needing to provide the function definition
The creators of Python wrote a set of functions to solve common
problems and included them in Python for us to use.
.
Built-in Functions / pre defined functions
One of the basic and popular method we have seen print() function. It
displays anything on screen as well as to debug code
The type() function is used to determine the type of an object. For
example, if you pass the number 32 to type(), it will return <class 'int'>,
indicating that 32 is an integer.
The max() function in Python is used to find the largest item in an iterable or
the largest of two or more arguments. Here are a few examples to illustrate
its usage:
.
Built-in Functions / pre defined functions
The min() function in Python is used to find the smallest item in an iterable or the
smallest of two or more arguments. Here are some examples to illustrate its usage:
The len() function in Python is used to determine the length of an object. It returns the
number of items in a container, such as a string, list, tuple, dictionary, or any other
iterable. Here are some examples:
.
Built-in Functions / pre defined functions
In Python, type conversion is the process of converting one data type to
another. There are two types of conversion: implicit and explicit.
Implicit Type Conversion: This is automatically handled by Python. For
example, when you add an integer and a float, Python automatically
converts the integer to a float to avoid data loss.
.
Built-in Functions / pre defined functions
Explicit Type Conversion: This is manually done by the programmer using
built-in functions. Here are some common type conversion functions:
int(): Converts a value to an integer.
float(): Converts a value to a floating-point number.
str(): Converts a value to a string.
.
Built-in Functions / pre defined functions
bool(): Converts a value to a boolean
list(): Converts a value to a list.
dict(): Converts a sequence of key-value pairs to a dictionary.
.
Built-in Functions / pre defined functions
In Python, the math module provides a wide range of mathematical functions and
constants. To use these functions, you need to import the math module first. Here’s a
quick overview of some commonly used functions and constants from the math module:
Built-in Functions / pre defined functions
In Python, you can generate random numbers using the random module. This module
provides various functions to generate random numbers for different purposes. Here are
some commonly used functions:
random(): Generates a random float number between 0.0 and 1.0
randint(a, b): Generates a random integer between a and b (inclusive).
Built-in Functions / pre defined functions
randrange(start, stop[, step]): Generates a random number from the specified
range
Choice(seq): Returns a random element from a non-empty sequence.
uniform(a, b): Generates a random float number between a and b.
Task 01:
A teacher records the marks of students in two subjects —
Maths and [Link] are asked to write a Python program
that performs the following tasks:
1. Take two lists of marks:
maths = [78, 92, 85, 69, 90]
science = [88, 79, 84, 91, 73]
2. Use the zip() function to combine the marks of each
student into pairs like (maths_mark, science_mark).
3. Use the map() function and a lambda expression to
calculate each student’s average mark.
4. Display the highest average using the max() function.
5. Compute the class average using the sum() and len()
functions.
6. Finally, display the averages in ascending order using the
sorted() function.
Create / define your on function
Python provides many built-in functions and allows programmers to define
their own functions
A request to execute a function is known as a function call. When you call
a function, you can pass arguments that specify data upon which the
function performs its computation.
To call the function, we use the function name followed by brackets:
function name () in the
first case, function name (parameters) in the second one.
A function always returns a result value, either or a None value that
represents the results of the computation
Functions defined within class statements are also known as methods.
Create / define your on function
A function definition specifies the name of a new function and the
sequence of statements that execute when the function is called.
def function_name(parameters):
statement(s)
function_name is an identifier. It is a variable that gets bound to the
function object when def executes.
parameters is an optional list of identifiers that get bound to the values
supplied when you call the function, which we refer to as arguments to
distinguish between definitions (parameters) and calls (arguments).
The function body can contain zero or more occurrences of the return
statement.
Create / define your on function
First example
Here, def is a keyword that indicates that this is a function definition.
The name of the function is print_lyrics. The rules for function names are the same as for
variable names: letters, numbers and some punctuation marks are legal, but the first
character can’t be a number. You can’t use a keyword as the name of a function,
and you should avoid having a variable and a function with the same name.
The empty parentheses after the name indicate that this function doesn’t take any
arguments.
The first line of the function definition is called the header; the rest is called the body.
The header has to end with a colon and the body has to be indented. By convention,
the indentation is always four spaces. The body can contain any number of
statements.
Create / define your on function
Second example
We update above function taking arguments
Here, in above example jesse is sent as arguments
you enter username in the parentheses of the function’s definition at def
greet_user(). By adding username here, you allow the function to accept any
value of username you specify.
Task 02: Create / define your on function
Message: Write a function called display_message() that
prints one sentence telling everyone what you are
learning about in this chapter. Call the function, and
make sure the message displays correctly.
Favorite Book: Write a function called favorite_book()
that accepts one parameter, title. The function should
print a message, such as One of my favorite books is
Alice in Wonderland. Call the function, making sure to
include a book title as an argument in the function call.
Create / define your on function
Another example
One more example
Create / define your on function
Function with Return Value: A function that calculates the area of a
rectangle and returns the result:
Function with Multiple Parameters: Let’s create a function that calculates
the total cost of items, including tax.
Create / define your on function
Function with Default Parameters: A function with default parameter values:
Function with Arbitrary Arguments: A function that accepts an arbitrary
number of arguments. If you do not know how many arguments that will
be passed into your function, add a * before the parameter name in the
function definition.
Global and Local Variables in Python
Global variables are those which are not defined inside any function and
have a global scope whereas Python local variables are those which are
defined inside a function and their scope is limited to that function only.
we can say that local variables are accessible only inside the function in
which it was initialized whereas the global variables are accessible
throughout the program and inside every function.
Local variables in Python are those which are initialized inside a function
and belong only to that particular function. It cannot be accessed
anywhere outside the function.
Global and Local Variables in Python
Local variables can not used outside the functions
Global and Local Variables in Python
Lets take previous example if we want x variable to use in function then
use global keyword
Task : 3
A local gym wants to create a simple membership tracking program using Python.
You are asked to define 3 functions to perform the following tasks:
1. calculate_bmi(weight, height) – Takes weight (in kg) and height (in meters) as
arguments and returns the Body Mass Index (BMI) using the formula:
BMI = weight / (height)^2
2. classify_bmi(bmi) – Returns a category string:
“Underweight” if BMI < 18.5
“Normal weight” if 18.5 ≤ BMI < 25
“Overweight” if 25 ≤ BMI < 30
“Obese” if BMI ≥ 30
3. display_report(name, weight, height) – Calls the above two functions, prints the
user’s name, BMI (rounded to 2 decimals), and category.
Write a short main program that:
1. Takes a user’s name, weight, and height as input,
2. Then calls display_report() to print the health summary.