0% found this document useful (0 votes)
4 views

Module 2

The document provides an overview of various Python functions for handling strings, tuples, lists, dictionaries, and sets, along with examples of their usage. It also explains how to work with text files in Python, including reading, writing, and appending data. Additionally, it covers the basics of defining and calling functions, as well as different types of function arguments.

Uploaded by

savagemaaman
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)
4 views

Module 2

The document provides an overview of various Python functions for handling strings, tuples, lists, dictionaries, and sets, along with examples of their usage. It also explains how to work with text files in Python, including reading, writing, and appending data. Additionally, it covers the basics of defining and calling functions, as well as different types of function arguments.

Uploaded by

savagemaaman
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/ 13

-l

-DLV'fA Vli A k}1 )


A-P I [ J~

~~~
STRING

String Function Description Example


· ien {) · Returns the length of a string · 1en ("Hello") · returns •5•

"lower{)· Converts a string to lowercase · "Hello" .lov,er() · returns· "hello"·

· upper()· Converts a string to uppercase · "Hello" . upper() · returns ·"HELLO"·

· capitalize () · Converts the first character to · "hello" .capitaliz e()· returns


uppercase, rest to lowercase ""Hello".
·strip()· Removes leading and trailing • 11 Hello 11 .strip()· returns · 11 Hello 11 •
whitespace

·split() · Splits a string into a list of ""Hello, World" .split(", 11 ) · returns


substrings "["Hello" , 11 World"] "
·join() · Joins elements of a list into a • 11 - 11 • join ( ["Hello", "World" J) · returns
string using a specified ""Hello-World" "
delimiter

·replace() · Replaces occurrences of a ""Hello" .replace("H " , 11


J 11 ) · returns
substring with another ""Jello"·
substring

·startswit h() " Checks if a string starts with a ·"Hello". startswith ( "H") • returns
specified prefix "True·

· end ■with() · Checks if a string ends with a • 11 Hello".endswith("o") " returns "True·
specified suffix

"find(). Searches for a substring within a · "Hello". find ( "e") · returns · 1 ·


string

·count{) · Returns the number of ""Hello" . count("l") · returns ·2·


occurrences of a substring in a
string
Function Description Example
·1eno · Returns the length of a tuple ·1en((1 , 2, 3}} · returns · 3 ·

· count(} . Returns the number of occurrences of · c1. 2, 2 , 3 , 3, 3}.count(3) "


a value in a tuple returns · 3 ·

"index() · Returns the index of the first "(1 , 2, 3, 2) . index(2) " returns ·1 ·
occurrence of a value in a tuple

·sorted(} ' 1 Returns a new sorted list from the · sorted((3, 1 , 2}) · returns · [1, 2,
elements of a tuple 3]"

'min() · Returns the minimum value in a tuple ·min((5, 2, 7}} · returns · 2 ·

'max(). Returns the maximum value in a tuple .max((5, 2, 7)} · returns ·r


· sum()· Returns the sum of all elements in a sum((1, 2, 3}) · returns · 5 ·
tuple

·tuple(}· , Converts an iterable (e.g., list) into a ·tuple([1, 2 , 3]}' returns · c1, 2 ,
tuple 3} "

· reversed () · Returns a reversed iterator of a tuple ·tuple(reversed((1, 2, 3)))"


returns • (3, 2, 1) ·

· any()· Returns ' True· if any element in the ·any((False, False , True))· returns
tuple is ' True · "True·

·all(}. Returns 'True· if all elements in the · all((True , True , False))" returns
tuple are ·rrue · "False·
List
Function Description
Example
· len O • Returns the length of a list · 1en([1, 2, 3)) · returns · 3·

· append () · , Adds an element to the end of a list ·c1. 2J . append(3)' modifiesthelistto


. [1, 2 , 3)"

·extend() · Extends a list by appending ' [1, 2].extend([3 , 4]) ' modifiesthe
elements from another iterable listto · c1, 2, 3 , 4]"

' insert() · Inserts an element at a specified · [1, 2, 3] .insert(1, 4) · modifies the


position in a list listto · c1, 4, 2, 3]'

· remove() · Removes the first occurrence of a · [1, 2, 3, 2] .remove(2) · modifies the


specified element list to ·u. 3, 2]"

·pop(). Removes and returns the element at · [1, 2 , 3] . pop(1)' modifies the list to
a specified position · [1, 3] · and returns ·2·

"index{)· Returns the index of the first ·c1. 2 , 3] . index(2)' returns ·1 ·


occurrence of a value

·.count()· Returns the number of occurrences · [1, 2, 2, 3 , 3, 3] . count(3) · returns


of a value in a list ·3·

· sort{) · Sorts the elements of a list in ·sorted([3, 1, 2]) " returns · c1, 2,

ascending order 3]"

·reverse()· Reverses the order of elements in a · c1. 2, 3J.reverseo· modifiesthelist

list to • (3, 2, 1] ·

· copy() · Returns a shallow copy of a list ·new.list = old.list.copy()· creates a


new list

·clear() · Removes all elements from a list ·c1, 2, 3].clear() "modifiesthelistto

·er
D1ot1onary
Function Description EX4mple
· len() ·
Returno the number of kay· v11lue ' ltn({'•' : 1, 'b' : 2)) ' return'.'. 2 ·
p11lm In a d1ct1onory

"keys() " Relurna a Hat of nll keyo In 11 ( '•' : 1 , 'b' : 2} . keyc ( ) return,
dictionary . ( 'e I . I bI J
· values() ' Return:; a llct of ull value::i 1n 11 ('a' : 1 , ' b ' : 2} . valuu() · rewr~
d1ct1onary ' [1, 2] .

"ite111s () · Return:: a li::t of all key-value ('a' : 1 , ' b ' : 2} .iteai () · rru rn:;
pairs in a d ic tionary ' (( ' a', 1) . ('b', 2)) .

·get ()· Return:: the value asooc1ated ' ('a ' : 1 , ' b ' : 2} . get( ' a ' ) ' r~...rn-: · 1 ·
with a specified key
. pop() . Removes and return:. the value ( ' a ' : 1 , ' b ' : 2) . pop ( ' a ' ) · re ~ ,~
associated with 11 specified key and re-turn:: · 1 ·

" popite ■ (). Removes and returns the last ' { ' a ' : 1 , 'b ' : 2} . PQ"pites () ~ 1'10"~

inserted key-value pair from a and retu•n:; · ( ' b ' , 2) ·


dictionary

· update()· Updates a d ictionary with key- · c•a•: 1) . update (C ' b ' : 2}} · noc~-es

value pairs from another the dictionary to ·c •a•: l , ' b ': 2)"
d ictionary

· c1u..r() . Removes all key-value pairs from · c•a• : 1. ' b ': 2} . c.leu (} ' m:::,:!:f~~t.~
a d ictionary dictionary to • {} ·

copy( ) · Return~ a shallow copy of a · new_dict ,. old _d.ict . cepy () · ~~es!

d1ct1onary new d1ctioru.ry

Creat~s a new dict1 on'-\ry with ' dict . ttoua y•(( 1 11 1 • ' b ') . 0 }. ~ - 'TIS

:;p~c1f1ed key= and a d efault "( ' a ' : 0 , ' b ' : 0} '

v~luc
Set Function Description Example

'len () • Retu rns the number of · 1en{ (1 , 2 , 3}) ' returns · 3 ·

elem ents in a set

, · add () · Adds an element to a ·u, 2} . add {3) " modifies theset to

set ·u, 2. 3J"

· rem ove{ ) ' Removes an element "(1, 2 , 3}.r emo ve(2 ) · modifies the

from a set sett o · u. 3} "

• (1, 2, 3} . disc ard (2) · modifies


the
·dis car d() · Removes an element
' from a set if it is present set to •{1, 3} ·

· pop {) . Removes and returns · (1, 2 , 3} . pop () · removes and

an arbitrary element returns an element

from a set

· (1, 2, 3} . clea r() · modifies the


set
' clea r{) · Removes all elements
from a set to an empty set

·u, 2} . unio n((2 , 3}) · returns ' {1 ,


· unio n() ·
, Returns the union of
2, 3}.
two sets
'(1, 2} . inte rsec :tion ((2, 3})"
Returns the
'int ers ecti on( ) ·
returns •{2} ·
inte rsection of two sets
'(1, 2} . diff eren ce(( 2 , 3}) " retur
ns
Returns the difference
"dif fere nce () '
between two sets • (1} ·
Working with text files in Python involves reading data from text files or writing data to text files.
Python provides built-in functions and methods to perform these operations. Here's an overview
of how to work with text files in Python:

Reading Text Files:


To read data from a text file, you can follow these steps:

1. Open the file using the · open()' function, specifying the file path and mode ('r' for reading).
2. Read the contents of the file using methods like ·read()' , ·readline(r , or ·readlines()·.

# Example: Reading from a text file


file_path = "file.bet"
with open(file_path, 'r1 as file:
content = file.readO # Read the entire file
# Or, read line by line using readlineO
# line = file.readlineO
# Or, read all lines into a list using read/inesO
# lines = file.readlinesO
print(content)

Writing to Text Files:


To write data to a text file, you can follow these steps:

. Open the file using the ·open()· function, specifying the file path and mode ('w' for writing or
1
'a' for appending). . . . . . . . .
2. Wne
·t the data to the file using methods like write() or wntehnes() .

# Example: Writing to a text file


file_path = "fi/e.txt• .
with open(fi/e_path, 'w? as file:
file. write("Hello, World/In")
file.write("This is a new line.")

Appending to Text Files: t ·sting text file without overwriting the existing content, use
If you w ant to append data o an ex,
the 'a ' m ode when opening the file .
# Example: Appending to a text file
flla_path = "fl/e.txt"
with open(fi/e_path, 'a') as file:
flle.write("Thls Is appended text. ")

It's important to handle file operations within a 'with' statem


ent, which automatically handles
closing the file after the block Is executed, ensuring prope
r resource management.

These are the basic operations for working with text files
In Python.
7/14123, 9:41 AM
FUNCTION.ipynb - Colaboratory

Creating a Function In Python a function Is defined using the def keyword:


Example

def my_functlonQ: prlnt("Hello from a f4nctlon')

Calling a Function To call a function, use the function name followed by parenthesis:
Example is given below:

def my_function() :
pr i nt("Hello from a functi on")

my_function( )

Hello f r om a fun ction

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, juS1 separate them wrth
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:

def my_f unction(fname ) :


pri nt (fname + " S6 CS E" )

11y_function( "Abhiram")
rny_fu nction( "Adarsh" )
11y_funct ion( "Aj i t h")

Abhira11 S6 CSE
Adarsh S6 CSE
Ajith S6 CSE

Parameters or Arguments? The terms parameter and argument can be used for the same thing: information that are passed into a function.

From a function's perspective:

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.

Types of function arguments There are various ways to use arguments in a function. In Python, we have the following 4 types of function
arguments.

1. Default argument
2. Keyword arguments (named arguments)
3. Positional arguments
4 . Arbitrary arguments (variable-length arguments args and •kwargs)
v"" • -·
FUNCTION.Jpy11 0 - v

7I I J /2:J , 9;q 1 AM

Function nam e De fou ll argum ent


r-17
I
I
I
, Function
c, d=L.10):
'it
de f my_sum(a, b, d +
t -definitio n
re tu rn a + b + C

(10, 20 , c=30 )
Function -~ my_sum ...__ .J, L, -- 1
call
Pos itional keyword
arguments argument s
20
uence. Now a,.10 and b-
on al argum en t values ge t assigned as per tho seq ign ed to the arg um ents by
Posltl en ts wh ere values get ass
those arg um
Keyword arguments are
their keyword erator at the time
n defau lt values to the argum ent usi ng the '• ' op
Default arguments ; As
sig
of function definition

DEFAULT ARGUMENTS

It def aul t argumen t s


def add (a• S,b ,c):
prin t(a+ b+c )
add (lS ,29 )

-89dd644S a5b7>", lin e 2


Fil e "<ipython-input-6
def add (a• S, b, c) :
s def aul t argument
fau lt argument foll ow
Syn tax frro r: non -de

FI.OW
SEARCH STACK 0\IER

It def aul t arguments


def add (a,b, c•l l):
pri nt( a+b+c)
add (lS , 29)

46

• def aul t arguments


def add (a,b ,c• ll) :
prin t(a+ b+c )
add (lS, 29)

46

NTS
POSITIONAL ARGUME

ument s
# POS ITI OIIAl arg
def add (a, b):
pri nt( a • b)

a dd( S0, 10)


• Output 40

add (19 , S0)


# Out put -40

40
40

der add ( o , b) :
prl nt ( a • b)

l~1. 1tnr intAAnt1 Az fn IA


mlr lrlu / 1 S::
,..-:-, r h nn~ nlo r n 1?~ 1nT nn" 11\/ nhh
h tl ~ · //rn l:1h ,,.., ,. J..4 n\l) (Plrl. , 1J\lr1 k''1
II 1-1/L;J, !l:4 1 AM
FUNCTION,lpynb - Colaboratory
odd( l OS, S61 , 4)

Typc Error - - -- ----- Trac eback (~os t r ecent call l ast )


d pyt hon - i nput-10 - cddb6ca 0b760> in <cell line :
4>()
2 prlnt(a - b )

· · ··> 4 add(l0S, 561, 4)

lypeErr or: add () t akes 2 pos i tional argument s


but 3 were give n

SEARCH STACK OVERFLOW

KEYWORD ARGUMENTS

• function with 2 keyword argumen ts


def s tudent ( name , age) :
print( ' Student De t ail s: ' , name , age)

; de f ault functio n call


student ( 'Nit hya ' , 20)

# both keyword argumen ts


student (namc• ' Hussain ', age•22)

# 1 pos itiona l and 1 keyword


student ( 'Hari ', age• 21)

Student De tails: Ni t hy a 20
St udent Det ails : Hussai n 22
Student Details : Hari 21

Variable-length arguments In Python, sometimes, there is


a situatio n where we need to pass multiple arguments to the
function. Such types of
arguments are called arbitrary arguments or variable-length
arguments.
We use variable-length arguments If we don't know the number
of arguments needed for the function in advance.
Types of Arbitrary Arguments:

1. arbitrary position al arguments (*args)


2. arbitrary keyword argume nts (**kwarg s)

def 11yFun( •a r gs ):
for arg in args:
print(a r g)

o,yfun( ' Hello ' , ' Welcome' , 'to ' , 'Geeksfo rGeeks
')

Hello
Wel cOOle
to
Geeksfo rGceks

def myFun ( .. kwa rgs ) :


prlnt ( " kwa r gs: •, kwargs )

# N<Jw we can use both •args , ••kwar gs


P to paH argume nts to this func tion :
myFun(f i r st•"I" , mid• "LOVE", las t■"PYTHON" )

kwargs: { 'fir st ': 'I ' , ' mi d ': ' LOVE ' , 'last ': 'PYTHON' }

d•f myFun( •args, .. kwa rgs):


prlnt( "ares: ", args)
print ( "k>1arKS : •, kw,1rgs )

• tiow w~ <.an use both ..,;1r gs , • • kwc1rgs


• to pt1•, •1 -trgu~n l r. to th i5 functio n
ll'J f un( ' I' , ' l(JI/ ~ ' , • PYTHON. , rt rs t•" t ", mid• " LOVE" , l as t • "PYTHON" )
" l "f/,CJ, tJ:41 AM !?'I
FUNCTION.lpynb - Colaboratory
args: ('I', 'LOVE ' , ' PYTHON')
kwargs: {' first': 'I ' , ' mid':
' LOVE', 'last ': 'PYTHON'}

RECURSIVE FUNCTIONS

In Python, a recursive function is a function that calls its If d I . .


·· e ur ng its execution Recursive f er
be d1v1ded into smaller, similar subproblems . · un ions are useful when solving problems that can
Here's the syntax for defining a recursive function In Python:

def recursive_function(parameters}:
# Base case(s) : Terminating condition(s)
if base_case_condition: th at do not
make a recursive call
return base_case_value

# Recursive case(s): Perform recursive calls with modifi d


# Combine result f e parameters
s rom r ecursive calls t o obtain the final result
recursive_result = recursive function( difi d
- mo e _parameters)
fina 1_result = combine_results(recursive_result, other_values)
return final_resul t

EXAMPLE

def factorial ( n) :
if n == 0: # Base case: factorial(0) is 1
return 1
else:
return n • factorial(n - 1) # Recursive case

# Calculate factorial of s
result = factorial(S)
print (result) # Output: 120

c~ 120
- - - - - - - - - - - - - - - - - - - - - -. + Code :--' + Text :-
. - - - - - -- - - - - -- - - - - - --
Double-click (or enter) to edit

*Higher-order functions*
functions that can take other functions as arguments or return functions as their results. They allow functions to
operate on other functions.
making it possible to encapsulate behavior and create more flexible and reusable code.
Here are a few examples of higher-order functions:
1. mapQ: The mapO function takes a function and an iterable as arguments, and applies the function to each element
in the iterable,
returning a new iterable with the results. It allows you to transform each element in a collection based on a given
function.

# Example: Squaring each element in a list using map()


numbers • (1, 2, 3, 4, 5)
squared_numbers = list(map(lambda x: x••2, numbers))
print (squared_numbers) # Output: (1, 4, 9, 16, 25]

[l, 4 , 9, 16, 25]

2. filterO: The filterO function takes a function and an iterable as arguments, and returns an iterator containing the elements
from the iterable
for which the function returns True. It allows you to filter elements based on a given condition.

R Exam ple : Fi ltering even numbers from a list using filter()


numbers • [1, 2, 3, 4, SJ
even_numbers = llst (filter( l ambda x: x X 2 •• 0, numbers))
pri nt(even_numbers) U Output : [2, 4]

[2, ,q

'.l. reduceQ: The reduceO function, available In the functools module, applies a function to an iterable, reducing it to a single value.
It
performs pairwise operations on the elements of the iterable until only one value remains.

4 1~
7/1 412.3, 9 :41 AM FUNCTION.lpynb - Colaboralory

• Example : Calculating t he product of clc111ents in a list using reduce()


froa functools import reduce
nu~bers • ll, l, 3, 4, S)
product • reduce(la~bda x, y : x • y, number s)
print(product) • Output : 110 (l • l • 3 • 4 • 5)
5, X

You might also like