0% found this document useful (0 votes)
7 views30 pages

DOC-20250209-WA0003.

The document provides an overview of Python's complex data types, focusing on strings and lists. It covers string properties, operations, methods, and list creation, manipulation, and operations such as appending, updating, and deleting elements. Key concepts include string immutability, list mutability, and various string and list methods for data handling.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views30 pages

DOC-20250209-WA0003.

The document provides an overview of Python's complex data types, focusing on strings and lists. It covers string properties, operations, methods, and list creation, manipulation, and operations such as appending, updating, and deleting elements. Key concepts include string immutability, list mutability, and various string and list methods for data handling.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

Notes on Python Programing

UNIT 3: PYTHON COMPLEX DATA TYPES:

STRINGS:
● Python strings are characters enclosed in quotes of any — single quotation
marks, double quotation and triple quotation marks.
● An empty string is a string that has 0 characters (i.e., it is just a pair of
quotation marks).
● Python strings are immutable.
● Each character has a unique Position-id/index.
● The indexes of a string begin from 0 to (length — l) in forward direction and
-1, -2, -3, .. -length in backward direction.
● We can primarily write a string in these three ways

a ='harry' # Single quoted string


b = "harry" # Double quoted string
c = '''harry''' # Triple quoted string

TRAVERSING A STRING:
● Traversing refers to iterating through the elements of a string one
character at a time.
● The individual characters of a string are accessible through the unique
index of each character.
● Using the indexes, you can traverse a string character by character.
● Traversing refers to iterating through the elements of a string one
character at a time.
● To traverse through a string you can write a loop like :

name = “superb”
for ch in name :
print( ch , ‘-’, end =” “ )

PROBLEM: Program to read a string and display it in reverse order - display one
character per line .Do not create a reverse string. just display in reverse order.
SOLUTION: string1 = input( "Enter a string : " )
print ("The", string1, "in reverse order is:")
length = len(string1)
for a in range (-1, (- length—1), —1) :
print (string1[a] )
STRING OPERATORS:
● We have many operators that can be used to manipulate strings in multiple
ways. They are basic + and *, membership operators in and not in and
comparison (all relational operators) for strings.

Basic Operators:
● Two basic operators of strings are : + and *. These operators are used as
arithmetic operators for addition and multiplication respectively.
● But when used With strings, + operator performs concatenation rather
than addition and * operator performs replication rather than
multiplication.
● As we know that strings are immutable i.e., un-modifiable, thus every time
someone performs something on a string that tries to change it, Python will
internally create a new string rather than modifying the old string in place.

String Concatenation Operator +


● The + Operator creates a new string by joining the two strings, e.g., "tea" +
"pot" will result into "teapot"

● Consider some more examples :


Expression will result into
‘1’ + ‘1’ ‘11’
‘a’ + ‘0’ ‘a0’
‘123’ + ‘abc’ ‘123abc’

NOTE: The + operator has to have both operands of the same type either of
number type (for addition) or of string types (for multiplication). It cannot work
with one operand as string and one as a number.

String replication Operator *


● The * operator when used with numbers (i.e., when both operands are
numbers), it performs multiplication and returns the product of the two
number operands.
● To use a * operator with strings, you need two types of operands - a string
and a number i.e., as number * string or string * number.
● for e.g. 3 * ‘go!’ will result in ‘go!go!go!’

Membership Operators
● There are two membership operators for strings (in fact for all sequence
types). These are in and not in.
● in : Returns True if a character or a substring exists in the given string ;
False otherwise
● not in : Returns True if a character or a substring does not exist in the
given string; False otherwise.
● Both membership operators (when used with strings), require that both
operands used with them are of string type, i.e.,
<string> in <string>
<string> not in <string>
e.g.,
"12" in "xyz"
"12" not in "xyz"

Comparison Operators
● python's standard comparison operators i.e., all relational operators (<, <=,
>, >=, ==, !=) apply to strings also.
● The comparisons using these are on the standard character-by-character
comparison rules for unicode (i.e., dictionary order).
e.g.
“a” == “a” will give True
“Abc” == “abc” will give False
“A” != “a” will give True
“Abc” ==”ABC” will give False

STRING SLICES
● The term 'string slice' refers to a part of the string, where strings are sliced
using a range of indices.
● That is, for a string say name, if we give name[ n : m ] where n and m are
integers and legal indices, Python will return a slice of the string by
returning the characters falling between indices n and m - starting at n,
n+1, n +2 till m -1 .
● Suppose we have a string namely ‘word’ storing a string 'amazing' i.e.,

word[ 0 : 7 ] will give ‘amazing’


word[ 0 : 3 ] will give ‘ama’
Word[-5 : -1 ] will give ‘’azin’

● In a string slice, you give the slicing range in the form [<begin-index> :
<last>].
● If, however, one can skip either of the begin-index or last, Python will
consider the limits of the string i.e., for missing begin-index, it will consider
'0' (the first index) and for missing last value, it will consider length of the
string.
● Consider following example to understand this :

word[ : 7 ] will give ‘amazing’


word[ 3 : ] will give ‘zing’
Word[ 5 : ] will give ‘’ng

STRING FUNCTIONS AND METHODS


● There are so many built-in functions and methods for string manipulation
in Python.
● Every string object that one creates in Python is actually an instance of
String class.
● String manipulation methods follow the below syntax:
<stringobject>.<method name> ( )

1. The capitalize() method returns a string where the first character is


upper case, and the rest is lower case.
Syntax: string.capitalize( )

E.g. txt = "python is FUN!"

x = txt.capitalize( )

print (x)
Output: Python is fun!

2. The count() method returns the number of times a specified value


appears in the string.
Syntax: string.count(value, start, end)

E.g. txt = "I love apples, apple are my favorite fruit"

x = txt.count("apple", 10, 24)

print(x)

Output: 1
3. The endswith() method returns True if the string ends with the specified
value, otherwise False.
Syntax: string.endswith(value, start, end)
txt = "Hello, welcome to my world."

x = txt.endswith("my world.")

print(x)

Output: True

4. The find() method finds the first occurrence of the specified value.The
find() method returns -1 if the value is not found.The find() method is
almost the same as the index() method, the only difference is that the
index() method raises an exception if the value is not found.

Syntax: string.find(value, start, end)

E.g.

txt = "Hello, welcome to my world."

x = txt.find("e")

print(x)

Output: 1

5. The replace() method replaces a specified phrase with another specified


phrase.
Syntax: string.replace(oldvalue, newvalue, count)

E.g.
txt = "one one was a race horse, two two was one too."

x = txt.replace("one", "three")

print(x)
Output: three three was a race horse, two two was three too."
6. The split() method splits a string into a list. One can specify the
separator, default separator is any whitespace.

Syntax: string.split(separator, maxsplit)

E.g. txt = "hello, my name is Peter, I am 26 years old"

x = txt.split(", ")

print(x)

Output: ['hello', 'my name is Peter', 'I am 26 years old']

7. The join() method takes all items in an iterable and joins them into one
string. A string must be specified as the separator.

Syntax: string.join(iterable)

E.g.

myDict = {"name": "John", "country": "Norway"}


mySeparator = "TEST"
x = mySeparator.join(myDict)
print(x)

Output: nameTESTcountry

8. The isalpha() method returns True if all the characters are alphabet
letters (a-z). Example of characters that are not alphabet letters:
(space)!#%&? etc.

Syntax: string.isalpha()

E.g.

txt = "Company10"
x = txt.isalpha()

print(x)

Output: False

9. The isalnum() method returns True if all the characters are


alphanumeric, meaning alphabet letter (a-z) and numbers (0-9). Example
of characters that are not alphanumeric: (space)!#%&? Etc.

Syntax: string.isalnum()

E.g.

txt = "Company 12"

x = txt.isalnum()

print(x)

Output: False

LISTS:
● The Python lists are containers that are used to store a list of values
of any type.
● Unlike other variables Python lists are mutable i.e., you can change
the elements of a list in place ; Python will not create a fresh list when
you make changes to an element of a list
● List is a type of sequence like strings and tuples but it differs from
them in the way that lists are mutable but strings and tuples are
immutable.

CREATING AND ACCESSING LISTS


● A list is a standard data type of Python that can Store a sequence of
values belonging to any type.
● The Lists are depicted through square brackets, e.g.. following are
some lists in python

[ ] OR list( ) #empty list


[1, 2, 3] #list of integers
[1, 2.5, 4.5, 4] #list of numbers(int and float)
[“a”, “b”, “c”] #list of string
[1, “a”, 2.5, “zero”] #list of mixed values type

Creating Lists
● To create a list, put a number of expressions in square brackets.
● That is, use square brackets to indicate the start and end of the list,
and separate the items by commas. (as shown above)

NESTED LIST:
● A list has an element in it, which itself is a list.
● Such a list is called a nested list, e.g.
L1 =[3, 4, [5,6], 7]
● L1 is a nested list with four elements : 3, 4, [5, 6] and 7, L1[2] element is
a list [5, 6]. Length of L1 is 4 as it counts [5, 6] as one element.

ACCESS A LIST ELEMENT:


● We can access the list elements just like we access a string's elements
e.g., List[i] will give the element at ith index of the list ; List[a:b] will
give you elements between indexes a to b - 1 and so on.
● Individual elements of a list are accessed through their indexes, e.g.
>>> vowels=[‘a’, ‘e’, ‘i’, ‘o’, ‘u’]
>>> vowels [0]
‘a’ #output

Traversing a List:
● Traversal of a sequence means accessing and processing each
element of it.
● Thus traversing a list also means the same and same is the tool for it,
i.e., the Python loops.
● That is why sometimes we call a traversal as looping over a
sequence. e.g.

L= [‘P’, ‘y’, ‘t’, ‘h’, ‘o’, ‘n’]


For a in L :
print(a)
Output:
P
y
t
h
o
n
LIST OPERATIONS:

1. Joining Lists
Joining two lists is very easy just like you perform addition. The
concatenation operator +, when used with two lists, joins two lists. Consider
the example given:

>>> list1 = [1, 2, 3]

>>>list2 = [6, 7, 8]

>>>list1 +list2

[1, 2, 3, 4, 5, 6, 7, 8]

NOTES: The* operator when used with lists requires that both the
operands must of list types. We cannot add a number or any other value to
a list.

2. Repeating or Replicating lists


we can use * operator to replicate a list specified number of times, e.g.,

>>> list1 = [1, 2, 3, 4]

>>>list1*2

[1, 2, 3, 4, 1, 2, 3, 4]

3. Slicing the List:


● We can uses indexes of list elements to create list slices as following
format : seq = L [start :stop]
● The above statement will create a list slice namely seq having
elements of list L on indexes start, start+1, start+2,...., stop—1.
● Index on the last limit is not included in the list slice.
● slice is a list in itself, that is, we can perform all operations on it just
like we perform on lists.
● Consider the following example :

>>> List1 = [10, 20 ,30 ,40 ,50 ,60]


>>> seq = List1[2: -1]
>>>seq
[30, 40, 50]

WORKING WITH LIST: We can perform various operation on lists like:


appending, updating, and deleting

Appending Elements to a List


● We can also add items to an existing sequence. The append( ) adds a
single item to the end of the list.
● It can be done as following format :

Consider some examples :


>>> Ist1 = [ 10, 12, 14 ]
>>> lst1. append(16)
>>> Ist1
[ 10, 12, 14, 16 ]

Updating Elements to o List


● To update or change an element of the list in place, we just have to
assign new value to the element's index in list as per syntax :
L [ index ] = < new value >

● consider following example :

>>>Ist1 = [ 10, 12, 14, 16 ]


>>> Ist1[2] = 24
>>>Ist1
[10, 12, 24, 16]

Deleting Elements from a list


● We can also remove items from lists. The del statement can be used
to remove an individual item or to remove all items identified by a
slice.
● It is to used as per syntax below:

del List [ <index>] #to remove element at index


del List [ <start> : <stop> ] # to remove elements in list slice

>>>Ist = [ 10, 12, 14, 16 ]


>>> del Ist[2]
>>>Ist
[10, 12, 16]
● If we use del <list name> only e.g., del lst, it will delete all the elements
and the list object too. After this, no object by the name lst would be
existing.
● we can use the pop( ) method to remove a single element, not list
slices.
● The pop( ) method removes an individual item and returns it.
● del statement and the pop method do pretty much the same thing,
except that pop method also returns the removed item along with
deleting it from the list.
● The pop( ) method is used as per following format :

List.pop( < index>) # index optional; if skipped, last


element is deleted
e.g.
>>>Ist = [ 10, 12, 14, 16 ]
>>> Ist.pop()
16
>>>Ist.pop(1)
12

NOTE: pop method is important when we want to store the element being
deleted for later use

LIST FUNCTIONS AND METHODS:


● There are so many built-in functions and methods for list
manipulation. They use the following syntax :
<listobject>.<method name> ( )

1. The Index method: The index() method returns the position at


the first occurrence of the specified value.
Syntax: list.index(element)
E.g
fruits = [4, 55, 64, 32, 16, 32]

x = fruits.index(32)

print(x)
Output: 3

2. The append method: The append() method appends an element


to the end of the list.
Syntax: list.append(element)
E.g.
a = ["apple", "banana", "cherry"]
b = ["Ford", "BMW", "Volvo"]
a.append(b)
Output: ['apple', 'banana', 'cherry', ["Ford", "BMW", "Volvo"]]

3. The Extend method: The extend() method adds the specified


list elements (or any iterable) to the end of the current list.
Syntax: list.extend(iterable)
E.g
fruits = ['apple', 'banana', 'cherry']

points = (1, 4, 5, 9)

fruits.extend(points)

Output: ['apple', 'banana', 'cherry', 1, 4, 5, 9]

4. The insert method: The insert() method inserts the


specified value at the specified position.
Syntax: list.insert(position, element)

fruits = ['apple', 'banana', 'cherry']

fruits.insert(1, "orange")

Output; ['apple', 'orange', 'banana', 'cherry']

5. The pop method: The pop() method removes the element at


the specified position and return it.
Syntax: list.pop(position)
E.g.
fruits = ['apple', 'banana', 'cherry']

x = fruits.pop(1)

Output:banana

6. The remove method:The remove() method removes the first


occurrence of the element with the specified value.
Syntax: list.remove(element)

E.g.
fruits = ['apple', 'banana', 'cherry']

fruits.remove("banana")

Output: ['apple', 'cherry']

7. The clear method: The clear() method removes all the


elements from a list.
Syntax: list.clear()
E.g.
fruits = ['apple', 'banana', 'cherry', 'orange']

fruits.clear()

Output: []

8. The count method:The count() method returns the number of


elements with the specified value.
Syntax: list.count(value)
E.g.
fruits = ['apple', 'banana', 'cherry']

x = fruits.count("cherry")

Output: 1

9. The reverse method: The reverse() method reverses the


sorting order of the elements.
Syntax: list.reverse()
E.g.
fruits = ['apple', 'banana', 'cherry']
fruits.reverse()

Output: ['cherry', 'banana', 'apple']

10. The sort method: The sort() method sorts the list
ascending by default.You can also make a function to decide
the sorting criteria(s).

Syntax: list.sort(reverse=True|False, key=myFunc)


E.g.
cars = ['Ford', 'BMW', 'Volvo']
cars.sort()

Output: ['BMW', 'Ford', 'Volvo']


TUPLE:

● The Python tuples are sequences that are used to store a tuple
of values of any type.
● Python tuples are immutable i.e. we cannot change the
elements of a tuple in place ; Python will create a fresh tuple
when you make changes to an element of a tuple.
● Tuple is a type of sequence like strings and lists but it differs
from them in the way that lists are mutable but strings and
tuples are immutable.

Creating Tuples:

Tuples are defined by enclosing elements in parentheses ()


separated by commas.

my_tuple = (1, 'apple', 3.14) # Creating a tuple

empty_tuple = ( ) # Creating an empty tuple

single_element_tuple = (5, ) # Tuple with a single element


(note the comma)

Accessing Tuple Elements:

You can access elements in a tuple using indexing, similar to lists.

# Accessing elements
print(my_tuple[0]) # Output: 1
print(my_tuple[1]) # Output: apple
print(my_tuple[2]) # Output: 3.14
Tuple Operations:

1. Concatenation:
● Tuples can be concatenated using the + operator.

tuple1 = (1, 2)

tuple2 = (3, 4)

result = tuple1 + tuple2 # Output: (1, 2, 3, 4)

2. Repetition:

● Tuples can be repeated using the * operator.

my_tuple = ('hello',) * 3

Output: ('hello', 'hello', 'hello')

3. Slicing:

● Tuples support slicing to access a range of elements.

my_tuple = (1, 2, 3, 4, 5)

print(my_tuple[1:4])

Output: (2, 3, 4)

Tuple Functions cmp( )

This is used to check whether the given tuples are the same or not. If both
are same, it will return ‘zero’, otherwise return 1 or -1. If the first tuple is big,
then it will return 1, otherwise return -1.

Syntax:

cmp(t1,t2) #t1and t2 are tuples.

returns 0 or 1 or -1
Example

>>> T1=(10,20,30)

>>> T2=(100,200,300)

>>> T3=(10,20,30)

>>> cmp(T1,T2)

-1

>>> cmp(T1,T3)

>>> cmp(T2,T1)

len( )

It returns the number of items in a tuple.

Syntax:

len(t) #t tuples returns the number of items in the tuple.

Example

>>> T2=(100,200,300,400,500)

>>> len(T2)

Output:

max( ):

It returns its largest item in the tuple.

Syntax:

max(t) #t tuples return maximum value among the given tuple.


Example

>>> T=(100,200,300,400,500)

>>> max(T)

Output:

500

min( ):

It returns the smallest item in the tuple.

Syntax:

min(t) #t tuples return a minimum value among the given


tuples.

Example

>>> T=(100,200,300,400,500)

>>> min(T)

Output:

100

Tuple Methods:

Tuples support only a couple of methods due to their immutability:

● count(): Returns the number of times a specified value appears in


the tuple.

my_tuple = (1, 2, 3, 2, 2, 5)
print(my_tuple.count(2))

Output: 3

● index(): Searches the tuple for a specified value and returns the
position of where it was found.

my_tuple = (1, 2, 3, 2, 2, 5)

print(my_tuple.index(5))

Output: 5
Dictionary:

● A dictionary is like a list, but more in general. In a list,


index value is an integer, while in a dictionary index value
can be any other data type and are called keys.
● The key will be used as a string as it is easy to recall.
● A dictionary is an extremely useful data storage construct
for storing and retrieving all key value pairs, where each
element is accessed (or indexed) by a unique key.
● Dictionary keys are not in sequences and hence maintain
no left-to right order.

Syntax:

my_dict = {'key1': 'value1','key2': 'value2',...................…'keyn': 'valuen'}

Note: Dictionary is created by using curly brackets(ie. {}).

Example

>>> A={1:"one",2:"two",3:"three"}

>>> print A

{1: 'one', 2: 'two', 3: 'three'}

Creation, initializing and accessing the elements in a


Dictionary:

● The function dict ( ) is used to create a new dictionary with no


items.
● This function is called built-in function.
● We can also create a dictionary using {}.

>>> D=dict()

>>> print D

{} #output
● {} represents an empty string.
● To add an item to the dictionary (empty string), we can use
square brackets for accessing and initializing dictionary
values.

Example

>>> H=dict()

>>> H["one"]="keyboard"

>>> H["two"]="Mouse"

>>> H["three"]="printer"

>>> H["Four"]="scanner"

>>> print H

{'Four': 'scanner', 'three': 'printer', 'two': 'Mouse', 'one':


'keyboard'} #output

Traversing a dictionary:

● If we want to see each element of the dictionary to display its


values on screen. This can be done by using ‘for-loop’.

Example :

H= {'Four': 'scanner', 'three': 'printer', 'two': 'Mouse', 'one':


'keyboard'}

for i in H:

print ( i, ":", H[i], end = “ “)

Output:

Four: scanner one: keyboard three: printer two: Mouse


WORKING WITH DICTIONARY:

Appending values to the dictionary:

● We can add new elements to the existing dictionary, extend it with a


single pair of values or join two dictionaries into one.
● If we want to add only one element to the dictionary, then we should
use the following method.

Syntax:

Dictionary name [key]=value

Example

>>> a={"mon":"monday","tue":"tuesday","wed":"wednesday"}

>>> a["thu"]="thursday"

>>> print a

Output :

{'thu': 'thursday', 'wed': 'wednesday', 'mon': 'monday', 'tue': 'tuesday'}

Merging dictionaries:
● Two dictionaries can be merged into one by using update ( ) method.
● It merges the keys and values of one dictionary into another and
overwrites values of the same key.

Syntax:
Dic_name1.update (dic_name2)
Using this dic_name2 is added with Dic_name1.

Example :
>>> d1={1:10,2:20,3:30}
>>> d2={4:40,5:50}
>>> d1.update(d2)
>>> print d1
Output:
{1: 10, 2: 20, 3: 30, 4: 40, 5: 50}
Removing an item from dictionary:
● We can remove items from the existing dictionary by using del
key word.

Syntax:
del dicname[key]

Example
>>>A={"mon":"monday","tue":"tuesday","wed":"wednesday","thu":"thursday"}
>>> del A["tue"]
>>> print A
output:
{'thu': 'thursday', 'wed': 'wednesday', 'mon': 'monday'}

Dictionary functions and methods:


1. cmp ( ) :
● This is used to check whether the given dictionaries are the same or
not.
● If both are same, it will return ‘zero’, otherwise return 1 or -1.
● If the first dictionary has more items, then it will return 1, otherwise
return -1.

Syntax: cmp(d1,d2) #d1and d2 are dictionaries.


returns 0 or 1 or -1

2. len( )
● This method returns a number of key-value pairs in the given
dictionary.

Syntax: len(d) #d dictionary returns a number of items in the list.

Example
>>> H={'Four': 'scanner', 'three': 'printer', 'two': 'Mouse', 'one': 'keyboard'}
>>> len(H)
Output:
4

3. clear ( ):
● It removes all items from the particular dictionary.

Syntax: d.clear( ) #d dictionary Example


>>> D={'mon':'Monday','tue':'Tuesday','wed':'Wednesday'}
>>> print D {'wed': 'Wednesday', 'mon': 'Monday', 'tue': 'Tuesday'}
>>> D.clear( )
>>> print D
Output:
{}

4. get(key, default= none ) :


● Returns the value for key if key is in the dictionary; otherwise, returns
default.

Example :
my_dict = {'name': 'Alice', 'age': 25}
print(my_dict.get('name')) # Output: Alice
print(my_dict.get('address', 'N/A')) # Output: N/A

5. items( ) It returns the content of dictionary as a list of key and


value. The key and value pair will be in the form of a tuple,
which is not in any particular order. Syntax: D.items() # D
dictionary
my_dict = {'name': 'Alice', 'age': 25}
print(my_dict.items()) # Output: dict_items([('name', 'Alice'), ('age', 25)])

6. keys() It returns a list of the key values in a dictionary, , which is


not in any particular order. Syntax: D.keys( ) #D dictionary
my_dict = {'name': 'Alice', 'age': 25}
print(my_dict.keys()) # Output: dict_keys(['name', 'age'])

7. values() It returns a list of values from key-value pairs in a


dictionary, which is not in any particular order. However, if we
call both the items () and values() method without changing the
dictionary's contents between these two (items() and values()),
Python guarantees that the order of the two results will be the
same
my_dict = {'name': 'Alice', 'age': 25}
print(my_dict.values()) # Output: dict_values(['Alice', 25])
Functions:
● A function is a named sequence of statement(s) that performs a
computation.
● It contains lines of code(s) that are executed sequentially from top to
bottom by Python interpreter.
● They are the most important building blocks for any software in
Python.
● Functions can be categorized as belonging to
i. Modules
ii. Built in
iii. User Defined

Module:
● A module is a file containing Python definitions (i.e. functions) and
statements.
● Standard library of Python is extended as module(s) to a
programmer.
● Functions from the module can be used within the code of a
program.
● To use these modules in the program, a programmer needs to
import the module.
● Once you import a module, we can use any of its functions or
variables in our code.
● Import is the simplest and most common way to use modules in our
code.
● Its syntax is:
import modulename1 [,modulename2, ---------]

Example
>>> import math

● To use/ access/invoke a function, you will specify the module name


and name of the function- separated by dot (.).
● This format is also known as dot notation.

Example
>>> value= math.sqrt (25) # dot notation

Built in Function:
● Built in functions are the function(s) that are built into Python and
can be accessed by a programmer.
● These are always available and for using them, we don’t have to
import any module.
● Python has a small set of built-in functions as most of the functions
have been partitioned to modules. This was done to keep the core
language precise.
● For example range( ), round( ), id( ), len( ), type( ) etc.

User Defined Functions:


● It is also possible for a programmer to write their own function(s).
● These functions can then be combined to form a module which can
then be used in other programs by importing them.
● To define a function keyword def is used.
● After the keyword comes an identifier i.e. name of the function,
followed by parenthesized list of parameters and the colon which
ends up the line.
● Next follows the block of statement(s) that are the part of the
function.
● Syntax of function is:

def NAME ([PARAMETER1, PARAMETER2, …..]) : #Square brackets


include statement(s) #optional part of statement
Example:
def sayHello (): # Line No. 1
print “Hello World!” # Line No.2
● The first line of function definition, i.e., Line No. 1 is called header
and the rest, i.e. Line No. 2 in our example, is known as body.
● Name of the function is sayHello, and empty parenthesis indicate no
parameters.
● Body of the function contains one Python statement, which displays
a string constant on screen.

Example
def check (num):
if (num%2==0):
print (True)
else:
print (False)
result = check (29)
False
print (result)
None

Parameters and Arguments:


● Parameters are the value(s) provided in the parenthesis when we write
a function header.
● These are the values required by the function to work.
● Let’s understand this with the help of a function written for
calculating the area of a circle.
● Radius is a parameter to the function area. If there is more than one
value required by the function to work on, then, all of them will be
listed in the parameter list separated by comma.
● Arguments are the value(s) provided in the function call/invoke
statement.
● List of arguments should be supplied in the same way as parameters
are listed.
● Bounding of parameters to arguments is done 1:1, and so there
should be the same number and type of arguments as mentioned in
the parameter list.

Defining Functions:
● It is possible to provide parameters of function with some default
value.
● In case the user does not want to provide values (argument) for all of
them at the time of calling, we can provide default argument values.

Example:
def greet (message, times=1):
print message * times
>>> greet (‘Welcome’) # calling function with one argument value

>>> greet (‘Hello’, 2) # calling function with both the argument values.

Output
Welcome
HelloHello

Note:
● The default value assigned to the parameter should be a constant
only.
● Only those parameters which are at the end of the list can be given a
default value.
● We cannot have a parameter on the left with default argument value,
without assigning default values to parameters lying on its right side.
● The default value is evaluated only once, at the time of function
definition.
Example:
def fun(a, b=1, c=5):
print (‘a is , a, ‘b is ‘, b, ‘c is ‘, c)

The function fun can be invoked in many ways


1. >>>fun (3)
a is 3 b is 1 c is 5
2. >>>fun (3, 7, 10)
a is 3 b is 7 c is 10
3. >>>fun (25, c = 20)
a is 25 b is 1 c is 20
4. >>>fun (c = 20, a = 10)
a is 10 b is 1 c is 20

Note: The function named fun ( ) has three parameters out of which the first
one is without default value and other two have default values. So any call
to the function should have at least one argument.

Flow of Execution of a Program:


● Containing Function call Execution always begins at the first
statement of the program.
● Statements are executed one at a time, in order from top to bottom.
● Function definition does not alter the flow of execution of a program,
as the statement inside the function is not executed until the
function is called.
● On a function call, instead of going to the next statement of the
program, the control jumps to the body of the function; executes all
statements of the function in the order from top to bottom and then
comes back to the point where it left off.
● This remains simple, till a function does not call another function.
Similarly, in the middle of a function, the program might have to
execute statements of the other function and so on.

You might also like