Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 32

INTRODUCTION UNIT 1

TO FUNCTIONS
FUNCTIONS
+ In Python, a function is a block of code that performs a specific task.
Functions are reusable pieces of code that allow you to break down a
program into smaller, more manageable pieces. They take inputs,
perform some operations, and return a result.
FUNCTIONS
+ Here's the syntax for defining a function in Python:

+ def function_name(parameter1, parameter2, ...):


+ # function code goes here
+ return result
FUNCTIONS
+ The def keyword is used to define a function.
+ function_name is the name of the function. It should be a descriptive
name that explains what the function does.
+ parameter1, parameter2, etc. are the input parameters to the
function. You can have any number of input parameters, or none at all.
+ The function code goes inside the indented block.
+ The return keyword is used to return a result from the function.
+ If the function doesn't return anything, you can omit this keyword.
+ Here's an example of a function that takes two numbers as input and
returns their sum:
+ def add_numbers(num1, num2):
+ sum = num1 + num2
+ return sum
+ The function can be called by passing in the required arguments:
+ result = add_numbers(2, 3)
+ print(result)

+ # output: 5
Advantages of Functions in Python

•By including functions, we can prevent repeating the same code block
repeatedly in a program.
•Python functions, once defined, can be called many times and from
anywhere in a program.
•If our Python program is large, it can be separated into numerous
functions which is simple to track.
•The key accomplishment of Python functions is we can return as many
outputs as we want with different arguments.
USER-DEFINED FUNCTIONS
+ User-defined functions are functions that are defined by the
programmer to perform a specific task in a Python program. These
functions can be created and called by the programmer as needed, and
can help to make code more readable, reusable, and modular. Here's an
example of a simple user-defined function:
USER-DEFINED FUNCTIONS
+ def say_hello(name):
+ print("Hello, " + name + "!")
+ In this example, the function say_hello takes one argument name, and
prints a greeting message using the value of that argument.
+ To call this function, you simply pass in the desired argument:
+ say_hello("Alice")
+ This would output: Hello, Alice!
Example Python Code for User-
Defined function

1.def square( num ):


2. """
3. This function computes the square of the number.
4. """
5. return num**2
6.object_ = square(6)
7.print( "The square of the given number is: ", object_ )
Example Python Code for calling a function

1.# Defining a function


2.def a_function( string ):
3. "This prints the value of length of string"
4. return len(string)
5.
6.# Calling the function we defined
7.print( "Length of the string Functions is: ", a_function( "Functions" ) )
8.print( "Length of the string Python is: ", a_function( "Python" ) )
Output:
+ Length of the string Functions is: 9
+ Length of the string Python is: 6
Pass by Reference vs. Pass by Value

+ All parameters in the Python programming language are provided by


reference. It indicates that if we alter the value of an argument inside
of a function, the calling function will likewise reflect the change. For
example,
# Example Python Code for Pass by Reference v
s. Value
1. # defining the function
2. def square( item_list ):
3. '''''''This function will find the square of items in the list'''
4. squares = [ ]
5. for l in item_list:
6. squares.append( l**2 )
7. return squares
8.
9. # calling the defined function
10.my_list = [17, 52, 8];
11.my_result = square( my_list )
12.print( "Squares of the list are: ", my_result )
Output
+ Squares of the list are: [289, 2704, 64]
+ In addition to functions, Python also allows you to import modules,
which are pre-defined collections of functions and variables that can
be used to perform more complex tasks.
+ For example, the math module provides functions for performing
mathematical operations such as square roots, trigonometric functions,
and logarithms.
+ To use a module in your program,
+ import statement:
+ import math

+ # Now the functions can be used from the math module


+ print(math.sqrt(4))
+ # Output: 2.0
ou can also import specific functions or variables from a module using the from keyword:

+ specific functions or variables from a module using the from keyword:


+ from math import pi

+ # Now you can use the pi constant from the math module
+ print(pi)
+ # Output: 3.141592653589793

In summary, user-defined functions and modules are both powerful tools that can be
used to organize code, improve readability, and perform complex tasks in Python.
BUILT-IN FUNCTIONS
+ Python provides a large number of built-in functions that can be used
to perform common tasks such as working with strings, numbers, lists,
dictionaries, and more. These functions are pre-defined by Python and
are available for use in any Python program.
Python Built-in Functions

+ The Python built-in functions are defined as the functions whose functionality
is pre-defined in Python. The python interpreter has several functions that are
always present for use. These functions are known as Built-in Functions. There
are several built-in functions in Python which are listed below:
+ Python abs() Function
+ The python abs() function is used to return the absolute value of a number. It
takes only one argument, a number whose absolute value is to be returned. The
argument can be an integer and floating-point number. If the argument is a
complex number, then, abs() returns its magnitude.
Python abs() Function Example

1.# integer number


2.integer = -20
3.print('Absolute value of -40 is:', abs(integer))
4.
5.# floating number
6.floating = -20.83
7.print('Absolute value of -40.83 is:', abs(floating))
Python all() Function

+ The python all() function accepts an iterable object (such as list, dictionary, etc.). It returns true if
all items in passed iterable are true. Otherwise, it returns False. If the iterable object is empty, the
all() function returns True.
+ Python all() Function Example
1. # all values true
2. k = [1, 3, 4, 6]
3. print(all(k))
4.
5. # all values false
6. k = [0, False]
7. print(all(k))
1.
2. # one false value
3. k = [1, 3, 7, 0]
4. print(all(k))
5.
6. # one true value
7. k = [0, False, 5]
8. print(all(k))
9.
10.# empty iterable
11.k = []
12.print(all(k))
Python any() Function

+ The python any() function returns true if any item in an iterable is true. Otherwise, it returns False.
+ Python any() Function Example
1. l = [4, 3, 2, 0]
2. print(any(l))
3.
4. l = [0, False]
5. print(any(l))
6.
7. l = [0, False, 5]
8. print(any(l))
9.
10.l = []
11.print(any(l))
PARAMETERS

+ Parameters are inputs that are passed into a function when it is called.
They allow you to pass data into a function so that the function can
perform some operation on that data. Here is an example of a function
that takes two parameters:
+ def add_numbers(num1, num2):
+ sum = num1 + num2
+ return sum

+ In this example, num1 and num2 are the two parameters that are
passed into the function add_numbers. The function then adds the
two numbers together and returns the result.
The scope of variables:

+ The scope of a variable is the part of the program where the variable is accessible. In
Python, variables can have different scopes depending on where they are defined. Here are
the four types of variable scopes in Python:
1.Local scope: Variables that are defined inside a function have local scope and can only be
accessed from within that function.
2.Global scope: Variables that are defined outside of any function have global scope and can
be accessed from anywhere in the program.
3.Enclosing scope: Variables that are defined in an enclosing function have enclosing scope
and can be accessed from within any nested functions.
4.Built-in scope: Python has a set of built-in functions and variables that are available in any
scope.
Passing parameters:

+ When you call a function in Python, you can pass in one or more
parameters to the function. Here is an example of a function that takes
two parameters:

+ def say_hello(name, age):


+ print("Hello, " + name + "! You are " + str(age) + " years old.")
Void functions:

+ A void function is a function that does not return any value. It is


simply used to perform some operation or side effect. Here is an
example of a void function:
+ def print_hello():
+ print("Hello, world!")
+ In this example, the function print_hello simply prints a greeting
message to the console
Function returning values:

A function can also return a value back to the caller. This can be
useful when you need to perform some operation on data and
then use the result of that operation in another part of your
program. Here is an example of a function that returns a value:
python

def add_numbers(num1, num2):


sum = num1 + num2
return sum
+ In this example, the function add_numbers takes two parameters and
returns the sum of those parameters.

You might also like