0% found this document useful (0 votes)
3 views14 pages

Python

The document provides an overview of Python operators, including arithmetic, logical, relational, assignment, membership, and identity operators, along with examples. It also covers lists, tuples, and strings, detailing their creation, manipulation methods, and built-in functions. Key operations such as indexing, slicing, and various list methods are explained to enhance understanding of Python's data structures.

Uploaded by

thehaloyt890
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)
3 views14 pages

Python

The document provides an overview of Python operators, including arithmetic, logical, relational, assignment, membership, and identity operators, along with examples. It also covers lists, tuples, and strings, detailing their creation, manipulation methods, and built-in functions. Key operations such as indexing, slicing, and various list methods are explained to enhance understanding of Python's data structures.

Uploaded by

thehaloyt890
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/ 14

▪ Python Operators

• Arithmetic operator:-
a) +
b) –
c) *
d) / e.g.-> c=a/b (5/3=1.667)
e) ** (exponent) e.g.-> 5**3= 53 = 125
f) // (floor division) e.g.-> 5//3 = 1
Floor:
For +ve number, after the division part of the number removed and the
number stay same.
e.g.->5/2 = 2.5 but 5//2 = 2
4/3 = 1.33 but 4//3 = 1
3/4 = 0.75 but 3//4 = 0
For –ve number, after the division part of the number removed and the
number decreased by 1.
e.g.->-4/3 = -1.33 but -4//3 = -2
-4/5 = -0.8 but -4//5 = -1
g) % (modulus/ remainder) e.g.->5%3 = 2, 5.0%3 = 2.0, 5%6 = 6(if L<R, %, L)
• Logical operator:-
a) and
b) or
c) not
• Relational operator:-
a) <
b) >
c) <=
d) >=
e) ==
f) !=
• Assignment/Shorthand operator:-
a) +=, e.g.-> a+=b ⇒ a =a+b
b) -=, e.g.-> a-=b ⇒ a=a-b
c) /=, e.g.-> a/=b ⇒ a=a/b
d) *=, e.g.-> a*=b ⇒ a=a*b
e) **=, e.g.-> a**=b ⇒ a=a**b⇒ ab
f) //=, e.g.-> a//=b ⇒ a =a//b
g) %=, e.g.-> a%=b ⇒ a =a%b
• Membership operator:-
a) in
e.g.-> 5 in [4,3,7,5], True
6 in [4,3,5,7], False
b) not in
e.g.-> 5 not in [4,3,7,5], False
6 not in [4,3,5,7], True
• Identity operator:-
a) is
b) not is

1|Page
▪ List Notes
• Declaring directly:-
e.g.->a=[]
• Using the list constructor:-
e.g.->a = list()
• Forward index -> 0 ,1, 2, 3……..
• Backward index-> -4, -3, -2, -1

• List arithmetic:-
1. Addition of two different list :-
L1= [1,7,5]
L2= [2,7,5]
L3 = L1+L2 -> [1,7,5,2,7,5]
2. Repeating of a list :-
L = [2,1,3]
J= L**2 -> J = [2,1,3,2,1,3]
3. Slicing of list :-
Syntax-> var = [start: stop: step]
e.g.-> l = [1,2,3,4,5,6,7]
i. k = l[3:]=[4,5,6,7]
ii. k = l[1:5]=[2,3,4,5]
iii. k = l[-1:-3] =[7,6]
iv. k = l[1:6:2]=[2,4,6]
v. k = l[::]=[1,2,3,4,5,6,7]
vi. k = l[::-1]=[7,6,5,4,3,2,1](reversing an array)

• Creating list from string:-


Syntax: var = list(string)
e.g.-> s = ‘mango’
l = list(s) -> [m, a, n, g, o]
• Taking input from user in list form using eval() function:-
Syntax: var = eval(input (“Enter the list element in list form”))
• To display all element in a list:
Syntax: for <loop var> in <list var>:
print(<loop var>)
e.g.-> l = [100,200,300,400] (output) 100
for p in l: 200
print(p)
300
400
• Length of a list: using len() function:-
Syntax: var = len(array)
e.g.-> l = [1,25,8648,5]
b= len(l)
print(b)-> output: 5
• Nested list:-
L = [2,5, [7,8,9],10,11]

->L[2][1]->9
2|Page
• List method:-
1) Index() method{if you give the element, you will get the position of the element)
e.g.-> l = [1,23,4,5,6,7]
l.index(23)-> 1
2) append() method{To add element at list, tuple , dictionary or any data type}
3) extend() {method to add lists elements to another list}
e.g.-> l1 = [1,2,3]
l2 = [4,5,6]
->l1 = extend(l2)-> l1 = [1,2,3,4,5,6]
4) insert() {method used to insert one or more element at a particular position}
syntax: list.insert(position, element)
e.g. -> l = [1,2,3,4]
l.insert(2,7) -> output => [1,2,7,3,4]
5) pop() {method to remove an element from the end of the list}
e.g. -> l = [2,4,6,8,10]
l.pop() -> removes 10 -> [2,4,6,8]
6) remove() {method to remove the first occurrence of an element }
e.g. -> l = [5,10,15,25,15]
l.remove(15) -> [5,10,25,15]
7) clear() {method to remove all the elements inside)
e.g. -> l = [2,4,6]
l.clear() ->l=[]
8) reverse() {method to reverse the list}
e.g. -> l = [5,4,3,2,1]
l.reverse() -> [1,2,3,4,5]
9) sort() {method to sort elements in ascending and descending order}
e.g. -> l = [5,6,1,2,4]
l.sort() -> [1,2,4,5,6]
{sort() to sort the elements of a list}
10) sorted() {method use the elements of different data types}
e.g. -> L = [2,7,1,0,5]
sorted(l) -> l = [0,1,2,5,7]

11) del {keyword to delete an entail list}


e.g. -> l = [1,2,3]
del l ->{removes the list}

3|Page
▪ Tuples
Note: Tuples are immutable sequences.
• Empty tuples:-
T = () or T = tuple()
• Only one tuple
T = (9,) or T = 9,
• Tuples of integers:-
a) T = (7,8,9,10) or T = 7,8,9,10
b) T = tuple(7,8,9,10)
• Tuple of characters:-
T = ('a','b','c') or T = 'a','b','c'
Note: Creating a tuple from a set of values is called packing. Accessing or creating individual values
from a tuple's element is called unpacking.
• Creating a tuple from string:-
k = 'Snehasish'
m = tuple(k) -> ('S', 'n', 'e', 'h', 'a', 's', 'i', 's', 'h')
• Creating a tuple from a list:-
Y = [1,2,3,4]
T = tuple(Y) -> (1,2,3,4)
• Accepting tuple from the user:-
t1 = tuple(input("Enter values: ")) -> Enter values: 24567 - > t1 -> ('2', '4', '5', '6', '7')
or,
t1 = eval(input("Enter values:")) -> Enter values:(4,"Good",[2],'a') -> t1 -> ( 4, 'Good', [2,], 'a')
• Traversing the tuple:-
T = (2, 4, 'Good', [2, 4, 6], 'a')
for i in T:
print(i)
• Joining two tuples:- • Count number of repetition:-
t1 = (1,2,3) t2 = (4,8,7,6,4,2,4)
t2 = (4,5,6,) t2.count(4) -> 3
t = t1+t2
t = (1,2,3,4,5,6)

• Multiplying a tuples:-
m= t1 * 3
m = (1,2,3,1,2,3,1,2,3)
• Length of a tuple:-
len()
len(t1) -> 3
• Finds the maximum number in the tuple:-
Max()
max(t1) -> 3
• Finds the minimum number in the tuple:-
min(t1) ---> 1
Note: +ve index 0 1 2 3 4 && -ve index -5 -4 -3 -2 -1
• Finds the index of a number:-
t3 = (7, 2, 1, 8, 3)

4|Page
t3.index(8) -> 3

▪ String
Note: String is alphanumeric set of characters.
Strings are enclosed within the single quotes, double quotes, triple single or triple double
quotes. Triple single or triple double quotes are also called docstrings. They are used as
multiline comments or multiline inputs. Strings are set of immutable characters. That is the
characters cannot be changed on once they are declared
Example:
a = 'Aarish Biswas'
b = "Ranjoy Biswas"
c = '''Srihan
Kumar
Nath
'''
d = “””
Shreyan
Nag
Computer
Class “””
• Taking input as String:-
k = input("Enter your name: ")
print(k)
Enter your name: Aaron Black -> (output)Aaron Black
Note:- m = " A p p l e" +ve index 0 1 2 3 4-ve index -5 -4 -3 -2 -1 syntax is variable[start:stop:step]
by default stop is always less by 1 than the given value and step value is always 1 by default. Start
value is always the beginning or the starting index 0
Example:
m = "Apple"
print(m[0]) #A
print(m[0:]) #Apple
print(m[::]) #Apple
print(m[1:]) #pple
print(m[-4:]) #pple
print(m[-4:4]) #ppl
print(m[::-1]) #elppA
print(m[::-2]) #epA
print(m[-2::-2]) #lp
• Length of the string:-
m = input("Enter a string: ")
print(len(m))
(Output)Enter a string: Quick Brown Fox Jumps Over The Lazy Dog -> 39
• Traversing a string:-
a) Method 1
m = "Good Evening"
for i in m:
print(i,end=' ')
print("#")
G#

5|Page
o#
o#
d#
#
E#
v#
e#
n#
i#
n#
g#
Note:- end=' ' the characters will be placed side by side
by default, end='\n'
'\n' means new line

b) Method 2
m = "Dr Doom"
for i in range(0,len(m)):
print(m[i],end='')
(output)Dr Doom
c) Method 3
m = "Robert Downey Junior"
p = len(m)
for i in range(-p,0):
print(m[i],end='')
(output)Robert Downey Junior
• String concatenation:-
s = 'Ms'
s1 = ' Marvel'
s2 = s + s1
print(s2)
(output)Ms Marvel
• membership finds the presence or absence of a character in a string:-
m = "Good Night"
print('i' in m)
print('z' in m)
print('i' not in m)
print('z' not in m)
(output):True
False
False
True
Note:-ASCII or American Standard Code For Information Interchange
'A'-'Z' : 65 - 90
'a'-'z': 97 - 122
'0'-'9': 48 - 57
' '(blank space): 32
Suppose you want to find the ascii code of P, trick is 64 + count of the alphabet => 64 + 16(P) => 80
Suppose you want to find the ascii code of d, trick is 96 + count of the alphabet = > 96 + 4 => 100

6|Page
Note:- chr() function converts a ascii code to the appropriate character
ord() means ordinal number. This function finds the ascii code of each character
• String functions:-
k = input("Enter a sentence:")
print(k.isalpha())
# isalpha() checks a string is composed of letters only or not space is not a letter that why
it give you answer false #

print(k.isdigit())
# isdigit() checks a string is composed of integers only or not #

print(k.isalnum())
# isalnum() checks a string is composed of letters or digits or both #

print(k.islower())
# islower() check a string is smaller letter or not #

print(k.isupper())
# isupper() checks a string is uppercase letters or not #

k = input("Enter a string: ")


print(k.lower())
# converts entire string to smaller letters #

print(k.upper())
# converts entire string to capital letters #

print(k.capitalize())
# converts the string to sentence, meaning word's first alphabet will in captal letter #

print(k.title())
# converts the string to sentence, converts each word's first alphabet to capital letter #

print(k.swapcase())
# each alphabet will be converted to small and capital interchangeably #
• Some more fuctions:-
1. replace(old,new) fuction to replace a word in a linestring
e.g. -> k="Blue Bag Blue Ball"
print(k.replace("Blue","Red")) ->(output)Red Bag Red Ball
2. isspace() function check a character is space or not
e.g.-> k = " "
print(k.isspace()) -> (output)True
k = 'Jai Hitler'
print(k.isspace()) -> (output)False
3. find() function find the index of a string only the first chracter's index
e.g.-> k = "The Quick Brown Fox Jumps Over The Lazy Dog"
s = k.find("Oil")
print(s) -> (output)-1 # if the string is not present then it returns -1 #
s = k.find("Over")
print(s) -> (output)26
7|Page
4. count() counts the repetition of a given string in sentence
e.g.-> k = "The Quick Brown Fox Jumps Over The Lazy Dog"
p = k.count("The")
print(p) -> (output)2
5. split() function breaks a sentence in list of words
syntax: <string>.split(<separator>,<maxsplit>)
e.g.-> s = "Jack and Jill went up the hill"
print(s.split()) ->(output) ['Jack', 'and', 'Jill', 'went', 'up', 'the', 'hill']
s="Good@Morning@India@2050"
print(s.split("@",2)) ->(output) ['Good', 'Morning', 'India@2050']
6. partition() function breaks a string into three elements in a tuple
e.g.-> m = "Jack and Jill went up the hill"
print(m.partition("and")) -> (output) ('Jack ', 'and', ' Jill went up the hill')
# in partition() if a string is not present then the first element will be the
whole s string second and third element will be empty string #
print(m.partition("green")) -> (output) ('Jack and Jill went up the hill', '', '')
7. strip() function is used to remove the leading and preceding whitespace(by default)
# if a character is mentioned it is removed from left and right inthe string #
e.g.-> s = " Good Evening "
print(s.strip()) -> (output) Good Evening
s="-------Good-Evening-----"
print(s.strip("-")) -> (output)Good-Evenin
8. lstrip() function removes the whitespaces from the left hand side
# if a character is mentioned that is removed from the left side #
e.g.-> s="***Good-Evening$$$$"
print(s.lstrip("*")) -> (output) Good-Evening$$$$
9. rstrip() function removes the whitespaces from the right hand side
# if a character is mentioned that is removed from the right side #
e.g.-> s="***Good-Evening$$$$"
print(s.rstrip("$")) -> (output) ***Good-Evening
10. #startswith() function check a string is present at the beginning of string or not
e.g.-> z = "Python is a high level language"
print(z.startswith("Python")) -> (output) True
11. #endswith() function check a string is present at the end of string or not
e.g.-> print(z.endswith("uage")) -> (output) True
12. join() function creates a new string by concatenating the elements
e.g.-> z = ['All','is','well']
k = " ".join(z)
print(k) -> (output) All is well
e.g.-> w = "Hello" w2 = "world"
k = " " .join([w,w2])
print (k) -> (output) Hello world

8|Page
▪ Dictionary
Note:- Dictionary is an mutable seqeunce. Each element of dictionary is called item. Item contains a
key-value pair.
Example:
d = {'name':'Aman','class':10,'roll':25}
->name,class,roll are keys
->Aman,10,25 are values
• Declare a dictionary:-
1. D = {}
2. D = Dict()
Note:- We have remember that a dictionary’s ‘ key ‘ cannot be of mutable datatype.
• Adding elements of a dictionary:-
D = {}
D['Fruit']='Apple'
D['Flower']='Tulip'
D['Vegetable']='Potato'
print(D) -> (output) {'Fruit': 'Apple', 'Flower': 'Tulip', 'Vegetable': 'Potato'}

• Creating a list containing key-value pairs:-


z = dict([['Player','Cristiano Ronaldo'],["Ballon D'or",5],['Golden Boot',6]])
print(z) -> (output) {'Player': 'Cristiano Ronaldo', "Ballon D'or": 5, 'Golden Boot': 6}
• Creating a list using zip():-
syntax: variable = dict(zip((key1,key2...),(value1,value2..)))
z = dict(zip(('Player',"Ballon D'or",'Golden Boots'),('CR7',5,6)))
print(z) -> (output) {'Player': 'CR7', "Ballon D'or": 5, 'Golden Boots': 6}
• Creating list using key-value arguments to the dict() function:-
1. Syntax: variable = dict(Key1=Value1,Key2=Values,....)
z = dict(Player="CR7",Cars=25)
print(z) -> (output) {'Player': 'CR7', 'Cars': 25}
2. syntax: variable = dict({key1:value1,key2:value2,....})
z=dict({'Player':'CR7','Cars':25})
print(z) -> (output) {'Player': 'CR7', 'Cars': 25}
• Limitations of keys in a dictionary:-
1. A key should not be duplicated within the dictionary
2. A key can never be mutable data type. As it will returns, TypeError: unhashable type
Note:- A dictionary is also called Mappings or Hashes
• Accessing elements using a key:-
d = {"TV":"Sony","AC":"Godrej","Fan":"Havells"}
print(d['TV']) -> (output) Sony
print(d['Fan']) -> (output) Havells
• Renaming a key in dictionary:-
1. Using key names
d = {'Mango':80,'Banana':50,'Apple':60}
print("Originally:",d) -> (output) Orignally: {'Mango': 80, 'Banana': 50, 'Apple': 60}
d['Orange']=d['Banana'] #adds a new key with the value of previous key
print("Adding ",d) ->(output) {'Mango': 80, 'Banana': 50, 'Apple': 60, 'Orange': 50}
del d['Banana'] #then we are removing old key

9|Page
print("After removing: ",d)-> (output) {'Mango': 80, 'Apple': 60, 'Orange': 50}

2. Using pop() function


d = {'Mango':80,'Banana':50,'Apple':60}
print("Originally:",d)-> (output) Orignally: {'Mango': 80, 'Banana': 50, 'Apple': 60}
d['Orange']=d.pop('Banana')-> (output) New: {'Mango': 80, 'Apple': 60, 'Orange': 50}
print("New:",d)
Note:- The new value pair will always be added at the end of the dictionary , using pop().
• Use of membership operators in dictionary:-
d = {"Animal":"Cow","Tree":"Neem","Flower":"Lily"}
print("Flower" in d)->(output)True #since the key is present it will return True
print("Food" in d)->(output) False #since the key is absent it will return False
print("Flower" not in d)->(output) False #since the key is present it will return False
print("Food" not in d)->(output)True #since the key is absent it will return True
• make a duplicate copy of a dictionary using copy() fucntion:-
1. marks = {"Eng":90,"Maths":95,"Sci":90,"Comp":100,"SST":80}
new = marks.copy()
print("Original:",marks)->(output) Original: {'Eng': 90, 'Maths': 95, 'Sci': 90, 'Comp': 100, 'SST': 80}
print("newdict:",new)->(output) newdict: {'Eng': 90, 'Maths': 95, 'Sci': 90, 'Comp': 100, 'SST': 80}
2. marks = {"Eng":90,"Maths":95,"Sci:":90,"Comp":100,"SST":80}
new=dict(marks)
print("Original:",marks)->(output) Original: {'Eng': 90, 'Maths': 95, 'Sci': 90, 'Comp': 100, 'SST': 80}
print("newdict:",new)->(output) newdict: {'Eng': 90, 'Maths': 95, 'Sci': 90, 'Comp': 100, 'SST': 80}

• Dictionary functions:-
1. keys() functions displays all the keys present in the dictionary
e.g.-> marks = {"Eng":90,"Maths":95,"Sci:":90,"Comp":100,"SST":80}
print(marks.keys())->(output) dict_keys(['Eng', 'Maths', 'Sci:', 'Comp', 'SST'])
2. values() functions displays all the values present in the dictionary
e.g.-> marks = {"Eng":90,"Maths":95,"Sci:":90,"Comp":100,"SST":80}
print(marks.values())->(output) dict_values([90, 95, 90, 100, 80])
3. items() functions displays two tuples : first one containing the keys and second one
contains the values
e.g.-> marks = {"Eng":90,"Maths":95,"Sci:":90,"Comp":100,"SST":80}
print(marks.items())
(output)dict_items([('Eng', 90), ('Maths', 95), ('Sci:', 90), ('Comp', 100), ('SST',
80)])
4. fromkeys() creates a new dictionary from a given sequence,where the given sequence
becomes the keys
e.g.-> sub = ['Physics','Chem','Math','Bio','Comp']
d = dict.fromkeys(sub) #the values will be none
print(d)
(output){'Physics': None, 'Chem': None, 'Math': None, 'Bio': None, 'Comp':
None}
#we will provide a value,all the keys will have the same value
sub = ['Physics','Chem','Math','Bio','Comp']
d = dict.fromkeys(sub,100) #the values will be same
print(d)
(output) {'Physics': 100, 'Chem': 100, 'Math': 100, 'Bio': 100, 'Comp': 100}
5. get() will take a key and it will return the value

10 | P a g e
e.g.-> marks = {"Eng":90,"Maths":95,"Sci:":90,"Comp":100,"SST":80}
print(marks['Eng']) ->(output) 90
print(marks.get('Eng')) ->(output) 90
print(marks.get('Bengali')) ->(output) None
#since the key is absent it returns None
print(marks.get("Hindi","Key not found")) ->(output) Key not found
#since the Hindi key is absent so it returns the adjacent value

6. setdefault() it works similar to get() only difference is that if the key is not present then it
adds to the dictionary
e.g.-> marks = {"Eng":90,"Maths":95,"Sci:":90,"Comp":100,"SST":80}
print(marks.setdefault("Maths")) ->(output) 95
print(marks.setdefault("Bengali",99)) ->(output) 99
print(marks)
(output) {'Eng': 90, 'Maths': 95, 'Sci:': 90, 'Comp': 100, 'SST': 80, 'Bengali': 99}
7. update() it compares two dictionary and updates the common key values also it add the
new key value
e.g.-> marks = {"Eng":90,"Maths":95,"Sci:":90,"Comp":100,"SST":80}
marks2={"Eng":85,"Bengali":100}
marks.update(marks2)
print("After update:",marks)
(output) {'Eng': 85, 'Maths': 95, 'Sci:': 90, 'Comp': 100, 'SST': 80, 'Bengali': 100}
8. #popitem() it does not take any parameters it just removes the last item and display it as
tuple
e.g.-> marks = {"Eng":90,"Maths":95,"Sci:":90,"Comp":100,"SST":80}
p = marks.popitem()
print(p) ->(output) ('SST', 80)
print(marks) ->(output) {'Eng': 90, 'Maths': 95, 'Sci:': 90, 'Comp': 100}
#If the dictionary is empty and you try to use popitem() it will display
KeyError
9. max with get
e.g.-> marks = {"Eng":90,"Maths":95,"Sci:":90,"Comp":100,"SST":80}
m = max(marks,key=marks.get)
print("Maximum marks subject:",m)
10. max with value
e.g.-> n = max(marks.values())->(output) Maximum marks subject: Comp
print("Maximum value is:",n)->(output) Maximum value is: 100
11. min with get
e.g.-> marks = {"Eng":90,"Maths":95,"Sci:":90,"Comp":100,"SST":80}
m = min(marks,key=marks.get)
print("Minimum marks subject:",m)->(output) Minimum marks subject: SST
12. max with value
e.g.-> n = min(marks.values())
print("Minimum value is:",n)->(output) Minimum value is: 80
13. count() displays the frequency of an element from values
e.g.-> marks = {"Eng":90,"Maths":95,"Sci:":90,"Comp":100,"SST":80}
m = marks.values()
print("Number of 90's are ",list(m).count(90))->(output)Number of 90's are 2
14. sorted()
a) sorting the keys of the dictionary(ascending/descending)

11 | P a g e
e.g.-> marks = {"Eng":90,"Maths":95,"Sci":90,"Comp":100,"SST":80}
print(" ascending alphabets",sorted(marks.keys()))
(output) ['Comp', 'Eng', 'Maths', 'SST', 'Sci']
print("descending",sorted(marks.keys(),reverse=True))
(output) ['Sci', 'SST', 'Maths', 'Eng', 'Comp']
b) sorting the values of the dictionary(ascending/descending)
e.g.-> marks = {"Eng":90,"Maths":95,"Sci":90,"Comp":100,"SST":80}
print("ascending ",sorted(marks.values()))
(output) [80, 90, 90, 95, 100]
print("descending ",sorted(marks.values(),reverse=True))
(output) [100, 95, 90, 90, 80]
15. Nested Dictionary
e.g.-> d = {'name':'Aarish','subject':{'Physics':87,'Chemistry':80},'Hobby':'Matal'}
print(d)
(output) {'name': 'Aarish', 'subject': {'Physics': 87, 'Chemistry': 80}, 'Hobby':
'Matal'}
print(d['subject'])->(output) {'Physics': 87, 'Chemistry': 80}
print(d['subject']['Chemistry'])->(output) 80

12 | P a g e
▪ Functions
• Advantages of functions:-
1. Code reusablity & modularity
2. Complex tasks are broken down into multiple subtasks
• Types of functions:-
1. Built in functions
Built in functions - are the functions which are already defined and programmed into the
programming language. Example: input() ,print(), help(), min(), max(), bin(), sum(), len() etc.
2. Functions in a module
Functions in a module - are basically folders containing python files which can be included or
imported into another python program,so that the program which is already written inside
the modules, can be used instantly. example: json, math, mysql.connector etc

We can also download modules using the pip command in cmd/terminal. pip install
module_name Example: pip install pandas
e.g.-> import math #here math is the module
d = math.sqrt(25)
print("Square root:",d) -> (output)5.0

Note: - dir() will display the list of all the functions present in a library
import math
print(dir(math)
(output) -> ['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh',
'asin', 'asinh', 'atan', 'atan2', 'atanh', 'cbrt', 'ceil', 'comb', 'copysign', 'cos', 'cosh', 'degrees',
'dist', 'e', 'erf', 'erfc', 'exp', 'exp2', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum',
'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'isqrt', 'lcm', 'ldexp', 'lgamma',
'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'nextafter', 'perm', 'pi', 'pow', 'prod', 'radians',
'remainder', 'sin', 'sinh', 'sqrt', 'sumprod', 'tan', 'tanh', 'tau', 'trunc', 'ulp']

3. User defined functions


a) We write the function starting the keyword def (means define)
b) Function name must be an identifier
c) Then we have the paramater followed by : semicolon
d) The first line of the function is called the function header

• default arguments:-
The first rule of default arguments is that, if you assign values to parameter in the
function header, makes sure that all the parameters are assigned some value, or
keeping the first parameter empty, assign the default values, but you must not assign
the first, parameter a value while keeping the, rest of the parameters empty,it will show
an error
e.g.-> def Calculate(a=1,b,c):
print(a+b+c)
Calculate(2,3)
(output)SyntaxError: parameter without a default follows parameter with a default

13 | P a g e
Note:- when variable name are same, even if we redeclare the variables inside a function
with new value its changed value stays active within the function body and the value is not
affected which is declared outside the function.
now if we wanted to change the variable data declared outside the function, we will have to
use the global keyword.
e.g.-> a=5
def sum(b):
global a
c=a+b
print(c)
print(a)-> (output)5
sum(5)-> (output)10
• Nested function:-
That function called inside another function wap to accept a number.

e.g.-> def prime(n):


c=0
for i in range(1,n+1):
if n%i==0:
c=c+1
return True if c==2 else False
def primenumbers(n):
l=0
if prime(n):
l.append(n)

else:
print("Not a prime number")

14 | P a g e

You might also like