0% found this document useful (0 votes)
101 views47 pages

PythonNotes Original

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
101 views47 pages

PythonNotes Original

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 47

PYTHON NOTES 1

S.NO TOPIC

1. Definition
Python is a very popular general-purpose interpreted, interactive, object-oriented, and high-level
programming language. Python is dynamically-typed and garbage-collected programming language.
It was created by Guido van Rossum during 1985- 1990. Like Perl, Python source code is also
available under the GNU General Public License (GPL).

 Python is Open Source which means it’s available free of cost.


 Python is simple and so easy to learn
 Python is versatile and can be used to create many different things.
 Python has powerful development libraries include AI, ML etc.
 Python is much in demand and ensures high salary
 Python is Interpreted − Python is processed at runtime by the interpreter. You do not
need to compile your program before executing it. This is similar to PERL and PHP.
 Python is Interactive − You can actually sit at a Python prompt and interact with the
interpreter directly to write your programs.
 Python is Object-Oriented − Python supports Object-Oriented style or technique of
programming that encapsulates code within objects.
 Python is a Beginner's Language − Python is a great language for the beginner-level
programmers and supports the development of a wide range of applications from simple
text processing to WWW browsers to games.

2. Characteristics of Python
Following are important characteristics of Python Programming −

 It supports functional and structured programming methods as well as OOP.


 It can be used as a scripting language or can be compiled to byte-code for building large
applications.
 It provides very high-level dynamic data types and supports dynamic type checking.
 It supports automatic garbage collection.
 It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.

3. Applications of Python

 Easy-to-learn − Python has few keywords, simple structure, and a clearly defined syntax.
This allows the student to pick up the language quickly.
 Easy-to-read − Python code is more clearly defined and visible to the eyes.
 Easy-to-maintain − Python's source code is fairly easy-to-maintain.
 A broad standard library − Python's bulk of the library is very portable and cross-
platform compatible on UNIX, Windows, and Macintosh.
 Interactive Mode − Python has support for an interactive mode which allows interactive
testing and debugging of snippets of code.
 Portable − Python can run on a wide variety of hardware platforms and has the same
interface on all platforms.
 Extendable − You can add low-level modules to the Python interpreter. These modules
enable programmers to add to or customize their tools to be more efficient.
 Databases − Python provides interfaces to all major commercial databases.
 GUI Programming − Python supports GUI applications that can be created and ported to
many system calls, libraries and windows systems, such as Windows MFC, Macintosh,
and the X Window system of Unix.
PYTHON NOTES 2

 Scalable − Python provides a better structure and support for large programs than shell
scripting.

4. Python can be executed in two ways


 Interactive Mode
 Script Mode

Interactive Mode
$ python
Python 3.6.8 (default, Sep 10 2021, 09:13:53)
[GCC 8.5.0 20210514 (Red Hat 8.5.0-3)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>> print ("Hello, World!")
Hello, World!

Script Mode
Create a file demo.py and type the program and execute by hitting F5 key.

5. Rules for declaring Variables


o The first character of the variable must be an alphabet or underscore ( _ ).
PYTHON NOTES 3

o All the characters except the first character may be an alphabet of lower-case(a-z),
upper-case (A-Z), underscore, or digit (0-9).
o Identifier name must not contain any white-space, or special character (!, @, #, %, ^, &,
*).
o Identifier name must not be similar to any keyword defined in the language.
o Identifier names are case sensitive; for example, my name, and MyName is not the same.
o Examples of valid identifiers: a123, _n, n_9, etc.
o Examples of invalid identifiers: 1a, n%4, n 9, etc.
6. Variable assigning methods
1. x=y=z=50
2. print(x)
3. print(y)
4. print(z)

o/p : 50 50 50

1. a,b,c=5,10,15
2. print a
3. print b
4. print c

o/p: 5 10 15

7. Local Variable

1. # Declaring a function
2. def add():
3. # Defining local variables. They has scope only within a function
4. a = 20
5. b = 30
6. c=a+b
7. print("The sum is:", c)
8.
9. # Calling a function
10. add()

o/p : The sum is: 50


8. Global Variable
1. # Declare a variable and initialize it
2. x = 101
3.
PYTHON NOTES 4

4. # Global variable in function


5. def mainFunction():
6. # printing a global variable
7. global x
8. print(x)
9. # modifying a global variable
10. x = 'Welcome To Javatpoint'
11. print(x)
12.
13. mainFunction()
14. print(x)

o/p
101
Welcome to Javatpoint
9. Python String data type

str = 'Hello World!'

print (str) # Prints complete string


print (str[0]) # Prints first character of the string
print (str[2:5]) # Prints characters starting from 3rd to 5th
print (str[2:]) # Prints string starting from 3rd character
print (str * 2) # Prints string two times
print (str + "TEST") # Prints concatenated string

o/p
Hello World!
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST

10. Python List Datatype

Python Lists are the most versatile compound data types. A Python list contains items separated by
commas and enclosed within square brackets ([]). To some extent, Python lists are similar to arrays
in C. One difference between them is that all the items belonging to a Python list can be of different
data type where as C array can store elements related to a particular data type.

list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]


tinylist = [123, 'john']

print (list) # Prints complete list


print (list[0]) # Prints first element of the list
print (list[1:3]) # Prints elements starting from 2nd till 3rd
print (list[2:]) # Prints elements starting from 3rd element
print (tinylist * 2) # Prints list two times
PYTHON NOTES 5

print (list + tinylist) # Prints concatenated lists

['abcd', 786, 2.23, 'john', 70.2]


abcd
[786, 2.23]
[2.23, 'john', 70.2]
[123, 'john', 123, 'john']
['abcd', 786, 2.23, 'john', 70.2, 123, 'john']

o The lists are ordered.


o The element of the list can access by index.
o The lists are the mutable type.
o The lists are mutable types.
o A list can store the number of various elements.

11. Python Tuple data type

Python tuple is another sequence data type that is similar to a list. A Python tuple consists of
a number of values separated by commas. Unlike lists, however, tuples are enclosed within
parentheses.
The main differences between lists and tuples are: Lists are enclosed in brackets ( [ ] ) and
their elements and size can be changed, while tuples are enclosed in parentheses ( ( ) ) and
cannot be updated. Tuples can be thought of as read-only lists
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
tinytuple = (123, 'john')

print (tuple) # Prints the complete tuple


print (tuple[0]) # Prints first element of the tuple
print (tuple[1:3]) # Prints elements of t
he tuple starting from 2nd till 3rd
print (tuple[2:]) # Prints elements of the tuple starting from 3rd element
print (tinytuple * 2) # Prints the contents of the tuple twice
print (tuple + tinytuple) # Prints concatenated tuples

('abcd', 786, 2.23, 'john', 70.2)


abcd
(786, 2.23)
(2.23, 'john', 70.2)
(123, 'john', 123, 'john')
('abcd', 786, 2.23, 'john', 70.2, 123, 'john')

12. Python Ranges

Python range() is an in-built function in Python which returns a sequence of numbers starting
from 0 and increments to 1 until it reaches a specified number.
We use range() function with for and while loop to generate a sequence of numbers
Syntax:
range (start,stop,step)
PYTHON NOTES 6

example

for i in range(5):
print(i)

o/p : 0 1 2 3 4

example

for i in range(1, 5, 2):


print(i)

o/p : 1 3

13. Python Dictionary

dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"

tinydict = {'name': 'john','code':6734, 'dept': 'sales'}

print (dict['one']) # Prints value for 'one' key


print (dict[2]) # Prints value for 2 key
print (tinydict) # Prints complete dictionary
print (tinydict.keys()) # Prints all the keys
print (tinydict.values()) # Prints all the values

o/p

This is one
This is two
{'dept': 'sales', 'code': 6734, 'name': 'john'}
['dept', 'code', 'name']
['sales', 6734, 'john']

14. Python boolean type is one of built-in data types which represents one of the two values
either True or False. Python bool() function allows you to evaluate the value of any expression and
returns either True or False based on the expression

a = True
# display the value of a
print(a)

# display the data type of a


print(type(a))

o/p:
true
<class 'bool'>

15. Python Data type conversion


PYTHON NOTES 7

1. Conversion to int

a = int(1) # a will be 1
b = int(2.2) # b will be 2
c = int("3") # c will be 3

print (a)
print (b)
print (c)

o/p : 1 2 3

2. Conversion to float

a = float(1) # a will be 1.0


b = float(2.2) # b will be 2.2
c = float("3.3") # c will be 3.3

print (a)
print (b)
print (c)

o/p: 1.0
2.2
3.3

3. Conversion to string

a = str(1) # a will be "1"


b = str(2.2) # b will be "2.2"
c = str("3.3") # c will be "3.3"

print (a)
print (b)
print (c)

o/p: 1
2.2
3.3

16. Python Arithmetic Operators

Operator Name Example

+ Addition 10 + 20 = 30

- Subtraction 20 – 10 = 10

* Multiplication 10 * 20 = 200

/ Division 20 / 10 = 2
PYTHON NOTES 8

% Modulus 22 % 10 = 2

** Exponent 4**2 = 16

// Floor Division 9//2 = 4


17. Python Comparison Operators

Operator Name Example

== Equal 4 == 5 is not true.

!= Not Equal 4 != 5 is true.

> Greater Than 4 > 5 is not true.

< Less Than 4 < 5 is true.

>= Greater than or Equal to 4 >= 5 is not true.

<= Less than or Equal to 4 <= 5 is true.


18. Python Assignment Operators

Operator Name Example

= Assignment Operator a = 10

+= Addition Assignment a += 5 (Same as a = a + 5)

-= Subtraction Assignment a -= 5 (Same as a = a - 5)

*= Multiplication Assignment a *= 5 (Same as a = a * 5)

/= Division Assignment a /= 5 (Same as a = a / 5)

%= Remainder Assignment a %= 5 (Same as a = a % 5)

**= Exponent Assignment a **= 2 (Same as a = a ** 2)

//= Floor Division Assignment a //= 3 (Same as a = a // 3)


19. Python Bitwise Operator

Operator Name Example

& Binary Sets each bit to 1 if both bits are 1


AND

| Binary Sets each bit to 1 if one of two bits is 1


OR
PYTHON NOTES 9

^ Binary Sets each bit to 1 if only one of two bits is 1


XOR

~ Binary Inverts all the bits


Ones
Comple
ment

<< Binary Shift left by pushing zeros in from the right and
Left let the leftmost bits fall off
Shift

>> Binary Shift right by pushing copies of the leftmost bit in from the left,
Right and let the rightmost bits fall off
Shift
20. Python Logical Operators

Operator Description Example

and Logical AND If both the operands are true then condition (a and b) is true.
becomes true.

or Logical OR If any of the two operands are non-zero then (a or b) is true.


condition becomes true.

not Logical NOT Used to reverse the logical state of its operand. Not(a and b) is false.
21. Python Membership Operators

Operator Description Example

in Evaluates to true if it finds a


variable in the specified x in y, here in results in a 1 if x is a member
sequence and false of sequence y.
otherwise.

not in Evaluates to true if it does x not in y, here not in results in a 1 if x is not a


not finds a variable in the member of sequence y.
specified sequence and false
otherwise.
22. Python Control Structures

Statement Description

If Statement The if statement is used to test a specific condition.


If the condition is true, a block of code (if-block) will be executed.
PYTHON NOTES 10

If - else Statement The if-else statement is similar to if statement except the fact
that, it also provides the block of the code for the false case of
the condition to be checked. If the condition provided in the
if statement is false, then the else statement will be executed.

Nested if Statement Nested if statements enable us to use if? else statement inside
an outer if statement.
23. If statement
1. num = int(input("enter the number?"))
2. if num%2 == 0:
3. print("Number is even")

24. If statement (example 2)


1. a = int(input("Enter a? "));
2. b = int(input("Enter b? "));
3. c = int(input("Enter c? "));
4. if a>b and a>c:
5. print("a is largest");
6. if b>a and b>c:
7. print("b is largest");
8. if c>a and c>b:
9. print("c is largest");

25. If…else….statement
age = int (input("Enter your age? "))
if age>=18:
print("You are eligible to vote !!");
else:
print("Sorry! you have to wait !!");
and-----------------------
num = int(input("enter the number?"))
if num%2 == 0:
print("Number is even...")
else:
print("Number is odd...")

26. elif … statement (multiple if…else…statement…)


PYTHON NOTES 11

The elif statement enables us to check multiple conditions and execute the specific block of
statements depending upon the true condition among them. We can have any number of elif
statements in our program depending upon our need. However, using elif is optional.

1. marks = int(input("Enter the marks? "))


2. if marks > 85 and marks <= 100:
3. print("Congrats ! you scored grade A ...")
4. elif marks > 60 and marks <= 85:
5. print("You scored grade B + ...")
6. elif marks > 40 and marks <= 60:
7. print("You scored grade B ...")
8. elif (marks > 30 and marks <= 40):
9. print("You scored grade C ...")
10. else:
11. print("Sorry you are fail ?")

27. Python Loops

Sr.No. Name of the Loop Type & Description


loop

1 While loop Repeats a statement or group of statements


while a given condition is TRUE. It tests the condition before
executing the loop body.

2 For loop This type of loop executes a code block multiple


times and abbreviates the code that manages the loop variable.

3 Nested loops We can iterate a loop inside another loop.


28.
Sr.No. Name of the Description
control statement

1 Break statement This command terminates the loop's execution and


transfers the program's control to the statement next
to the loop.

2 Continue statement This command skips the current iteration of the loop.
The statements following the continue statement are
not executed once the Python interpreter reaches the
continue statement.
PYTHON NOTES 12

3 Pass statement The pass statement is used when a statement is syntactically neces
be executed.
29. The for loop statement
1. # Python program to show how the for loop works
2. # Creating a sequence which is a tuple of numbers
3. numbers = [4, 2, 6, 7, 3, 5, 8, 10, 6, 1, 9, 2]
4. # variable to store the square of the number
5. square = 0
6. # Creating an empty list
7. squares = []
8. # Creating a for loop
9. for value in numbers:
square = value ** 2
squares.append(square)
10. print("The list of squares is", squares)

o/p
The list of squares is: [16, 4, 36, 49, 9, 25, 64, 100, 36, 1, 81, 4]
1. # Python program to show how to use else statement with for loop
2.
3. # Creating a sequence
4. tuple_ = (3, 4, 6, 8, 9, 2, 3, 8, 9, 7)
5.
6. # Initiating the loop
7. for value in tuple_:
8. if value % 2 != 0:
9. print(value)
10. # giving an else statement
11. else:
12. print("These are the odd numbers present in the tuple")

39397
These are the odd numbers present in the tuple

30. Range Function


1. # Python program to show the working of range() function
2.
PYTHON NOTES 13

3. print(range(15))
4. print(list(range(15)))
5. print(list(range(4, 9)))
6. print(list(range(5, 25, 4)))

o/p
range (0.15)
[0, 1,2,3,4,5,6,7,8,9,10,11,12,13,14]
[4,5,6,7,8]
[5,9,13,17,21]

31. 1. # Python program to iterate over a sequence with the help of indexing

2.
3. tuple_ = ("Python", "Loops", "Sequence", "Condition", "Range")
4.
5. # iterating over tuple_ using range() function
6. for iterator in range(len(tuple_)):
7. print(tuple_[iterator].upper())

o/p

PYTHON
LOOPS
SEQUENCE
CONDITION
RANGE

32. While Loop

1. # Python program to show how to use a while loop


2. counter = 0
3. # Initiating the loop
4. while counter < 10: # giving the condition
5. counter = counter + 3
6. print("Python Loops")

o/p
Python Loops
Python Loops
Python Loops
Python Loops

33. For Loop in Python


PYTHON NOTES 14

1. # Code to find the sum of squares of each element of the list using for loop
2. # creating the list of numbers
3. numbers = [3, 5, 23, 6, 5, 1, 2, 9, 8]
4. # initializing a variable that will store the sum
5. sum_ = 0
6. # using for loop to iterate over the list
7. for num in numbers:
8. sum_ = sum_ + num ** 2
9. print("The sum of squares is: ", sum_)
o/p
The sum of squares is: 774

34. The Range Function


1. my_list = [3, 5, 6, 8, 4]
2. for iter_var in range( len( my_list ) ):
3. my_list.append(my_list[iter_var] + 2)
4. print( my_list )

o/p
[3,5,6,8,4,5,7,8,10,6]

35. Break statement

1. str = "python"
2. for i in str:
3. if i == 'o':
4. break
5. print(i);

o/p
p
y
t
h

36. Python Strings


var1 = 'Hello World!'
var2 = "Python Programming"

print "var1[0]: ", var1[0]


print "var2[1:5]: ", var2[1:5]

o/p
PYTHON NOTES 15

var1[0]: H
var2[1:5]: ytho

37. Updating Strings

var1 = 'Hello World!'


print "Updated String :- ", var1[:6] + 'Python'

Updated String :- Hello Python

38. String Special operators

39. Python Lists


The list is a most versatile datatype available in Python which can be written as a list of comma-
separated values (items) between square brackets. Important thing about a list is that items in a list
need not be of the same type.

list1 = ['Maths', 'ComputerScience', 1997, 2000];


list2 = [1, 2, 3, 4, 5 ];
PYTHON NOTES 16

list3 = ["a", "b", "c", "d"]

Accessing List values


list1 = ['physics', 'chemistry', 1997, 2000];
list2 = [1, 2, 3, 4, 5, 6, 7 ];
print "list1[0]: ", list1[0]
print "list2[1:5]: ", list2[1:5]

o/p
list1[0]: physics
list2[1:5]: [2, 3, 4, 5]

Updating Lists
list = ['physics', 'chemistry', 1997, 2000];
print "Value available at index 2 : "
print list[2]
list[2] = 2001;
print "New value available at index 2 : "
print list[2]

O/p
Value available at index 2 :
1997
New value available at index 2 :
2001

List Indexing and Splitting

Basic List Operations


PYTHON NOTES 17

Built-in List Functions

Len()
1. # size of the list
2. # declaring the list
3. list1 = [12, 16, 18, 20, 39, 40]
4. # finding length of the list
5. len(list1)

o/p
6

Max()
1. # maximum of the list
2. list1 = [103, 675, 321, 782, 200]
3. # large element in the list
4. print(max(list1))

o/p
782

Min()
1. # minimum of the list
2. list1 = [103, 675, 321, 782, 200]
3. # smallest element in the list
4. print(min(list1))

o/p
103

40. Tuples

A tuple is a collection of objects which ordered and immutable. Tuples are sequences, just like lists.
The differences between tuples and lists are, the tuples cannot be changed unlike lists and tuples use
parentheses, whereas lists use square brackets.
PYTHON NOTES 18

tup1 = ('physics', 'chemistry', 1997, 2000);


tup2 = (1, 2, 3, 4, 5 );
tup3 = "a", "b", "c", "d";

Accessing values in Tuples


tup1 = ('physics', 'chemistry', 1997, 2000);
tup2 = (1, 2, 3, 4, 5, 6, 7 );
print "tup1[0]: ", tup1[0];
print "tup2[1:5]: ", tup2[1:5];

o/p
tup1[0]: physics
tup2[1:5]: [2, 3, 4, 5]

Updating Tuples

tup1 = (12, 34.56);


tup2 = ('abc', 'xyz');

tup3 = tup1 + tup2;


print tup3;

o/p
(12, 34.56, 'abc', 'xyz')

Deleting Tuples elements


tup = ('physics', 'chemistry', 1997, 2000);
print tup;
del tup;
print "After deleting tup : ";
print tup;

o/p
('physics', 'chemistry', 1997, 2000)
After deleting tup :
Traceback (most recent call last):
File "test.py", line 9, in <module>
print tup;
NameError: name 'tup' is not defined

Basic Tuple Operations


PYTHON NOTES 19

Accessing Tuple Elements


a. Indexing
# Python program to show how to access tuple elements
# Creating a tuple
tuple_ = ("Python", "Tuple", "Ordered", "Collection")
print(tuple_[0])
print(tuple_[1])
# trying to access element index more than the length of a tuple
try:
print(tuple_[5])
except Exception as e:
print(e)
# trying to access elements through the index of floating data type
try:
print(tuple_[1.0])
except Exception as e:
print(e)
# Creating a nested tuple
nested_tuple = ("Tuple", [4, 6, 2, 6], (6, 2, 6, 7))

# Accessing the index of a nested tuple


print(nested_tuple[0][3])
print(nested_tuple[1][1])

O/P

b. Slicing
# Python program to show how slicing works in Python tuples
# Creating a tuple
tuple_ = ("Python", "Tuple", "Ordered", "Immutable", "Collection", "Objects")
# Using slicing to access elements of the tuple
print("Elements between indices 1 and 3: ", tuple_[1:3])
# Using negative indexing in slicing
PYTHON NOTES 20

print("Elements between indices 0 and -4: ", tuple_[:-4])


# Printing the entire tuple by using the default start and end values.
print("Entire tuple: ", tuple_[:])

O/P
Elements between indices 1 and 3: ('Tuple', 'Ordered')
Elements between indices 0 and -4: ('Python', 'Tuple')
Entire tuple: ('Python', 'Tuple', 'Ordered', 'Immutable',
'Collection', 'Objects')

c. Repetition
# Python program to show repetition in tuples
tuple_ = ('Python',"Tuples")
print("Original tuple is: ", tuple_)
# Repeting the tuple elements
tuple_ = tuple_ * 3
print("New tuple is: ", tuple_)

O/p
Original tuple is: ('Python', 'Tuples')
New tuple is: ('Python', 'Tuples', 'Python', 'Tuples', 'Python',
'Tuples')

Tuple Methods
a. Count()
b. Index()

Tuple Membership Test


1. # Python program to show how to perform membership test for tuples
2. # Creating a tuple
3. tuple_ = ("Python", "Tuple", "Ordered", "Immutable", "Collection", "Ordered")
4. # In operator
5. print('Tuple' in tuple_)
6. print('Items' in tuple_)
7. # Not in operator
8. print('Immutable' not in tuple_)
9. print('Items' not in tuple_)
o/p
True
False
False
True
PYTHON NOTES 21

41. Sets in Python

A Python set is the collection of the unordered items. Each element in the set must be unique,
immutable, and the sets remove the duplicate elements. Sets are mutable which means we can
modify it after its creation.

1. Days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"}


2. print(Days)
3. print(type(Days))
4. print("looping through the set elements ... ")
5. for i in Days:
6. print(i)

O/P
{'Friday', 'Tuesday', 'Monday', 'Saturday', 'Thursday', 'Sunday',
'Wednesday'}
<class 'set'>
looping through the set elements ...
Friday
Tuesday
Monday
Saturday
Thursday
Sunday
Wednesday

Adding items to the Set


1. Months = set(["January","February", "March", "April", "May", "June"])
2. print("\nprinting the original set ... ")
3. print(months)
4. print("\nAdding other months to the set...");
5. Months.add("July");
6. Months.add ("August");
7. print("\nPrinting the modified set...");
8. print(Months)
9. print("\nlooping through the set elements ... ")
10. for i in Months:
11. print(i)

printing the original set ...


{'February', 'May', 'April', 'March', 'June', 'January'}

Adding other months to the set...


PYTHON NOTES 22

Printing the modified set...


{'February', 'July', 'May', 'April', 'March', 'August', 'June',
'January'}

looping through the set elements ...


February
July
May
April
March
August
June
January

Removing Elements from the Set

1. months = set(["January","February", "March", "April", "May", "June"])


2. print("\nprinting the original set ... ")
3. print(months)
4. print("\nRemoving some months from the set...");
5. months.remove("January");
6. months.remove("May");
7. print("\nPrinting the modified set...");
8. print(months)

O/p
printing the original set ...
{'February', 'June', 'April', 'May', 'January', 'March'}

Removing some months from the set...

Printing the modified set...


{'February', 'June', 'April', 'March'}

42. Python Dictionary


Each key is separated from its value by a colon (:), the items are separated by commas, and
the whole thing is enclosed in curly braces. An empty dictionary without any items is written
with just two curly braces, like this: {}.
Keys are unique within a dictionary while values may not be. The values of a dictionary can be
of any type, but the keys must be of an immutable data type such as strings, numbers, or
tuples.
Creating and Accessing a Dictionary
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
print "dict['Name']: ", dict['Name']
print "dict['Age']: ", dict['Age']
PYTHON NOTES 23

O/p
dict['Name']: Zara
dict['Age']: 7

Updating a Dictionary
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
dict['Age'] = 8; # update existing entry
dict['School'] = "DPS School"; # Add new entry

print "dict['Age']: ", dict['Age']


print "dict['School']: ", dict['School']

O/p
dict['Age']: 8
dict['School']: DPS School

Delete Dictionary Elements

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}


del dict['Name']; # remove entry with key 'Name'
dict.clear(); # remove all entries in dict
del dict ; # delete entire dictionary

Accessing a Dictionary Values

1. Employee = {"Name": "David", "Age": 30, "salary":55000,"Company":"GOOGLE"}


2. print(type(Employee))
3. print("printing Employee data .... ")
4. print("Name : %s" %Employee["Name"])
5. print("Age : %d" %Employee["Age"])
6. print("Salary : %d" %Employee["salary"])
7. print("Company : %s" %Employee["Company"])

O/p
<class 'dict'>
printing Employee data ....
Name : David
Age : 30
Salary : 55000
Company : GOOGLE

Adding Dictionary Values

1. # Creating an empty Dictionary


2. Dict = {}
PYTHON NOTES 24

3. print("Empty Dictionary: ")


4. print(Dict)
5. # Adding elements to dictionary one at a time
6. Dict[0] = 'Peter'
7. Dict[2] = 'Joseph'
8. Dict[3] = 'Ricky'
9. print("\nDictionary after adding 3 elements: ")
10. print(Dict)
11. # Adding set of values
12. # with a single Key
13. # The Emp_ages doesn't exist to dictionary
14. Dict['Emp_ages'] = 20, 33, 24
15. print("\nDictionary after adding 3 elements: ")
16. print(Dict)
17. # Updating existing Key's Value
18. Dict[3] = 'JavaTpoint'
19. print("\nUpdated key value: ")
20. print(Dict)

O/p
Empty Dictionary:
{}

Dictionary after adding 3 elements:


{0: 'Peter', 2: 'Joseph', 3: 'Ricky'}

Dictionary after adding 3 elements:


{0: 'Peter', 2: 'Joseph', 3: 'Ricky', 'Emp_ages': (20, 33, 24)}

Updated key value:


{0: 'Peter', 2: 'Joseph', 3: 'JavaTpoint', 'Emp_ages': (20, 33, 24)}

Example2

1. Employee = {"Name": "David", "Age": 30, "salary":55000,"Company":"GOOGLE"}


2. print(type(Employee))
3. print("printing Employee data .... ")
4. print(Employee)
5. print("Enter the details of the new employee....");
6. Employee["Name"] = input("Name: ");
7. Employee["Age"] = int(input("Age: "));
PYTHON NOTES 25

8. Employee["salary"] = int(input("Salary: "));


9. Employee["Company"] = input("Company:");
10. print("printing the new data");
11. print(Employee)

O/p
<class 'dict'>
printing Employee data ....
{'Name': 'David', 'Age': 30, 'salary': 55000, 'Company': 'GOOGLE'}
Enter the details of the new employee....
Name: Rahul
Age: 28
Salary: 36000
Company: Microsoft
printing the new data
{'Name': 'Rahul', 'Age': 28, 'salary': 36000, 'Company': 'Microsoft'}

Deleting elements using Del keyword

1. Employee = {"Name": "David", "Age": 30, "salary":55000,"Company":"GOOGLE"}


2. print(type(Employee))
3. print("printing Employee data .... ")
4. print(Employee)
5. print("Deleting some of the employee data")
6. del Employee["Name"]
7. del Employee["Company"]
8. print("printing the modified information ")
9. print(Employee)
10. print("Deleting the dictionary: Employee");
11. del Employee
12. print("Lets try to print it again ");
13. print(Employee)

O/P
<class 'dict'>
printing Employee data ....
{'Name': 'David', 'Age': 30, 'salary': 55000, 'Company': 'GOOGLE'}
Deleting some of the employee data
printing the modified information
{'Age': 30, 'salary': 55000}
Deleting the dictionary: Employee
Lets try to print it again
NameError: name 'Employee' is not defined
PYTHON NOTES 26

Deleting using POP() method


1. # Creating a Dictionary
2. Dict = {1: 'JavaTpoint', 2: 'Learning', 3: 'Website'}
3. # Deleting a key
4. # using pop() method
5. pop_key = Dict.pop(2)
6. print(Dict)

O/P
{1: 'JavaTpoint', 3: 'Website'}

Iterating Dictionary
Example1
1. # for loop to print all the keys of a dictionary
2. Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}
3. for x in Employee:
4. print(x)

O/P
Name
Age
salary
Company

Example2
1. #for loop to print all the values of the dictionary
2. Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"} for x in Emplo
yee:
3. print(Employee[x])

O/P
John
29
25000
GOOGLE

43. Built-In Dictionary Functions

1. 1. dict = {1: "Ayan", 2: "Bunny", 3: "Ram", 4: "Bheem"}


2. len(dict)
O/P
4
PYTHON NOTES 27

1. 2. dict = {1: "Ayan", 2: "Bunny", 3: "Ram", 4: "Bheem"}


2. any({'':'','':'','3':''})
O/P
True

1. 3. dict = {1: "Ayan", 2: "Bunny", 3: "Ram", 4: "Bheem"}


2. all({1:'',2:'','':''})

O/P
False
1. 4. dict = {7: "Ayan", 5: "Bunny", 8: "Ram", 1: "Bheem"}
2. sorted(dict)

O/P
[1,5,7,8]

1. 5. dict = {1: "Microsoft", 2: "Google", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}


2. # clear() method
3. dict.clear()
4. print(dict)

o/p
{}

1. 6. # dictionary methods
2. dict = {1: "Microsoft", 2: "Google", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
3. # copy() method
4. dict_demo = dict.copy()
5. print(dict_demo)

O/p
{1: 'Microsoft', 2: 'Google', 3: 'Facebook', 4: 'Amazon', 5: {1:
'Microsoft', 2: 'Google', 3: 'Facebook', 4: 'Amazon', 5: 'Flipkart'}

1. 7. dict = {1: "Microsoft", 2: "Google", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}


2. # pop() method
3. dict_demo = dict.copy()
4. x = dict_demo.pop(1)
5. print(x)
PYTHON NOTES 28

O/p
{2: 'Google', 3: 'Facebook', 4: 'Amazon', 5: 'Flipkart'}

1. 8. dict = {1: "Microsoft", 2: "Google", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}


2. # keys() method
3. print(dict_demo.keys())

O/p
dict_keys([1, 2, 3, 4, 5])

1. 9. dict = {1: "Microsoft", 2: "Google", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}


2. # items() method
3. print(dict_demo.items())

o/p
dict_items([(1, 'Microsoft'), (2, 'Google'), (3, 'Facebook'), (4,
'Amazon'), (5, 'Flipkart')])

1. 10. dict = {1: "Microsoft", 2: "Google", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}


2. # get() method
3. print(dict_demo.get(3))

44. Python Functions

A function is a collection of related assertions that performs a mathematical, analytical,


or evaluative operation. A collection of statements called Python Functions returns the
particular task. Python functions are simple to define and essential to intermediate-level
programming. The exact criteria hold to function names as they do to variable names. The goal
is to group up certain often performed actions and define a function. We may call the function
and reuse the code contained within it with different variables rather than repeatedly creating
the same code block for different input variables.

User-defined and built-in functions are the two main categories of functions in Python.
It helps maintain the programme concise, unique, and well-structured.

o By including functions, we can prevent repeating the same code block repeatedly in a program.
o Python functions, once defined, can be called many times and from anywhere in a program.
o If our Python program is large, it can be separated into numerous functions which is simple to
track.
PYTHON NOTES 29

o The key accomplishment of Python functions is we can return as many outputs as we want with
different arguments.

Syntax:
1. # An example Python Function
2. def function_name( parameters ):
3. # code block
Rules

o The beginning of a function header is indicated by a keyword called def.


o function_name is the function's name that we can use to separate it from others. We will use
this name to call the function later in the program. In Python, name functions must follow the
same rules as naming variables.
o We pass arguments to the defined function using parameters. However, they are optional.
o The function header is terminated by a colon (:).
o We can use a documentation string called docstring in the short form to explain the purpose of
the function.
o The body of the function is made up of several valid Python statements. The indentation depth
of the whole code block must be the same (usually 4 spaces).
o We can use a return expression to return a value from a defined function.

Example

1. # Example Python Code for User-Defined function


2. def square( num ):
3. """
4. This function computes the square of the number.
5. """
6. return num**2
7. object_ = square(6)
8. print( "The square of the given number is: ", object_ )

Output:

The square of the given number is: 36


---------------------------------------------------------
Calling a Function

1. # Example Python Code for calling a function


PYTHON NOTES 30

2. # Defining a function
3. def a_function( string ):
4. "This prints the value of length of string"
5. return len(string)
6.
7. # Calling the function we defined
8. print( "Length of the string Functions is: ", a_function( "Functions" ) )
9. print( "Length of the string Python is: ", a_function( "Python" ) )

Output:

Length of the string Functions is: 9


Length of the string Python is: 6
45. Pass by Reference
1. # Example Python Code for Pass by Reference vs. Value
2. # defining the function
3. def square( item_list ):
4. '''''''This function will find the square of items in the list'''
5. squares = [ ]
6. for l in item_list:
7. squares.append( l**2 )
8. return squares
9.
10. # calling the defined function
11. my_list = [17, 52, 8];
12. my_result = square( my_list )
13. print( "Squares of the list are: ", my_result )

Output
Squares of the list are: [289, 2704, 64]

46. Function Arguments


Default Arguments
1. # Python code to demonstrate the use of default arguments
2. # defining a function
3. def function( n1, n2 = 20 ):
4. print("number 1 is: ", n1)
5. print("number 2 is: ", n2)
PYTHON NOTES 31

6. # Calling the function and passing only one argument


7. print( "Passing only one argument" )
8. function(30)
9.
# Now giving two arguments to the function
print( "Passing two arguments" )
function(50,30)

Output:

Passing only one argument


number 1 is: 30
number 2 is: 20
Passing two arguments
number 1 is: 50
number 2 is: 30

47. Keyword Arguments


A function called's arguments are linked to keyword arguments. When invoking a function with
keyword arguments, the user may tell whose parameter value it is by looking at the parameter label.

1. # Python code to demonstrate the use of keyword arguments


2. # Defining a function
3. def function( n1, n2 ):
4. print("number 1 is: ", n1)
5. print("number 2 is: ", n2)
6.
7. # Calling function and passing arguments without using keyword
8. print( "Without using keyword" )
9. function( 50, 30)
10.
11. # Calling function and passing arguments using keyword
12. print( "With using keyword" )
13. function( n2 = 50, n1 = 30)

Output:
Without using keyword
number 1 is: 50
number 2 is: 30
PYTHON NOTES 32

With using keyword


number 1 is: 30
number 2 is: 50

48. Required Arguments


The arguments given to a function while calling in a pre-defined positional sequence are required
arguments. The count of required arguments in the method call must be equal to the count of
arguments provided while defining the function.
1. # Python code to demonstrate the use of default arguments
2. # Defining a function
3. def function( n1, n2 ):
4. print("number 1 is: ", n1)
5. print("number 2 is: ", n2)
6.
7. # Calling function and passing two arguments out of order, we need num1 to be 20 and num
2 to be 30
8. print( "Passing out of order arguments" )
9. function( 30, 20 )
10.
11. # Calling function and passing only one argument
12. print( "Passing only one argument" )
13. try:
14. function( 30 )
15. except:
16. print( "Function needs two positional arguments" )

Output:

Passing out of order arguments


number 1 is: 30
number 2 is: 20
Passing only one argument
Function needs two positional arguments

49. Variable – Length Arguments

We can use special characters in Python functions to pass as many arguments as we want in a
function. There are two types of characters that we can use for this purpose:

1. *args -These are Non-Keyword Arguments


PYTHON NOTES 33

2. **kwargs -These are Keyword Arguments.

# Python code to demonstrate the use of variable-length arguments


# Defining a function
def function( *args_list ):
ans = []
for l in args_list:
ans.append( l.upper() )
return ans
# Passing args arguments
object = function('Python', 'Functions', 'tutorial')
print( object )

# defining a function
def function( **kargs_list ):
ans = []
for key, value in kargs_list.items():
ans.append([key, value])
return ans
# Paasing kwargs arguments
object = function(First = "Python", Second = "Functions", Third = "Tutorial")
print(object)

Output:

['PYTHON', 'FUNCTIONS', 'TUTORIAL']


[['First', 'Python'], ['Second', 'Functions'], ['Third', 'Tutorial']]

50. Return Function


We write a return statement in a function to leave a function and give the calculated value when a
defined function is called.
return < expression to be returned as output >

1. # Python code to demonstrate the use of return statements


2. # Defining a function with return statement
3. def square( num ):
4. return num**2
5. # Calling function and passing arguments.
6. print( "With return statement" )
PYTHON NOTES 34

7. print( square( 52 ) )
8. # Defining a function without return statement
9. def square( num ):
10. num**2
11. # Calling function and passing arguments.
12. print( "Without return statement" )
13. print( square( 52 ) )

51. Lambda Functions


Lambda expressions can accept an unlimited number of arguments; however, they only return one
value as the result of the function. They can't have numerous expressions or instructions in them.
Since lambda needs an expression, an anonymous function cannot be directly called to print.
1. lambda [argument1 [,argument2... .argumentn]] : expression
2. # Python code to demonstrate ananymous functions
3. # Defining a function
4. lambda_ = lambda argument1, argument2: argument1 + argument2;
5.
6. # Calling the function and passing values
7. print( "Value of the function is : ", lambda_( 20, 30 ) )
8. print( "Value of the function is : ", lambda_( 40, 50 ) )

Output:

Value of the function is : 50


Value of the function is : 90

52. Python Built-In Functions


Abs()
1. # integer number
2. integer = -20
3. print('Absolute value of -40 is:', abs(integer))
4.
5. # floating number
6. floating = -20.83
7. print('Absolute value of -40.83 is:', abs(floating))
8.
Absolute value of -20 is: 20
Absolute value of -20.83 is: 20.83
9.
Bin()
PYTHON NOTES 35

1. x = 10
2. y = bin(x)
3. print (y)

0b1010

Bytes()
1. string = "Hello World."
2. array = bytes(string, 'utf-8')
3. print(array)

b ' Hello World.'

Compile()
1. # compile string source to code
2. code_str = 'x=5\ny=10\nprint("sum =",x+y)'
3. code = compile(code_str, 'sum.py', 'exec')
4. print(type(code))
5. exec(code)
6. exec(x)

<class 'code'>
sum = 15

exec()
1. x = 8
2. exec('print(x==8)')
3. exec('print(x+4)')

True
12

Sum()
1. s = sum([1, 2,4 ])
2. print(s)
3.
4. s = sum([1, 2, 4], 10)
5. print(s)

7
17

Bytearray()
PYTHON NOTES 36

1. string = "Python is a programming language."


2.
3. # string with encoding 'utf-8'
4. arr = bytearray(string, 'utf-8')
5. print(arr)

bytearray(b'Python is a programming language.')

eval()
1. x = 8
2. print(eval('x + 1'))

Float()
1. # for integers
2. print(float(9))
3. # for floats
4. print(float(8.19))

9.0
8.19

Format()
1. # d, f and b are a type
2. # integer
3. print(format(123, "d"))
4. # float arguments
5. print(format(123.4567898, "f"))
6. # binary format
7. print(format(12, "b"))

123
123.456790
1100

Getattr()
1. class Details:
2. age = 22
3. name = "Phill"
4. details = Details()
PYTHON NOTES 37

5. print('The age is:', getattr(details, "age"))


6. print('The age is:', details.age)

The age is: 22


The age is: 22

Globals()
1. age = 22
2. globals()['age'] = 22
3. print('The age is:', age)

The age is: 22

Open()
1. # opens python.text file of the current directory
2. f = open("python.txt")
3. # specifying full path
4. f = open("C:/Python33/README.txt")

delattr()
1. class Student:
2. id = 101
3. name = "Pranshu"
4. email = "pranshu@abc.com"
5. # Declaring function
6. def getinfo(self):
7. print(self.id, self.name, self.email)
8. s = Student()
9. s.getinfo()
delattr(Student,'course') # Removing attribute which is not available
s.getinfo() # error: throws an error

101 Pranshu pranshu@abc.com


AttributeError: course

Divmod()
1. # Python divmod() function example
2. # Calling function
3. result = divmod(10,2)
4. # Displaying result
5. print(result)
PYTHON NOTES 38

(5, 0)

Enumerate function()
1. # Calling function
2. result = enumerate([1,2,3])
3. # Displaying result
4. print(result)
5. print(list(result))

<enumerate object at 0x7ff641093d80>


[(0, 1), (1, 2), (2, 3)]

Filter()
1. # Python filter() function example
2. def filterdata(x):
3. if x>5:
4. return x
5. # Calling function
6. result = filter(filterdata,(1,2,6))
7. # Displaying result
8. print(list(result))

[6]

53. Packing with * Operator and Unpacking

Packing - As its name suggests, it wraps all the arguments into a single variable, and this
function call gets into a tuple called args. We can use any other name in place of args.

o Example: def func( *args )

Unpacking - Unpacking is the term which refers to an operation list or tuple assigned to a
single variable.

o Example - (a, b, c) = List/tuple

Packing
The * operator is the tuple (or iterables) unpacking operator. It allows packing multiple values into a
single variable. We pack a tuple of values into a single variable using the * operators in the following
example.
1. a, b, *c= 1, 2, 'x', 'y', 'z'
PYTHON NOTES 39

2. print(a)
3. print(b)
4. print(c)

1
2
['x', 'y', 'z']

Example2
1. *a, b, c = 1, 2, 3
2. print(a)
3. print(b)
4. print(c)

[1]
2
3

unpacking
1. (a, b, c, d, e, f) = (1, 2, 3, 4, 5, 6)
2. print(a)
3. print(b)
4. print(c)
5. print(d)
6. print(e)
7. print(f)

54. Python Zip() Function

The zip() function returns a zip object, which is an iterator of tuples where the first
item in each passed iterator is paired together, and then the second item in each
passed iterator are paired together etc.

If the passed iterators have different lengths, the iterator with the least items
decides the length of the new iterator.

a = ("John", "Charles", "Mike")


b = ("Jenny", "Christy", "Monica")

x = zip(a, b)

#use the tuple() function to display a readable version of the result:


PYTHON NOTES 40

print(tuple(x))

(('John', 'Jenny'), ('Charles', 'Christy'), ('Mike', 'Monica'))

55. Frozenset() Function


Python frozenset() Method creates an immutable Set object from an iterable. It is a built-in Python function.
As it is a set object therefore we cannot have duplicate values in the frozenset.

Frozenset method on list

l = ["Geeks", "for", "Geeks"]

# converting list to frozenset


fnum = frozenset(l)

# printing empty frozenset object


print("frozenset Object is : ", fnum)

Output
frozenset Object is : frozenset({'Geeks', 'for'})

56. List Permutation


Permutation is an arrangement of objects in a specific order. Order of arrangement of object is very
important. The number of permutations on a set of n elements is given by n!. For example, there are 2! = 2*1
= 2 permutations of {1, 2}, namely {1, 2} and {2, 1}, and 3! = 3*2*1 = 6 permutations of {1, 2, 3}, namely {1, 2,
3}, {1, 3, 2}, {2, 1, 3}, {2, 3, 1}, {3, 1, 2} and {3, 2, 1}.

def permutation(lst):

# If lst is empty then there are no permutations


if len(lst) == 0:
return []

# If there is only one element in lst then, only


# one permutation is possible
if len(lst) == 1:
return [lst]

# Find the permutations for lst if there are


# more than 1 characters

l = [] # empty list that will store current permutation

# Iterate the input(lst) and calculate the permutation


for i in range(len(lst)):
m = lst[i]

# Extract lst[i] or m from the list. remLst is


# remaining list
remLst = lst[:i] + lst[i+1:]

# Generating all permutations where m is first


# element
for p in permutation(remLst):
PYTHON NOTES 41

l.append([m] + p)
return l

# Driver program to test above function


data = list('123')
for p in permutation(data):

Output:
['1', '2', '3']
['1', '3', '2']
['2', '1', '3']
['2', '3', '1']
['3', '1', '2']
['3', '2', '1']

57. Exception Handling in Python


Exceptions: Exceptions are raised when the program is syntactically correct, but
the code resulted in an error. This error does not stop the execution of the
program, however, it changes the normal flow of the program.

# initialize the amount variable


marks = 10000

# perform division with 0


a = marks / 0
print(a)

58. Try and Except Examples


Try and except statements are used to catch and handle exceptions in Python.
Statements that can raise exceptions are kept inside the try clause and the
statements that handle the exception are written inside except clause.
Example: Let us try to access the array element whose index is out of bound and
handle the corresponding exception.
# Python program to handle simple runtime error
#Python 3

a = [1, 2, 3]
try:
print ("Second element = %d" %(a[1]))

# Throws error since there are only 3 elements in array


PYTHON NOTES 42

print ("Fourth element = %d" %(a[3]))

except:
print ("An error occurred")

Example2
# Program to handle multiple errors with one
# except statement
# Python 3

def fun(a):
if a < 4:

# throws ZeroDivisionError for a = 3


b = a/(a-3)

# throws NameError if a >= 4


print("Value of b = ", b)

try:
fun(3)
fun(5)

# note that braces () are necessary here for


# multiple exceptions
except ZeroDivisionError:
print("ZeroDivisionError Occurred and Handled")
except NameError:
print("NameError Occurred and Handled")

O/p
ZeroDivisionError Occurred and Handled

59. Python String Functions


Python String capitalize()
Converts first character to Capital Letter
Python String casefold()
converts to case folded strings
Python String center()
Pads string with specified character
Python String count()
returns occurrences of substring in string
Python String encode()
returns encoded string of given string
Python String endswith()
Checks if String Ends with the Specified Suffix
Python String expandtabs()
Replaces Tab character With Spaces
PYTHON NOTES 43

Python String find()


Returns the index of first occurrence of substring
Python String format()
formats string into nicer output
Python String format_map()
Formats the String Using Dictionary
Python String index()
Returns Index of Substring
Python String isalnum()
Checks Alphanumeric Character
Python String isalpha()
Checks if All Characters are Alphabets
Python String isdecimal()
Checks Decimal Characters
Python String isdigit()
Checks Digit Characters
Python String isidentifier()
Checks for Valid Identifier
Python String islower()
Checks if all Alphabets in a String are Lowercase
Python String isnumeric()
Checks Numeric Characters
Python String isprintable()
Checks Printable Character
Python String isspace()
Checks Whitespace Characters
Python String istitle()
Checks for Titlecased String
Python String isupper()
returns if all characters are uppercase characters
Python String join()
Returns a Concatenated String
Python String ljust()
returns left-justified string of given width
Python String lower()
returns lowercased string
Python String lstrip()
Removes Leading Characters
PYTHON NOTES 44

Python String maketrans()


returns a translation table
Python String partition()
Returns a Tuple
Python String replace()
Replaces Substring Inside
Python String rfind()
Returns the Highest Index of Substring
Python String rindex()
Returns Highest Index of Substring
Python String rjust()
returns right-justified string of given width
Python String rpartition()
Returns a Tuple
Python String rsplit()
Splits String From Right
Python String rstrip()
Removes Trailing Characters
Python String split()
Splits String from Left
Python String splitlines()
Splits String at Line Boundaries
Python String startswith()
Checks if String Starts with the Specified String
Python String strip()
Removes Both Leading and Trailing Characters
Python String swapcase()
swap uppercase characters to lowercase; vice versa
Python String title()
Returns a Title Cased String
Python String translate()
returns mapped charactered string
Python String upper()
returns uppercased string
Python String zfill()
Returns a Copy of The String Padded With Zeros

60. Command Line Arguments


PYTHON NOTES 45

The arguments that are given after the name of the program in the command line shell of
the operating system are known as Command Line Arguments. Python provides various
ways of dealing with these types of arguments. The three most common are:
 Using sys.argv
 Using getopt module
 Using argparse module
The sys module provides functions and variables used to manipulate different parts
of the Python runtime environment. This module provides access to some variables
used or maintained by the interpreter and to functions that interact strongly with the
interpreter.
One such variable is sys.argv which is a simple list structure. It’s main purpose are:
 It is a list of command line arguments.
 len(sys.argv) provides the number of command line arguments.
 sys.argv[0] is the name of the current Python script.

Example: Let’s suppose there is a Python script for adding two numbers and the
numbers are passed as command-line arguments.

# Python program to demonstrate


# command line arguments

import sys

# total arguments
n = len(sys.argv)
print("Total arguments passed:", n)

# Arguments passed
print("\nName of Python script:", sys.argv[0])

print("\nArguments passed:", end = " ")


for i in range(1, n):
print(sys.argv[i], end = " ")

# Addition of numbers
Sum = 0
# Using argparse module
for i in range(1, n):
Sum += int(sys.argv[i])

print("\n\nResult:", Sum)
PYTHON NOTES 46

61. List Sorting


cars = ['Ford', 'BMW', 'Volvo']

cars.sort(reverse=True)

print(cars)

o/p
['Volvo', 'Ford', 'BMW']

62. Map in Python


Python Maps also called ChainMap is a type of data structure to manage multiple dictionaries together
as one unit. The combined dictionary contains the key and value pairs in a specific sequence
eliminating any duplicate keys. The best use of ChainMap is to search through multiple dictionaries at
a time and get the proper key-value pair mapping. We also see that these ChainMaps behave as stack
data structure.

import collections

dict1 = {'day1': 'Mon', 'day2': 'Tue'}


dict2 = {'day3': 'Wed', 'day1': 'Thu'}

res = collections.ChainMap(dict1, dict2)

# Creating a single dictionary


print(res.maps,'\n')

print('Keys = {}'.format(list(res.keys())))
print('Values = {}'.format(list(res.values())))
print()

# Print all the elements from the result


print('elements:')
for key, val in res.items():
print('{} = {}'.format(key, val))
print()

# Find a specific value in the result


print('day3 in res: {}'.format(('day1' in res)))
PYTHON NOTES 47

print('day4 in res: {}'.format(('day4' in res)))


Output
When the above code is executed, it produces the following result −
[{'day1': 'Mon', 'day2': 'Tue'}, {'day1': 'Thu', 'day3': 'Wed'}]

Keys = ['day1', 'day3', 'day2']


Values = ['Mon', 'Wed', 'Tue']

elements:
day1 = Mon
day3 = Wed
day2 = Tue

day3 in res: True


day4 in res: False

63. Searching using Python


def linear_search(values, search_for):
search_at = 0
search_res = False
# Match the value with each data element
while search_at < len(values) and search_res is False:
if values[search_at] == search_for:
search_res = True
else:
search_at = search_at + 1
return search_res
l = [64, 34, 25, 12, 22, 11, 90]
print(linear_search(l, 12))
print(linear_search(l, 91))

Output

True
False

You might also like