0% found this document useful (0 votes)
14 views20 pages

Unit 4

This document provides an overview of Python functions, modules, and packages, detailing various string methods, built-in functions, user-defined functions, lambda functions, and the concepts of namespace and scope. It explains how to create and use modules and packages to organize and manage code effectively. Additionally, it covers string formatting techniques and the importance of maintaining a structured approach in larger projects.

Uploaded by

Siddhesh Rasane
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)
14 views20 pages

Unit 4

This document provides an overview of Python functions, modules, and packages, detailing various string methods, built-in functions, user-defined functions, lambda functions, and the concepts of namespace and scope. It explains how to create and use modules and packages to organize and manage code effectively. Additionally, it covers string formatting techniques and the importance of maintaining a structured approach in larger projects.

Uploaded by

Siddhesh Rasane
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/ 20

Unit–IV

Python Functions, Modules and Packages


14 marks
Strings
All string methods returns new values. They do not change the original string.
Method Description

capitalize() Converts the first character to uppercase

title() Converts the first character of each word to uppercase

casefold()/lower() Converts strings in lowercase

upper() Converts strings in uppercase

swapcase() Toggles the case of string

count() Returns the number of times the specified value occurs in the string

index() Searches the string for a specified value and returns the position of where it was found

find() Searches the string for a specified value and returns the position of where it was found # does not raise error

rindex() Searches the string for a specified value and returns the last position of where it was found

rfind() Searches the string for a specified value and returns the last position of where it was found # does not raise error

strip()/rstrip() Removes the leading and trailing/only trailing spaces of the string and the given characters , if specified

split()/rsplit() Splits the string at the specified separator, and returns a list

splitlines() Splits the string at line breaks and returns a list

join() Joins the elements of an iterable to the end of the string


Method Description

maketrans() Returns a mapping table that can be used with the translate() method to replace specified characters

translate() Returns the translated string

ljust()/rjust() Returns a left justified version of the string

partition()/ rpartition() Returns a tuple where the string is parted into three parts

replace() Returns a string where a specified value is replaced with a specified value

zfill() Fills the string with a specified number of 0 values at the beginning

center() Returns a centered string

format() Formats specified values in a string

endswith() Returns True if the string ends with the specified value

startswith() Returns True if the string starts with the specified value

isalpha() Returns True if all characters in the string are in the alphabet

isdigit()/isnumeric() Returns True if all characters in the string are digits/(Considers other language digits, fr ex. Chinese)

isalnum() Returns True if all characters in the string are alphanumeric

isidentifier() Returns True if all characters in the string is an identifier

isspace() Returns True if all characters in the string are whitespaces

islower() Returns True if all characters in the string are lower case

isupper() Returns True if all characters in the string are upper case
String Formatting
• format() method
The format() method formats the specified value(s) and insert them inside the string's placeholder.
The placeholder is defined using curly brackets:{}
#named indexes:
txt1 = "My name is {fname}, I'm {age}".format(fname = "John", age = 36)
#numbered indexes:
txt2 = "My name is {0}, I'm {1}".format("John",36)
#empty placeholders:
txt3 = "My name is {}, I'm {}".format("John",36)

#without format method:


>>>n=5
>>>print(f “{n} * 3 = { n*3}”)
String Formatting (contd….)

• format specifier operator (%)

Format Specifier Meaning


%c Character
%d Integer
%i Signed decimal integer
%u Unsigned decimal integer
%o Octal integer
%x or %X Hexadecimal integer
%f Floating point real number
%s String
Built-in functions
Function
int(), float(), complex(), bool()
str(), list(), tuple(),set(), dict()
bin(), oct(), hex()
min(), max(), sum(), len()
sorted(), reversed()
print(), input(), range(), type()
abs(), pow(), round(), divmod()
enumerate(), eval()
type(), id(), dir()
locals(), globals()
isinstance(), issubclass(), super()
iter(), next()
open(), help()
User defined functions
• A function is a block of code which only runs when it is called.
• Information can be passed into functions as arguments. Arguments of a function can be of any
data type (string, number, list, dictionary etc.)
• Python also accepts function recursion, which means a defined function can call itself.
• A function can return multiple data as a result, using the return statement
• In Python a function is defined using the def keyword
• To call a function, the function name is followed by parenthesis

def greet():
print("Hello from a function")

greet()
• By default, a function must be called with the correct number of arguments/parameters.

def add(a,b,c):
print(a+b+c)

add(a,b,c)

• Arbitrary arguments: If many arguments are passed to the 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

def marks(*k):
print(“Percentage marks = " , (k[0]+k[1]+k[2]+k[3])/4)

marks(54, 67,89,34)
• Keyword Arguments: You can also send arguments with the key = value syntax.
This way the order of the arguments does not matter.

def emp_info(name, age, salary):


print(“Emp salary is “, salary)

emp_info(salary=5000, age=35, name=“John”)

• If there are many keyword arguments passed to the function, add two asterisk ** before the
parameter name in the function definition. This way the function will receive a dictionary of
arguments, and can access the items accordingly,

def emp_info(**emp)
print(“Emp salary is”, emp[“salary”]

emp_info(salary = 5000, name=“John”, age=35)


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

def welcome(country = "Norway"):


print(“Good Morning " , country)

welcome("Sweden")
welcome("India")
welcome()
welcome("Brazil")
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.

def add(x):
x = x + 10 add = lambda x : x + 10
return x print(add(5))
print(add(5))

f = lambda x, y : x * y f = lambda x, y, z : x + y + z
print(f(15, 20)) print(f(8, 9, 10))
• The power of lambda is better shown when you use them as an anonymous
function inside another function.

def fun(n): def fun(n):


return lambda a : a * n return lambda a : a * n

double = fun(2) double = fun(2)


triple = fun(3)
print(double(11))
print(double(10))
print(triple(10))
Namespace and Scope
• Namespace is a collection of names
• Different namespaces can co-exist at a given time but are completely isolated.
• A local namespace is created when a function is called, which has all the names defined in it.
• When a reference is made inside a function, the name is searched in the local namespace, then in
the global namespace and finally in the built-in namespace. If there is a function inside another
function, a new scope is nested inside the local scope.
Modules in Python
• A module is a file with .py extension, containing Python statements and definitions
• We use modules to break down large programs into small manageable and organized
files. Furthermore, modules provide reusability of code.
• We can define our most used functions in a module and import it, instead of copying their
definitions into different programs.
• We can use the module by using the import statement
import module1

sum = module1.add(x,y)
print(sum)
• Or import only only parts from a module using the from keyword
from mymodule import person1

print (person1["age"])
Modules and Packages
• As we create more and more classes we need a way to organize them in such a
way to make them available and easy to find
• Modules in Python are simply files, if you have two files in the same folder we can
load a class from one module for use in the other module
• So, for example , if we are building an e-Commerce system and we create a single
file (module) that contains all the classes and methods related to accessing the
database, then as long as all the other necessary modules (product, customer
inventory classes) are in the same folder, those modules can use the database
module to access the database
• As projects get larger and larger it becomes more and more difficult
to organize all of the modules (Python files) in a single folder.
• To help us with this issue, Python allows you to organize your
modules into sub-folders called packages. The name of the package is
the name of the folder
• To achieve this we place a file called __init__.py in each sub-folder we
wish to be included in the project. The __init__.py file contains the
contents of the package when its treated as a module. It can be left
empty.
myprg.py

module1.py

module2.py
Packages in Python
• As our application program grows larger in size with a lot of modules, we place similar
modules in one package and different modules in different packages. This makes a
project (program) easy to manage and conceptually clear.
• Similarly, as a directory can contain subdirectories and files, a Python package can
have sub-packages and modules.
• A directory must contain a file named __init__.py in order for Python to consider it as
a package. This file can be left empty but we generally place the initialization code for
that package in this file.
• A package can be globally installed for system-wide use by running the setup script.
The script calls setup() function from the setuptools module.

You might also like