MODULE III
Functions
Python has many components like,
Functions
Python allows large program to be divided into basic
blocks called functions.
Classes
Classes can comprise many objects, functions, codes
etc.
Modules
A files that contains definition of functions and classes
Packages
Many modules can be combined in packages
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.
Creating a Function
In Python a function is defined using the def
keyword:
Example
def my_function():
print("Hello from a function")
Python supports the use of three types of
functions:
Python Built-in functions
Already created, predefined function
User defined function
A function created by users as per the requirements
Anonymous function
A function having no name
Function has three parts:
Name
Every function has a name that identifies the code to
be executed.
Function rules follow the same rules for variable
names.
Parameters
A function must be called with a certain number of
parameters, and each parameters must be the correct
type.
Some functions do not accept any parametes.
Result Type
A function returns a value to its caller.
name=“Heera”
def display():
print(“My name is“, name)
display()
Calling a Function
To call a function, use
the function name
followed by parenthesis:
Example
def my_function():
print("Hello from a function")
my_function()
Arguments
Information can be passed into functions as
arguments.
Arguments are specified after the function
name, inside the parentheses.
You can add as many arguments as you want,
just separate them with a comma.
def my_function(fname):
print(fname + " Refsnes")
my_function(“Niya")
my_function("Tobias")
my_function("Linus")
def my_function(fname, lname):
print(fname + " " + lname)
my_function(“Mili", "Refsnes")
Arbitrary Arguments, *args
def my_function(*kids):
print("The youngest child is " + kids[2])
my_function("Emil", "Tobias", "Linus")
Parameters or Arguments?
The terms parameter and argument can
be used for the same thing: information that
are passed into a function.
A parameter is the variable listed inside
the parentheses in the function definition.
An argument is the value that is sent to
the function when it is called.
Keyword Arguments
You can also send arguments with
the key = value syntax.
This way the order of the arguments does not matter.
Example
def my_function(child3, child2, child1):
print("The youngest child is " + child3)
my_function(child1 = "Emil", child2 = "Tobias", child3
= "Linus")
Built-in Functions
abs()
Returns the absolute value of a number
The argument may be an integer, or a
floating point number.
Syntax:
abs(n)
Eg: integer
n=-20
m=abs(n)
print(“ABSOLUTE VALUE OF “,n,” IS”,m)
Eg: floating number
n=-20.25
m=abs(n)
print(“ABSOLUTE VALUE OF “,n,” IS”,m)
all()
This function returns True if all items in an iterable
are True, otherwise it returns False.
If the iterable object is empty, the all() function also
returns True.
Syntax:
all(iterable)
iterable object: list,tuple,dictionary
#check if all items in a list are True
mylist=[0,1,1]
Print(all(mylist)
Output:
False
#check if all items in a list are True
mylist=[1,2,3]
Print(all(mylist)
Output:
True
#check if all items in a list are True
mylist=[]
Print(all(mylist)
Output:
True
Check if all items in a tuple are True:
mytuple = (True, False)
x = all(mytuple)
print(x)
Output:
False
Check if all items in a set are True:
myset = {0, 1, 0}
x = all(myset)
print(x)
Output:
False
Check if all items in a dictionary are True:
mydict = {0 : "Apple", 1 : "Orange"}
x = all(mydict)
print(x)
Output:
False
When used on a dictionary, the all() function checks
if all the keys are true, not the values.
any()
Check if any of the items in a list are True:
Syntax:
any(iterable)
Example
mylist = [False, True, False]
x = any(mylist)
Check if any item in a tuple is True:
mytuple = (0, 1, False)
x = any(mytuple)
Output:
True
Check if any item in a set is True:
myset = {0, 1, 0}
x = any(myset)
Output:
True
Check if any item in a dictionary is True:
mydict = {0 : "Apple", 1 : "Orange"}
x = any(mydict)
Output:
True
Check if any item in a dictionary is True:
mylist = []
x = any(mylist)
Output:
True
Python ascii() Function
The ascii() function returns a readable
version of any object (Strings, Tuples, Lists,
etc).
The ascii() function will replace any
non-ascii characters with escape characters:
å will be replaced with \xe5.
Example
Escape non-ascii characters:
x = ascii("My name is Ståle")
Print(x);
Output:
My name is St\xe5
Parameter Values
Parameter Description
object An object, like String, List, Tuple, Dictionary etc.
Python bin() Function
The bin() returns the binary version of a
specified integer.
The result will always start with the prefix 0b.
Syntax:
bin(n)
Parameter Values
Parameter Description
n Required. An integer
Example
Return the binary version of 36:
x = bin(36)
Output
0b100100
Python bool() function
The bool() function returns the boolean value of
a specified object.
The object will always return True, unless:
The object is empty, like [], (), {}
The object is False
The object is 0
The object is None
Parameter Values
Parameter Description
object Any object, like String, List, Number etc.
Syntax
bool(object)
Example
Return the boolean value of 1:
x = bool(1)
Output:
True
Python chr() Function
The chr() function returns the character that
represents the specified unicode.
Syntax
chr(number)
Parameter Values
Parameter Description
number An integer representing a valid Unicode code point
x = chr(97)
print(x)
Output:
A
---------------------------------------------------
x = chr(65)
print(x)
Output:
A
Python complex() Function
The complex() function returns a complex
number by specifying a real number and an
imaginary number.
Syntax
complex(real, imaginary)
Parameter Values
Parameter Description
real Required. A number representing the real part of the complex
number. Default 0. The real number can also be a String, like this
'3+5j', when this is the case, the second parameter should be
omitted.
imaginary Optional. A number representing the imaginary part of the
complex number. Default 0.
Example
Convert the number 3 and imaginary number 5
into a complex number:
x = complex(3, 5)
Python dict() Function
The dict() function creates a dictionary.
A dictionary is a collection which is unordered,
changeable and indexed.The dict() function
creates a dictionary.
Syntax
dict(keyword arguments)
Parameter Values
Parameter Description
keyword Optional. As many keyword arguments you like, separated
arguments by comma: key = value, key = value ...
Example
Create a dictionary containing personal information:
x = dict(name = "John", age = 36, country = "Norway")
Output:
{'name': 'John', 'age': 36, 'country': 'Norway'}
Python divmod() Function
The divmod() function returns a tuple containing
the quotient and the remainder when
argument1 (dividend) is divided by argument2
(divisor).
Syntax
divmod(dividend, divisor)
Parameter Values
Parameter Description
dividend A Number. The number you want to divide
divisor A Number. The number you want to divide with
Example
Display the quotient and the remainder of 5
divided by 2:
x = divmod(5, 2)
Output:
(2, 1)
Python eval() Function
The eval() function evaluates the specified
expression, if the expression is a legal Python
statement, it will be executed.
Syntax
eval(expression, globals, locals)
Parameter Values
Parameter Description
expression A String, that will be evaluated as Python code
globals Optional. A dictionary containing global parameters
locals Optional. A dictionary containing local parameters
Example
Evaluate the expression 'print(55)':
x = 'print(55)'
eval(x)
Output:
55
Python float() Function
The float() function converts the specified value
into a floating point number.
Syntax
float(value)
Parameter Values
Parameter Description
value A number or a string that can be converted into a floating
point number
Example
Convert the number 3 into a floating point
number:
x = float(3)
Output:
3.0
Python format() Function
The format() function formats a specified value
into a specified format.
Syntax
format(value, format)
x = format(0.5, '%')
Output
50.000000%
x = format(255, 'x')
Output:
ff
Parameter Description
value A value of any format
format The format you want to format the value into.
Legal values:
'<' - Left aligns the result (within the available space)
'>' - Right aligns the result (within the available space)
'^' - Center aligns the result (within the available space)
'=' - Places the sign to the left most position
'+' - Use a plus sign to indicate if the result is positive or negative
'-' - Use a minus sign for negative values only
' ' - Use a leading space for positive numbers
',' - Use a comma as a thousand separator
'_' - Use a underscore as a thousand separator
'b' - Binary format
'c' - Converts the value into the corresponding unicode character
'd' - Decimal format
'e' - Scientific format, with a lower case e
'E' - Scientific format, with an upper case E
'f' - Fix point number format
'F' - Fix point number format, upper case
'g' - General format
'G' - General format (using a upper case E for scientific notations)
'o' - Octal format
'x' - Hex format, lower case
'X' - Hex format, upper case
'n' - Number format
'%' - Percentage format
Python help() function
help() Executes the built-in help system
It generates help of the given object.
help(list)
help(print)
Python hex() Function
The hex() function converts the specified
number into a hexadecimal value.
The returned string always starts with the prefix
0x.
Syntax
hex(number)
Parameter Values
Parameter Description
number An Integer
Example
Convert 255 into hexadecimal value:
x = hex(255)
Python input() Function
The input() function allows user input.
Syntax
input(prompt)
Parameter Values
Parameter Description
prompt A String, representing a default message before the input.
Example
Use the prompt parameter to write a message before the
input:
x = input('Enter your name:')
print('Hello, ' + x)
Output:
Enter your name: mili
Hello, mili