PP Unit-3
PP Unit-3
Python Programming
Unit-3
Python Functions and Modules
Contents
• Defining custom functions
• Organizing Python codes using functions
• Create and reference variables using the appropriate scope
• Basic skills for working with lists and tuples
• Dates and time module
• Dictionaries
• Importing own module as well as external modules
• Programming using functions, modules and external packages
Functions
Defining Custom Function
• 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")
Calling a Custom Function
• To call a function, use the function name followed by parenthesis.
• Example:
def my_function():
print("Hello from a function") Output:
Hello from a function
my_function()
Arguments of a Function
• 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.
• The following example has a function with one argument (fname). When the function is called, we
pass along a first name, which is used inside the function to print the full name:
• Example:
def my_function(fname):
Output:
print(fname + “, Hello!") Annie, Hello!
my_function(“Annie") Bob, Hello!
my_function(“Bob")
Arguments of a Function
• By default, a function must be called with the correct number of arguments. Meaning that if your
function expects 2 arguments, you have to call the function with 2 arguments, not more, and not
less.
• Example:
• This function expects 2 arguments, and gets 2 arguments:
my_function(“Steve", “Jobs")
Arbitrary Arguments of a Function
• 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.
• This way the function will receive a tuple of arguments, and can access the items accordingly.
• Example:
• If the number of arguments is unknown, add a * before the parameter name:
def my_function(*p):
print("The youngest child is " + p[2]) Output:
The youngest child is Bob
• Example:
def my_function(p3, p2, p1): Output:
print("The youngest person is " + p1) The youngest person is Annie
• Example:
• If the number of keyword arguments is unknown, add a double ** before the parameter name:
def my_function(**p):
print("His last name is " + p["lname"]) Output:
His last name is Jobs
• Example:
def my_function(country = "Norway"):
print("I am from " + country)
my_function("Sweden") Output:
I am from Sweden
my_function("India")
I am from India
my_function() I am from Norway
my_function("Brazil") I am from Brazil
Returning a Value from a Function
• To let a function return a value, use the return statement:
• Example:
def my_function(x):
return 5 * x
print(my_function(3))
print(my_function(5)) Output:
15
print(my_function(9)) 25
45
The Pass Statement in a Function
• Function definitions cannot be empty, but if you for some reason have a function definition with no
content, put in the pass statement to avoid getting an error.
• Example:
def my_function(x):
pass
Lambda Functions
Lambda Functions
• A lambda function is a small anonymous function.
• A lambda function can take any number of arguments, but can only have one expression.
• Syntax:
lambda arguments : expression
• Example:
x = lambda a : a + 10 Output:
print(x(5)) 15
Lambda Functions
• Example:
x = lambda a, b : a * b Output:
200
print(x(10, 20))
• Example:
def myfunc(n):
return lambda a : a * n
Output:
mydoubler = myfunc(2) 22
print(mydoubler(11))
Dunder/Magic Methods
Creating Class & Object in Python
• A Class is like an object constructor, or a "blueprint" for creating objects.
• Python is an object oriented programming language. Almost everything in Python is an object, with
its properties and methods.
• Syntax: Class Creation: Object Creation:
class class_name: object_name = class_name ()
#code object.property_name = value
• Example:
class MyClass:
a=5
Output:
obj = MyClass() 5
print(obj.a)
Dunder/Magic Methods
• Python Magic methods are the methods starting and ending with double underscores ‘__’.
• They are defined by built-in classes in Python and commonly used for operator overloading.
• They are also called Dunder methods, Dunder here means “Double Under (Underscores)”.
Methods Description
__new__ To get called in an object’s instantiation.
__init__ This is the constructor method, called when a new instance of the class is created.
It's typically used to initialize the object's attributes.
__del__ It is the destructor.
Dunder/Magic Methods
2) Arithmetic Operators:
Methods Description
__add__(self, other) Defines the behavior of the + operator.
__sub__(self, other) Used for subtraction (-).
__mul__(self, other) Used for multiplication (*).
__truediv__(self, other) Used for division (/).
__floordiv__(self, other) Used for floor division (//).
__mod__(self, other) Used for modulus (%).
__pow__(self, other) Used for exponentiation (**).
Dunder/Magic Methods
3) Comparison Operators:
Methods Description
__eq__(self, other) Defines the behavior of the equality operator (==).
__ne__(self, other) Defines the behavior of the inequality operator (!=).
__lt__(self, other) Defines the behavior of the less-than operator (<).
__le__(self, other) Defines the behavior of the less-than-or-equal-to operator (<=).
__gt__(self, other) Defines the behavior of the greater-than operator (>).
__ge__(self, other) Defines the behavior of the greater-than-or-equal-to operator (>=).
Dunder/Magic Methods
4) Container/Sequence Methods:
Methods Description
__len__(self) Defines the behavior of len() on the object.
__getitem__(self, key) Defines the behavior of indexing and slicing.
__setitem__(self, key) Defines the behavior of setting an item at a specific index or key.
__delitem__(self, key) Defines the behavior of deleting an item at a specific index or key.
if __name__ == '__main__’:
# object creation
Output:
string1 = String('Hello’) <__main__.String object at 0x784bfa90afd0>
# print object location
print(string1)
Dunder/Magic Methods: Example
• Example:
class String:
# magic method to initiate object
def __init__(self, string):
self.string = string
# print our string object
def __repr__(self):
return 'Object: {}'.format(self.string)
if __name__ == '__main__’:
# object creation Output:
string1 = String('Hello’) Object: Hello
print(string1)
Dunder/Magic Methods: Example
• Example:
class String:
def __init__(self, string):
self.string = string
def __repr__(self):
return 'Object: {}'.format(self.string)
def __add__(self, other):
return self.string + other
if __name__ == '__main__’:
# object creation Output:
string1 = String(‘Hello’) Hello World
print(string1 + ‘ World’)
Scope of Variable
Local Scope
• A variable is only available from inside the region it is created. This is called scope.
• Local Scope: A variable created inside a function belongs to the local scope of that function, and
can only be used inside that function.
• Example:
def myfunc():
x = 100
print(x)
myfunc()
Output:
100
Global Scope
• A variable created in the main body of the Python code is a global variable and belongs to the
global scope.
• Global variables are available from within any scope, global and local.
• Example:
x = 100
def myfunc():
print(x)
myfunc()
Output:
print(x) 100
100
Global Scope
• Naming Variable: If you operate with the same variable name inside and outside of a function,
Python will treat them as two separate variables, one available in the global scope (outside the
function) and one available in the local scope (inside the function).
• Example:
x = 100
def myfunc():
x = 200 Output:
print(x) 200
myfunc() 100
print(x)
• The function will print the local x, and then the code will print the global x.
Global Keyword
• If you need to create a global variable, but are stuck in the local scope, you can use the global
keyword.
• The global keyword makes the variable global.
• Example:
def myfunc():
global x
x = 100
Output: 100
# here, variable x belongs to the global scope
# x can also be used outside the function.
myfunc()
print(x)
Global Scope
• Also, use the global keyword if you want to make a change to a global variable inside a function.
• Example:
x = 100
def myfunc():
global x
x = 200
Output:
200
myfunc()
print(x)
Nonlocal Keyword
• The nonlocal keyword is used to work with variables inside nested functions.
• The nonlocal keyword makes the variable belong to the outer function.
• Example:
def myfunc1():
x = “world"
def myfunc2():
nonlocal x
x = "hello" Output: Hello
myfunc2()
return x
print(myfunc1())
Lists
List
• Lists are used to store multiple items in a single variable.
• Lists are one of 4 built-in data types in Python used to store collections of data, the other 3 are
Tuple, Set, and Dictionary, all with different qualities and usage.
• Lists are created using square brackets:
• Example:
thislist = ["apple", "banana", "cherry"] Output: ['apple', 'banana', 'cherry']
print(thislist)
• Example:
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
#This example returns the items from the beginning to, but NOT including, "kiwi"
print(thislist[:4])
#This example returns the items from "cherry" to the end
print(thislist[2:])
Range of Negative Indexes in a List
• Specify negative indexes if you want to start the search from the end of the list.
• Example:
#This example returns the items from "orange" (-4) to, but NOT including "mango" (-1)
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[-4:-1])
Joining Lists
• There are several ways to join, or concatenate, two or more lists in Python.
• One of the easiest ways are by using the + operator.
• Example:
list1 = ["a", "b", "c"]
list2 = [1, 2, 3] Output:
['a', 'b', 'c', 1, 2, 3]
list3 = list1 + list2
print(list3)
List Methods
Method Description
append() Adds an element at the end of the list
clear() Removes all the elements from the list
copy() Returns a copy of the list
count() Returns the number of elements with the specified value
extend() Add the elements of a list (or any iterable), to the end of the current list
index() Returns the index of the first element with the specified value
pop() Remove an element at the specified position
reverse() Reverses the order of the list
sort() Sorts the list
Tuple
Tuple
• Tuples are used to store multiple items in a single variable.
• A tuple is a collection which is ordered and unchangeable.
• Tuples are written with round brackets.
• Tuple items are ordered, unchangeable, and allow duplicate values. Since tuples are indexed, they
can have items with the same value.
• Example:
Output:
thistuple = ("apple", "banana", "cherry")
('apple', 'banana', 'cherry')
print(thistuple)
• Example:
Output:
thistuple = ("apple", "banana", "cherry", "apple", "cherry") ('apple', 'banana', 'cherry',
print(thistuple) 'apple', 'cherry')
Tuple
• Tuple items are ordered, unchangeable, and allow duplicate values.
• Tuple items are indexed, the first item has index [0], the second item has index [1] etc.
• Tuple Length: To determine how many items a tuple has, use the len() function.
• Example:
tuple1 = ("a", "b" , "c")
tuple2 = (1, 2, 3) Output:
tuple3 = tuple1 + tuple2 ('a', 'b', 'c', 1, 2, 3)
print(tuple3)
Tuple Methods
Method Description
count() Returns the number of times a given element appears
max() Maximum element in the tuple
min() Minimum element in the tuple
index() Returns the first occurrence of the given element from the tuple.
len() Returns the length of the tuple
Set
Set
• Sets are used to store multiple items in a single variable.
• Set is one of 4 built-in data types in Python used to store collections of data, the other 3 are List,
Tuple, and Dictionary, all with different qualities and usage.
• A set is a collection which is unordered, unchangeable, and unindexed.
• Set items are unchangeable, but you can remove items and add new items.
• Sets are written with curly brackets.
• Example:
thisset = {"apple", "banana", "cherry"} Output:
{'apple', 'banana', 'cherry’}
print(thisset)
Access Set Items
• You cannot access items in a set by referring to an index or a key.
• But you can loop through the set items using a for loop, or ask if a specified value is present in a
set, by using the in keyword.
• Example:
thisset = {"apple", "banana", "cherry"} Output:
for x in thisset: apple
banana
print(x) cherry
Set Methods
Method Description
set.add() adds an element to a set
set.clear() clear the elements
set.copy() returns a shallow copy of set
set.pop() remove and return a arbitrary set element
set.remove() remove an element from a set
Dictionary
Dictionary
• Dictionaries are used to store data values in key : value pairs.
• Dictionary items are ordered, changeable, and do not allow duplicates.
• Dictionary items are presented in key : value pairs, and can be referred to by using the key name.
• The values in dictionary items can be of any data type.
• Example:
thisdict = {
"brand": "Ford",
"electric": False,
"year": 1964,
"colors": ["red", "white", "blue"]
}
Access Dictionary Items
• You can access the items of a dictionary by referring to its key name, inside square brackets.
• Example:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
Output:
x = thisdict["model"]
Mustang
print(x)
Change Values in Dictionary
• You can change the value of a specific item by referring to its key name.
• Example:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
• Use a Module: Now we can use the module we just created, by using the import statement:
• Example: Import the module named mymodule, and call the greeting function
import mymodule Output:
mymodule.greeting(“John") Hello, John
Importing a Module
• Example 1:
import math Output:
print(math.pi) 3.141592653589793
• Example 2:
from math import pi Output:
3.141592653589793
print(pi)
• Example: Aliasing a module Output:
import random as rd 3
for i in range(3): 8
10
print(rd.randint(1,10))
Note: These numbers are randomly generated
and can vary after reexecuting the code.
Built-in Modules
• There are several built-in modules in Python, which you can import whenever you like:
1. collections
2. datetime
3. platform
4. math
5. numpy
6. os
7. pip
8. sys
9. time
Variables in Module
• The module can contain functions, as already described, but also variables of all types (arrays,
dictionaries, objects etc).
• Example: File name: mymodule.py
person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}
• Import the module named mymodule, and access the person1 dictionary:
import mymodule Output:
a = mymodule.person1["age"] 36
print(a)
DateTime
DateTime
• Python Dates: A date in Python is not a data type of its own, but we can import a module named
datetime to work with dates as date objects.
• Example:
#Import the datetime module and display the current date
import datetime
Output:
x = datetime.datetime.now() 2024-08-30 07:06:14.338006
print(x)
• The date contains year, month, day, hour, minute, second, and microsecond.
• The datetime module has many methods to return information about the date object.
DateTime
• Example:
#Return the year and name of weekday
import datetime
x = datetime.datetime.now()
Output:
print(x.year) 2024
print(x.strftime("%A")) Friday
Creating Date Objects
• To create a date, we can use the datetime() class (constructor) of the datetime module.
• The datetime() class requires three parameters to create a date: year, month, day.
• Example:
import datetime
Output:
x = datetime.datetime(2020, 5, 20)
2020-05-20 00:00:00
print(x)
• The datetime() class also takes parameters for time and timezone (hour, minute, second,
microsecond, tzone), but they are optional, and has a default value of 0, (None for timezone).
strftime() Method
• The datetime object has a method for formatting date objects into readable strings.
• The method is called strftime(), and takes one parameter, format, to specify the format of the
returned string.
• Example:
#Display the name of the month
import datetime
Output:
x = datetime.datetime(2018, 6, 1) June
print(x.strftime("%B"))
strftime() Method
Directive Description Example
%a Weekday, short version Wed
%A Weekday, full version Wednesday
%b Month name, short version Dec
%B Month name, full version December
%c Local version of date and time Mon Dec 31 17:41:00 2018
%C Century 20
%d Day of month 01-31 15
%f Microsecond 000000-999999 548513
%H Hour 00-23 17
%I Hour 00-12 5
%j Day number of year 001-366 360
strftime() Method
Directive Description Example
%m Month as a number 01-12 12
%M Minute 00-59 30
%p AM/PM PM
%S Second 00-59 08
%U Week number of year, Sunday as the first day of week, 52
00-53
%y Year, short version, without century 24
%Y Year, full version 2024
%Z Timezone CST
%% A % character %