Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
12 views

Session3 Functions

The document discusses functions in Python. It explains that a function is a block of code that runs when called. It provides examples of built-in functions like min, max, len. It also discusses how to define custom functions, pass parameters and arguments to functions, return values from functions, and import and use functions from modules like math.

Uploaded by

srinuleone
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Session3 Functions

The document discusses functions in Python. It explains that a function is a block of code that runs when called. It provides examples of built-in functions like min, max, len. It also discusses how to define custom functions, pass parameters and arguments to functions, return values from functions, and import and use functions from modules like math.

Uploaded by

srinuleone
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

5/6/22, 9:56 AM Session3 Functions

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

Built in functions
In [1]:
type(12)

int
Out[1]:

In [5]:
min('bac')

'a'
Out[5]:

In [6]:
max('bac')

'c'
Out[6]:

In [8]:
len('bac')

3
Out[8]:

In [7]:
min('ba c')

' '
Out[7]:

In [9]:
len('ba c')

4
Out[9]:

Math functions
In [11]:
radians=0.7
ht=sin(radians)

---------------------------------------------------------------------------
NameError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_11616/741569380.py in <module>
1 radians=0.7
----> 2 ht=sin(radians)

NameError: name 'sin' is not defined


Python has a math module that provides most of the familiar mathematical functions. Before we can
use the module, we have to import it:

In [17]:
import math

file:///C:/Users/GVPCOE/Desktop/Python sessions/Session3 Functions.html 1/10


5/6/22, 9:56 AM Session3 Functions

This statement creates a module object named math

In [18]:
print(math)

<module 'math' (built-in)>

In [16]:
type(math)

module
Out[16]:

In [19]:
# To display list of functions in a module- syntax dir(module_name)
dir(math)

['__doc__',
Out[19]:
'__loader__',
'__name__',
'__package__',
'__spec__',
'acos',
'acosh',
'asin',
'asinh',
'atan',
'atan2',
'atanh',
'ceil',
'comb',
'copysign',
'cos',
'cosh',
'degrees',
'dist',
'e',
'erf',
'erfc',
'exp',
'expm1',
'fabs',
'factorial',
'floor',
'fmod',
'frexp',
'fsum',
'gamma',
'gcd',
'hypot',
'inf',
'isclose',
'isfinite',
'isinf',
'isnan',
'isqrt',
'lcm',
'ldexp',
'lgamma',
'log',

file:///C:/Users/GVPCOE/Desktop/Python sessions/Session3 Functions.html 2/10


5/6/22, 9:56 AM Session3 Functions

'log10',
'log1p',
'log2',
'modf',
'nan',
'nextafter',
'perm',
'pi',
'pow',
'prod',
'radians',
'remainder',
'sin',
'sinh',
'sqrt',
'tan',
'tanh',
'tau',
'trunc',
'ulp']
To access one of the functions, you have to specify the name of the module and the name of the
function, separated by a dot

In [35]:
radians=math.pi/4
ht=math.sin(radians)
print(ht)

0.7071067811865476

In [27]:
s=1
n=2
ratio = s/n
decibels = 10 * math.log10(ratio)
print(decibels)

-3.010299956639812

In [36]:
math.sqrt(2) / 2.0

0.7071067811865476
Out[36]:

Creating a Function
In [53]:
def function_name():
print("Hello")

def is a keyword that indicates that this is a function definition.

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.

file:///C:/Users/GVPCOE/Desktop/Python sessions/Session3 Functions.html 3/10


5/6/22, 9:56 AM Session3 Functions

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. Later
we will build functions that take arguments as their inputs.

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.

To end the function, you have to enter an empty line (this is not necessary in a script).

In [54]:
function_name()

Hello
To call a function, use the function name followed by paranthesis

In [55]:
type(function_name)

function
Out[55]:

Once you have defined a function, you can use it inside another function.

In [57]:
def repeat_hello():
function_name()
function_name()
function_name()

In [58]:
repeat_hello()

Hello
Hello
Hello

Parameters and Arguments


A parameter is the variable listed inside the parantheses in the function definition. ex: bruce

An argument is the value that is sent to the function when it is called. ex: 10

In [60]:
def print_twice(bruce):
print(bruce)
print(bruce)

In [61]:
print_twice(10)

10
10
file:///C:/Users/GVPCOE/Desktop/Python sessions/Session3 Functions.html 4/10
5/6/22, 9:56 AM Session3 Functions

In [63]:
import math
print_twice(math.pi)

3.141592653589793
3.141592653589793

In [64]:
print_twice('Spam '*4)

Spam Spam Spam Spam


Spam Spam Spam Spam

In [66]:
x='Hello'
print_twice(x)

Hello
Hello

In [70]:
x=10
r=print_twice(x)
print(r)

10
10
None
Void functions might display something on the screen but they don’t have a return value. If you try
to assign the result to a variable r,you get a special value called None.

To return a result from a function, we use the return statement in our function.

In [71]:
def addtwo(a, b):
added = a + b
return added

In [72]:
x=addtwo(3,5)

In [73]:
x=addtwo(3,5)
print(x)

In [4]:
def oper(a, b):
sub=a-b
added = a + b
return sub

In [5]:
x=oper(3,5)
print(x)

-2

file:///C:/Users/GVPCOE/Desktop/Python sessions/Session3 Functions.html 5/10


5/6/22, 9:56 AM Session3 Functions

Number of Arguments
By default, a function must be called with the correct number of arguments.

In [7]:
x=oper(5)
print(x)

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_1400/1195630256.py in <module>
----> 1 x=oper(5)
2 print(x)

TypeError: oper() missing 1 required positional argument: 'b'

In [14]:
def my_function(x):
return 5 * x

y=my_function(5)
print(y)

25

Default Parameter Value


If we call the function without argument, it uses the default value:

In [8]:
def my_function(country = "Norway"):
print("I am from " + country)

In [9]:
my_function()

I am from Norway

In [10]:
my_function("Sweden")

I am from Sweden

In [11]:
my_function("India")

I am from India
Example: Write a program to define a function with multiple return values

In [45]:
def fun():
a=input("enter first value")
b=input("enter second value")
c=input("enter second value")
return a,b,c
d=fun()
print(d)
file:///C:/Users/GVPCOE/Desktop/Python sessions/Session3 Functions.html 6/10
5/6/22, 9:56 AM Session3 Functions

enter first value10


enter second value20
enter second value30
('10', '20', '30')

Recursion
Python also accepts function recursion, which means a defined function can call itself.

In [25]:
def tri_recursion(k):
if(k > 0):
result = k + tri_recursion(k - 1)
print(result)
else:
result = 0
return result

output=tri_recursion(3)

1
3
6

Python - Global Variables


Variables that are created outside of a function are known as global variables. Global variables can
be used by everyone, both inside of functions and outside.

Example Create a variable outside of a function, and use it inside the function

In [26]:
x = "awesome"
def myfunc():
print("Python is " + x)

myfunc()

Python is awesome
If you create a variable with the same name inside a function, this variable will be local, and can only
be used inside the function. The global variable with the same name will remain as it was, global and
with the original value.

Example Create a variable inside a function, with the same name as the global variable

In [27]:
x = "awesome"
def myfunc():
x = "fantastic"
print("Python is " + x)

myfunc()
print("Python is " + x)

file:///C:/Users/GVPCOE/Desktop/Python sessions/Session3 Functions.html 7/10


5/6/22, 9:56 AM Session3 Functions

Python is fantastic
Python is awesome

The global Keyword


Normally, when you create a variable inside a function, that variable is local, and can only be used
inside that function. To create a global variable inside a function, you can use the global keyword.

Example If you use the global keyword, the variable belongs to the global scope:

In [28]:
def myfunc():
global x
x = "fantastic"
myfunc()
print("Python is " + x)

Python is fantastic
Example

To change the value of a global variable inside a function, refer to the variable by using the global
keyword:

In [29]:
x = "awesome"
def myfunc():
global x
x = "fantastic"
myfunc()
print("Python is " + x)

Python is fantastic

Lambda Functions
Sometimes, we don’t want to use the normal way to define a function, especially if our function is
just one line. In this case, we can use anonymous function in Python, which is a function that is
defined without a name. This type of functions also called labmda function, since they are defined
using the labmda keyword.

A lambda function can take any number of arguments, but can only have one expression.

lambda arguments : expression

The expression is executed and the result is returned:

Example: Define a labmda function, which square the in put number. And call the function with input
2 and 5

In [31]:
square = lambda x: x**2

file:///C:/Users/GVPCOE/Desktop/Python sessions/Session3 Functions.html 8/10


5/6/22, 9:56 AM Session3 Functions

print(square(2))
print(square(5))

4
25
Example: Define a labmda function, which add x and y.

In [32]:
my_adder = lambda x, y: x + y

print(my_adder(2, 4))

6
Example: Add 10 to argument a, and return the result:

In [33]:
x = lambda a : a + 10
print(x(5))

15

Say you have a function definition that takes one argument, and that argument will be multiplied
with an unknown number:

Use that function definition to make a function that always doubles the number you send in:

In [38]:
def myfunc(n):
return lambda a : a * n

mydoubler = myfunc(2)
print(mydoubler(11))

22
use the same function definition to make a function that always triples the number you send in:

In [40]:
def myfunc(n):
return lambda a : a * n
mytripler = myfunc(3)
print(mytripler(11))

33
use the same function definition to make both functions, in the same program:

In [41]:
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
mytripler = myfunc(3)
print(mydoubler(11))
print(mytripler(11))

22
33

In [ ]:

file:///C:/Users/GVPCOE/Desktop/Python sessions/Session3 Functions.html 9/10


5/6/22, 9:56 AM Session3 Functions

file:///C:/Users/GVPCOE/Desktop/Python sessions/Session3 Functions.html 10/10

You might also like