Module 2
Module 2
~~~
STRING
·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
"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]"
·tuple(}· , Converts an iterable (e.g., list) into a ·tuple([1, 2 , 3]}' returns · c1, 2 ,
tuple 3} "
· 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·
·extend() · Extends a list by appending ' [1, 2].extend([3 , 4]) ' modifiesthe
elements from another iterable listto · c1, 2, 3 , 4]"
·pop(). Removes and returns the element at · [1, 2 , 3] . pop(1)' modifies the list to
a specified position · [1, 3] · and returns ·2·
· sort{) · Sorts the elements of a list in ·sorted([3, 1, 2]) " returns · c1, 2,
list to • (3, 2, 1] ·
·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"~
· 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 • {} ·
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
· rem ove{ ) ' Removes an element "(1, 2 , 3}.r emo ve(2 ) · modifies the
from a set
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()·.
. 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() .
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. ")
These are the basic operations for working with text files
In Python.
7/14123, 9:41 AM
FUNCTION.ipynb - Colaboratory
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( )
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:
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.
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
(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
FI.OW
SEARCH STACK 0\IER
46
46
NTS
POSITIONAL ARGUME
ument s
# POS ITI OIIAl arg
def add (a, b):
pri nt( a • b)
40
40
der add ( o , b) :
prl nt ( a • b)
KEYWORD ARGUMENTS
Student De tails: Ni t hy a 20
St udent Det ails : Hussai n 22
Student Details : Hari 21
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
kwargs: { 'fir st ': 'I ' , ' mi d ': ' LOVE ' , 'last ': 'PYTHON' }
RECURSIVE FUNCTIONS
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
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.
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.
[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