0% found this document useful (0 votes)
2 views76 pages

Python Notes

Python is a high-level programming language created by Guido van Rossum in 1991, emphasizing code readability and simplicity. It is widely used for web development, data analysis, automation, and machine learning due to its ease of learning and versatility. The document covers Python's history, applications, basic programming concepts, data types, and how to run Python scripts.

Uploaded by

arpanchhetri008
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)
2 views76 pages

Python Notes

Python is a high-level programming language created by Guido van Rossum in 1991, emphasizing code readability and simplicity. It is widely used for web development, data analysis, automation, and machine learning due to its ease of learning and versatility. The document covers Python's history, applications, basic programming concepts, data types, and how to run Python scripts.

Uploaded by

arpanchhetri008
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/ 76

UNIT 1

INTRODUCTION

HISTORY OF PYTHON

Python is a widely-used general-purpose, high-level programming language. It was initially


designed by Guido van Rossum in 1991 and developed by Python Software Foundation. It was
mainly developed for emphasis on code readability, and its syntax allows programmers to
express concepts in fewer lines of code.

In the late 1980s, history was about to be written. It was that time when working on Python
started. Soon after that, Guido Van Rossum began doing its application-based work in December
of 1989 at Centrum Wiskunde & Informatica (CWI) which is situated in the Netherlands. It was
started firstly as a hobby project because he was looking for an interesting project to keep him
occupied during Christmas.

The programming language in which Python is said to have succeeded is ABC Programming
Language, which had interfacing with the Amoeba Operating System and had the feature of
exception handling. He had already helped to create ABC earlier in his career and he had seen
some issues with ABC but liked most of the features. After that what he did was really very
clever. He had taken the syntax of ABC, and some of its good features.

It came with a lot of complaints too, so he fixed those issues completely and had created a good
scripting language that had removed all the flaws. The inspiration for the name came from
BBC’s TV Show – ‘Monty Python’s Flying Circus’, as he was a big fan of the TV show and
also, he wanted a short, unique and slightly mysterious name for his invention and hence he
named it Python! He was the “Benevolent dictator for life” (BDFL) until he stepped down from
the position as the leader on 12th July 2018. For quite some time he used to work for Google, but
currently, he is working at Dropbox.

1
The language was finally released in 1991. When it was released, it used a lot fewer codes to
express the concepts, when we compare it with Java, C++ & C. Its design philosophy was quite
good too. Its main objective is to provide code readability and advanced developer productivity.
When it was released, it had more than enough capability to provide classes with inheritance,
several core data types exception handling and functions.

NEEDS OF PYTHON
Python is commonly used for developing websites and software, task automation, data analysis,
and data visualization. Since it’s relatively easy to learn, Python has been adopted by many non-
programmers such as accountants and scientists, for a variety of everyday tasks, like organizing
finances.

“Writing programs is a very creative and rewarding activity,” says University of Michigan and
Coursera instructor Charles R Severance in his book Python for Everybody.

“You can write programs for many reasons, ranging from making your living to solving a
difficult data analysis problem to having fun to helping someone else solve a problem.”

What can you do with python? Some things include:

 Data analysis and machine learning


 Web development
 Automation or scripting
 Software testing and prototyping
 Everyday tasks

Data analysis and machine learning

Python has become a staple in data science, allowing data analysts and other professionals
to use the language to conduct complex statistical calculations, create data visualizations,
build machine learning algorithms, manipulate and analyze data, and complete other data-
related tasks.

2
Python can build a wide range of different data visualizations, like line and bar graphs, pie
charts, histograms, and 3D plots. Python also has a number of libraries that enable coders
to write programs for data analysis and machine learning more quickly and efficiently, like
TensorFlow and Keras.

Web development

Python is often used to develop the back end of a website or application—the parts that a
user doesn’t see. Python’s role in web development can include sending data to and from
servers, processing data and communicating with databases, URL routing, and ensuring
security. Python offers several frameworks for web development. Commonly used ones
include Django and Flask. Some web development jobs that use Python include back end
engineers, full stack engineers, Python developers, software engineers, and DevOps
engineers.

Automation or scripting

If you find yourself performing a task repeatedly, you could work more efficiently by
automating it with Python. Writing code used to build these automated processes is called
scripting. In the coding world, automation can be used to check for errors across multiple
files, convert files, execute simple math, and remove duplicates in data.

Python can even be used by relative beginners to automate simple tasks on the
computer—such as renaming files, finding and downloading online content or sending
emails or texts at desired intervals.

Software testing and prototyping

In software development, Python can aid in tasks like build control, bug tracking, and testing.
With Python, software developers can automate testing for new products or features. Some
Python tools used for software testing include Green and Requestium.

3
APPLICATIONS BASICS OF PYTHON PROGRAMMING USING THE REPL (SHELL)

Python is an interpreter language. It means it executes the code line by line. Python provides a
Python Shell, which is used to execute a single Python command and display the result. It is also
known as REPL (Read, Evaluate, Print, Loop), where it reads the command, evaluates the
command, prints the result, and loop it back to read the command again.

To run the Python Shell, open the command prompt or power shell on Windows and terminal
window on mac, write python and press enter.

A Python Prompt comprising of three greater-than symbols >>> appears, as shown below.

Now, you can enter a single statement and get the result. For example, enter a simple expression
like 3 + 2, press enter and it will display the result in the next line, as shown below.

4
As you have seen above, Python Shell executes a single statement. To execute multiple
statements, create a Python file with extension .py, and write Python scripts (multiple
statements).For example, enter the following statement in a text editor such as Notepad.

Example: myPythonScript.py
print ("This is Python Script.")
print ("Welcome to Python Tutorial by TutorialsTeacher.com")

Save it as myPythonScript.py, navigate the command prompt to the folder where you have saved
this file and execute the python myPythonScript.py command, as shown below. It will display
the result.

Thus, you can execute Python expressions and commands using Python REPL to quickly execute
Python code.

5
RUNNING PYTHON SCRIPTS:

1. Using the python command


The most basic and easy way to run a Python script is by using the python command. You need
to open a command line and type the word python followed by the path to your script file like
this:

python first_script.py Hello World!

Then you hit the ENTER button from the keyboard, and that's it. You can see the phrase Hello
World! on the screen. Congrats! You just ran your first Python script. However, if you do not get
the output, you might want to check your system PATH and the place where you saved your file.
If it still doesn’t work, re-install Python in your system and try again.

2. Redirecting output
Windows and Unix-like systems have a process called stream redirection. You can redirect the
output of your stream to some other file format instead of the standard system output. It is useful
to save the output in a different file for later analysis.

An example of how you can do this:

python first_script.py > output.txt

What happens is your Python script is redirected to the output.txt file. If the file doesn’t exist, it is
systematically created. However, if it already exists, the contents are replaced.

3. Running modules with the -m option


A module is a file that contains the Python code. It allows you to arrange your Python code in
a logical manner. It defines functions, classes, and variables and can also include runnable
code.

6
If you want to run a Python module, there are a lot of command-line options which Python
offers according to the needs of the user. One of which is the command

python -m <module-name>.

It searches the module name in the sys.path and runs the content as

main :

python -m first_script
Hello World!

Note that the module-name is a module object and not any string.

VARIABLES

Python Variable is containers which store values. Python is not “statically typed”. We do not
need to declare variables before using them or declare their type. A variable is created the
moment we first assign a value to it. A Python variable is a name given to a memory location. It
is the basic unit of storage in a program.

Example of Python Variables:


Var = "MYPYTHONPROGRAM"
print(Var)

Rules for creating variables in Python

 A variable name must start with a letter or the underscore character.


 A variable name cannot start with a number.
 A variable name can only contain alpha-numeric characters and underscores (A- z, 0-9,
and _ ).

7
 Variable names are case-sensitive (name, Name and NAME are three different variables).
 The reserved words(keywords) cannot be used naming the variable.

Data types are the classification or categorization of data items. It represents the kind of
value that tells what operations can be performed on a particular data. Since everything is an
object in Python programming, data types are actually classes and variables are instance
(object) of these classes. Following are the standard or built-in data type of Python:
 Numeric
 Sequence Type
 Boolean
 Set
 Dictionary

ASSIGNMENT

Python has an assignment operator that helps to assign values or expressions to the left-
hand-side variable. The assignment operator is represented as the "=" symbol used in
assignment statements and assignment expressions. In the assignment operator, the right-
hand side value or operand is assigned to the left-hand operand.

Following are the examples of the assignment operators:


x=8 # here 8 is assigned to the x (left side operand)
y = 20 # here 8 is assigned to the x (left side operand)
c=a+b-5 # here the value of expression a + b - 5 is assigned to c

Types of Assignment Operators

 Simple assignment operator ( = )


 Add and equal operator ( += )
 Subtract and equal operator ( -= )
 Asterisk and equal operator ( *= )
 Divide and equal operator ( /= )

8
 Modulus and equal operator ( %= )
 Double divide and equal operator ( //= )
 Exponent assign operator ( **= )

KEYWORDS

Python keywords are special reserved words that have specific meanings and purposes and
can’t be used for anything but those specific purposes. These keywords are always
available—you’ll never have to import them into your code. Python keywords are different
from Python’s built-in functions and types. The built-in functions and types are also always
available, but they aren’t as restrictive as the keywords in their usage.

An example of something you can’t do with Python keywords is assign something to them.
If you try, then you’ll get a Syntax Error. You won’t get a Syntax Error if you try to assign
something to a built-in function or type, but it still isn’t a good idea. For a more in-depth
explanation of ways keywords can be misused, check out Invalid Syntax in Python:
Common Reasons for Syntax Error.

False await else import pass


None break except in raise
True class finally is return
and continue for lambda try
as def from nonlocal while
assert del global not with
async elif if or yield

9
INPUT-OUTPUT

1. Input using the input( ) function

A function is defined as a block of organized, reusable code used to perform a single, related
action. Python has many built-in functions; you can also create your own. Python has an
input function which lets you ask a user for some text input. You call this function to tell the
program to stop and wait for the user to key in the data. In Python 2, you have a built-in
function raw_input(), whereas in Python 3, you have input(). The program will resume once
the user presses the ENTER or RETURN key. Look at this example to get input from the
keyboard using Python 2 in the interactive mode. Your output is displayed in quotes once
you hit the ENTER key.

>>>raw_input()

I am learning at hackerearth (This is where you type in)

'I am learning at hackerearth' (The interpreter showing you how the input is captured.)

>>> input()

I am learning at hackerearth.
'I am learning at hackerearth.'

2. Output using the print() function

To output your data to the screen, use the print() function. You can write print(argument)
and this will print the argument in the next line when you press the ENTER key.

Definitions to remember: An argument is a value you pass to a function when calling it. A
value is a letter or a number. A variable is a name that refers to a value. It begins with a
letter. An assignment statement creates new variables and gives them values.

This syntax is valid in both Python 3.x and Python 2.x. For example, if your data is "Guido,"
you can put "Guido" inside the parentheses ( ) after print.

>>> print("Guido")
Guido

10
INDENTATION

Indentation in general means indenting words or spaces or lines in the document to follow
the styling rule for documentation, or it may be used to explain the distances that should be
used or the spaces that should be used while writing the documents or codes. In Python,
indentation is one of the most distinctive features, and it can be defined as it refers to the
same meaning as that of the general, which means that the compiler in Python cannot
execute without indentation; therefore, the code is written with some spaces or tabs into
many different blocks of code to indent it so that the interpreter can easily execute the
Python code.

Role of Indentation in Python with Examples

The identification of a block of code in Python is done using Indentation. In many different
programming languages like C, C++, Java, etc. use flower brackets or braces {} to define or
to identify a block of code in the program, whereas in Python, it is done using the spaces or
tabs, which is known as indentation and also it is generally known as 4 space rule in Pep8
documentation of rules for styling and designing the code for Python. Let us consider an
example of this.

n = 10
if n>5:
print "n is greater than 5"
else:
print "n is not greater than 5"

11
UNIT 2
TYPES, OPERATORS AND EXPRESSIONS

DATA TYPES

 Integers

Integers are numbers with no decimal parts, such as -5, -4, -3, 0, 5, 7 etc. To declare an
integer in Python, simply write variableName = initial value Example: userAge = 20,
mobileNumber = 12398724

 Float

Float refers to numbers that have decimal parts, such as 1.234, -0.023, 12.01. To declare a
float in Python, we write variableName = initialvalue Example: userHeight = 1.82,
userWeight = 67.2

 String

String refers to text. To declare a string, you can either use variableName = ‘initial value’
(single quotes) or variableName = “initial value” (double quotes)

Example:

userName = ‘Peter’, userSpouseName = “Janet”, userAge = ‘30’

In the last example, because we wrote userAge = ‘30’, userAge is a string. In contrast, if you
wrote userAge = 30 (without quotes), userAge is an integer.

We can combine multiple substrings by using the concatenate sign (+).

For instance, “Peter” + “Lee” is equivalent to the string “PeterLee”.

 Boolean data type in Python

Python boolean type is one of the built-in data types provided by Python, which represents
one of the two values i.e. True or False. Generally, it is used to represent the truth values of

12
the expressions. For example, 1==1 is True whereas 2<1 is False. The boolean value can be
of two types only i.e. either True or False. The output <class ‘bool’> indicates the variable is
a boolean data type.

Example:

boolean type a = True

type(a)

b = False type(b)

Output:

<class 'bool'>

<class 'bool'>

OPERATORS

Operators are used to perform operations on values and variables. These are the special
symbols that carry out arithmetic and logical computations. The value the operator operates
on is known as Operand.

 Arithmetic Operators

Arithmetic operators are used to perform mathematical operations like addition,


subtraction, multiplication and division.

There are 7 arithmetic operators in Python :

1. Addition

2. Subtraction

3. Multiplication

4. Division

5. Modulus

6. Exponentiation

7. Floor division

13
1. Addition Operator : + is the addition operator. It is used to add 2values.
Example
val1 =2
val2 = 3
# using the addition operator
res = val1 + val2
print(res)

Output : 5

2. Subtraction Operator : In Python, – is the subtraction operator. It is used to subtract


the second value from the first value.
Example :
val1 = 2
val2 = 3
# using the subtraction operator
res = val1 - val2
print(res)

Output : -1

3. Multiplication Operator : In Python, * is the multiplication operator. It is used to find


the product of 2 values.
Example :
val1 = 2
val2 = 3
# using the multiplication operator
res = val1 * val2
print(res)

Output : 6

14
4. Division Operator : In Python, / is the division operator. It is used to find the quotient
when first operand is divided by the second.

Example :

val1 = 3

val2 = 2

# using the division operator

res = val1 / val2

print(res)

Output : 1.5

5. Modulus Operator : In Python, % is the modulus operator. It is used to find the


remainder when first operand is divided by the second.

Example :

val1 = 3

val2 = 2

# using the modulus operator

res = val1 % val2

print(res)

Output : 1
6. Exponentiation Operator : In Python, ** is the exponentiation operator. It is used to
raise the first operand to power of second.
Example :
val1 = 2
val2 = 3
# using the exponentiation operator res = val1 ** val2
print(res)
Output : 8

15
7. Floor division : In Python, // is used to conduct the floor division. It is used to find the
floor of the quotient when first operand is divided by the second.
Example:
val1 = 3
val2 = 2
# using the floor division
res = val1 // val2
print(res)

Output: 1

 Relational Operator
Relational operators are used for comparing the values. It either returns True or False according
to the condition. These operators are also known as Comparison Operators.
1. Greater than: This operator returns True if the left operand is greater than the right
operand.
Syntax: x>y
Example:
a=9
b=5
# Output print(a > b)
Output: True

2. Less than: This operator returns True if the left operand is less than the right operand.

Syntax: x<y
Example:
a=9
b=5
# Output
print(a < b)
Output: False

16
3. Equal to: This operator returns True if both the operands are equal i.e. if both the left and
the right operand are equal to each other.

Syntax: x == y
Example:
a=9
b=5
# Output
print(a == b)
Output: False

4. Not equal to: This operator returns True if both the operands are not equal.

Syntax: x != y

Example:

a=9

b=5

# Output

print(a != b)

Output: True

5. Greater than or equal to: This operator returns True if the left operand is greater than or
equal to the right operand.

Syntax: x >= y

Example:

a=9

b=5

# Output

print(a >= b)

Output: True
17
6. Less than or equal to: This operator returns True if the left operand is less than or equal
to the right operand.

Syntax: x <= y
Example:
a=9
b=5
# Output
print(a <= b)
Output: False

 Assignment Operator

Assignment Operators are used to assigning values to variables.

1. Assign: This operator is used to assign the value of the right side of the expression to the
left side operand.

Syntax: x=y+z

Example

a=3

b=5

c=a+b

# Output

print(c)

Output: 8

2. Add and Assign: This operator is used to add the right side operand with the left side
operand and then assigning the result to the left operand.

Syntax: x += y

Example:

18
a=3

b=5

#a=a+b

a += b

print(a)

Output: 8

3. Subtract and Assign: This operator is used to subtract the right operand from the left
operand and then assigning the result to the left operand.
Syntax: x -= y

Example:
a=3

b=5

#a=a-b

a -= b

print(a)

Output: -2

4. Multiply and Assign: This operator is used to multiply the right operand with the left
operand and then assigning the result to the left operand.

Syntax: x *= y

Example:

a=3

b=5

#a=a*b

a *= b

print(a)

Output: 15

19
5. Divide and Assign: This operator is used to divide the left operand with the right
operand and then assigning the result to the left operand.

Syntax: x /= y

Example:

a=3

b=5

#a=a/b

a /= b

print(a)

Output: 0.6

6. Modulus and Assign: This operator is used to take the modulus using the left and the
right operands and then assigning the result to the left operand.

Syntax: x %= y

Example:

a=3

b=5

#a=a%b

a %= b

print(a)

Output: 3

7. Divide (floor) and Assign: This operator is used to divide the left operand with the right
operand and then assigning the result(floor) to the left operand.

Syntax: x //= y

20
Example:

a=3

b=5

# a = a // b

a //= b

print(a)

Output: 0

8. Exponent and Assign: This operator is used to calculate the exponent(raise power) value
using operands and then assigning the result to the left operand.

Syntax: x **= y

Example:

a=3

b=5

# a = a ** b

a **= b

print(a)

Output: 243

9. Bitwise AND and Assign: This operator is used to perform Bitwise AND on both
operands and then assigning the result to the left operand.

Syntax: x &= y

Example

a=3

b=5

#a=a&b

21
a &= b

print(a)

Output: 1

10. Bitwise OR and Assign: This operator is used to perform Bitwise OR on the operands
and then assigning result to the left operand.

Syntax: x |= y

Example:

a=3

b=5

#a=a|b

a |= b

print(a)

Output: 7

11. Bitwise XOR and Assign: This operator is used to perform Bitwise XOR on the
operands and then assigning result to the left operand.
Syntax: x ^= y
Example:

a=3

b=5

#a=a^b

a ^= b

# Output

print(a)

Output: 6

22
12. Bitwise Right Shift and Assign: This operator is used to perform Bitwise right shift on
the operands and then assigning result to the left operand.
Syntax: x >>= y
Example
a=3
b=5
# a = a >> b
a >>= b
print(a)
Output: 0

13. Bitwise Left Shift and Assign: This operator is used to perform Bitwise left shift on the
operands and then assigning result to the left operand.
Syntax: x <<= y
Example:
a=3
b=5
# a = a << b
a <<= b
print(a)
Output: 96

 Bitwise Operator

Bitwise operators are used to perform bitwise calculations on integers. The integers are first
converted into binary and then operations are performed on each bit or corresponding pair of
bits, hence the name bitwise operators. Theresult is then returned in decimal format.

Note: Python bitwise operators work only on integers.

1. Bitwise AND operator Returns 1 if both the bits are 1 else 0.

Example:

a = 10 = 1010 (Binary)

b = 4 = 0100 (Binary)

23
a&b= 1010

&

0100

= 0000

= 0 (Decimal)

2. Bitwise or operator Returns 1 if either of the bit is 1 else 0.

Example:

a = 10 = 1010 (Binary)

b = 4 = 0100 (Binary)

a&b= 1010
|
0100
= 1110
= 14 (Decimal)

3. Bitwise not operator: Returns one’s complement of the number.

Example:

a = 10 = 1010 (Binary)

In computers we ususally represent numbers using 32 bits, so binary representation of 10 is


(....0000 1010)[32 bits]

~a is basically 1's complement of a, i.e ~a should be ~10 = ~(....0000 1010) = (....1111 0101) =
intermediate-result. Since bitwise negation inverts the sign bit, we now have a negative number.
And we represent a negative number using 2's complement.

24
2's complement of intermediate-result is: intermediate-res =

0101 //…1111 0101

1010 //…1111 0101(1’s complement)

+1

= 1011

-11(Decimal)

4. Bitwise xor operator: Returns 1 if one of the bits is 1 and the other is 0 else returns
false.

Example:

a = 10 = 1010 (Binary)

b = 4 = 0100 (Binary)

a^b= 1010
^
0100
= 1110
= 14 (Decimal)

# Python program to show # bitwise operators

a = 10

b=4

# Print bitwise AND operation

print("a & b =", a & b)

# Print bitwise OR operation

print("a | b =", a | b)

# Print bitwise NOT operation

print("~a =", ~a)

25
# print bitwise XOR operation

print("a ^ b =", a ^ b)

Output:
a&b=0
a | b = 14
~a = -11
a ^ b = 14

 Shift Operators
These operators are used to shift the bits of a number left or right thereby multiplying or
dividing the number by two respectively. They can be used when we have to multiply or
divide a number by two.

1. Bitwise right shift: Shifts the bits of the number to the right and fills 0 on voids
left( fills 1 in the case of a negative number) as a result. Similar effect as of dividing
the number with some power of two.

Example:
Example 1:
a = 10 = 0000 1010 (Binary)
a >> 1 = 0000 0101 = 5
Example 2:
a = -10 = 1111 0110 (Binary)
a >> 1 = 1111 1011 = -5

2. Bitwise left shift: Shifts the bits of the number to the left and fills 0 on voids right as
a result. Similar effect as of multiplying the number with some power of two.

Example:
Example 1:
a = 5 = 0000 0101 (Binary)
a << 1 = 0000 1010 = 10

26
a << 2 = 0001 0100 = 20
Example 2:
b = -10 = 1111 0110 (Binary)
b << 1 = 1110 1100 = -20
b << 2 = 1101 1000 = -40

Example:
print("a >> 1 =", a >> 1)
print("b >> 1 =", b >> 1)
a=5
b = -10
# print bitwise left shift operator
print("a << 1 =", a << 1)
print("b << 1 =", b << 1)

Output:
a >> 1 = 5
b >> 1 = -5
a << 1 = 10
b << 1 = -20

 Membership Operators
Python offers two membership operators to check or validate the membership of a value.
It tests for membership in a sequence, such asstrings, lists, or tuples.

1. in operator: The ‘in’ operator is used to check if a character/ substring/ element


exists in a sequence or not. Evaluate to True if it finds the specified element in a
sequence otherwise False

Example:
# Python program to illustrate
# Finding common member in list # without using 'in' operator

27
# Define a function() that takes two lists
def overlapping(list1, list2):
c=0
d=0
for i in list1:
c += 1
for i in list2:
d += 1
for i in range(0, c):
for j in range(0, d):
if(list1[i] == list2[j]):
return 1
return 0

list1 = [1, 2, 3, 4, 5]
list2 = [6, 7, 8, 9]
if(overlapping(list1, list2)): print("overlapping")
else:
print("not overlapping")

Output : not overlapping

2. not in’ operator- Evaluates to true if it does not finds a variable in the specified
sequence and false otherwise.

Example:
x = 24
y = 20
list = [10, 20, 30, 40, 50]
if (x not in list):
print("x is NOT present in given list")

28
else:
print("x is present in given list")

if (y in list):
print("y is present in given list")
else:
print("y is NOT present in given list")

Output
x is NOT present in given list y is present in given list

 Identity operators
Identity operators are used to compare the objects if both the objects are actually of the same
data type and share the same memory location.
There are different identity operators such as
1. ‘is’ operator – Evaluates to True if the variables on either side of the operator point to
the same object and false otherwise
Example:
# Python program to illustrate the use # of 'is' identity operator
x=5
y=5
print(x is y)
id(x)
id(y)
Output: True

Here in the given example, both the variables x and y have value 5 assigned to it and both share
the same memory location, which is why return True.

29
2. ‘is not’ operator: Evaluates True if both variables are not the same object
Example:
x = ["Geeks", "for", "Geeks"]
y = ["Geeks", "for", "Geeks"]z = x
# Returns False because z is the same object as x
print(x is not z)
# Returns True because x is not the same object as y,
# even if they have the same content
print(x is not y)
# To demonstrate the difference between "is not" and "!=":
# This comparison returns False because x is equal to y
print(x != y)

Output:
False
True
False

EXPRESSIONS

An expression is a combination of operators and operands that is interpreted to produce some


other value. In any programming language, an expression is evaluated as per the precedence of
its operators. So that if there is more than one operator in an expression, their precedence decides
which operation will be performed first. We have many different types of expressions in Python.

 Constant Expression

Example:
# Constant Expressions
x = 15 + 1.3
print(x)
Output: 16.3

30
 Arithmetic Expressions

An arithmetic expression is a combination of numeric values, operators, and sometimes


parenthesis. The result of this type of expression is also a numeric value. The operators used in
these expressions are arithmetic operators like addition, subtraction, etc.

Operators Syntax Functioning

+ x+y Addition

– x–y Subtraction

* x*y Multiplication

/ x/y Division

// x // y Quotient

% x%y Remainder

** x ** y Exponentiation

Example
# Arithmetic Expressions
x = 40
y = 12
add = x + y
sub = x - y
pro = x * y
div = x / y
print(add)
print(sub)
print(pro)
print(div)

31
Output
52
28
480
3.3333333333333335

 Integral Expressions: These are the kind of expressions that produce only integer results
after all computations and type conversions.

Example:
# Integral Expressions
a = 13
b = 12.0
c = a + int(b)
print(c)
Output: 25

 Floating Expressions: These are the kind of expressions which produce floating point
numbers as result after all computations and type conversions.

Example:
# Floating Expressions
a = 13
b=5
c=a/b
print(c)
Output: 2.6

 Relational Expressions: In these types of expressions, arithmetic expressions are written


on both sides of relational operator (> , < , >= , <=). Those arithmetic expressions are
evaluated first, and then compared as per relational operator and produce a boolean
output in the end. These expressions are also called Boolean expressions.

32
Example:
#Relational Expression
a=21
b=13
c=40
d=37
p=(a+b)>=(c-d)
print(p)
Output: True

 Logical Expressions: These are kinds of expressions that result in either True or False. It
basically specifies one or more conditions. For example, (10 == 9) is a condition if 10 is
equal to 9. As we know it is not correct, so it will return False. Studying logical
expressions, we also come across some logical operators which can be seen in logical
expressions most often. Here are some logical operators in Python:

Operator Syntax Functioning

And P and Q It returns true if both P and Q are true otherwise returns false

Or P or Q It returns true if at least one of P and Q is true

Not not P It returns true if condition P is false

Example:
P=(10==9)
Q=(7>5)
R=P and Q
S=P or Q
T=not P

33
print(R)
print(S)
print(T)

Output:
False
True
True

 Bitwise Expressions: These are the kind of expressions in which computations are
performed at bit level.

Example:
# Bitwise Expressions
a = 12
x = a >> 2
y = a << 1
print(x, y)
Output: 3 24

 Combinational Expressions: We can also use different types of expressions in a single


expression, and that will be termed as combinational expressions.

Example:
# Combinational Expressions
a = 16
b = 12
c = a + (b >> 1)
print(c)
Output: 22

34
ORDER OF EVALUATION
All operators except the power (**) operator are evaluated from left to right and are listed in the
table from highest to lowest precedence. That is, operators listed first in the table are evaluated
before operators listed later. (Note that operators included together within subsections, such as x
* y, x / y, x // y, and x % y, have equal precedence.)

Operator Name
(...), [...], {...} Tuple, list, and dictionary creation
´...´ String conversion
s[i], s[i:j] Indexing and slicing
s.attr Attributes
f(...) Function calls
+x, -x, ~x Unary operators
x ** y Power (right associative)
x * y, x / y, x // y, x % y Multiplication, division, floor division, modulo
x + y, x - y Addition, subtraction
x << y, x >> y Bit-shifting
x&y Bitwise and
x^y Bitwise exclusive or
x|y Bitwise or
x < y, x <= y, x > y, x >= y, Comparison, identity, and sequence membership tests
x == y, x != y
x <> y
x is y, x is not y
x in s, x not in s
not x Logical negation
x and y Logical and
x or y Logical or
lambda args: expr Anonymous function

35
CONTROL FLOW

 if statement

If the simple code of block is to be performed if the condition holds true then if statement is
used. Here the condition mentioned holds true then the code of block runs otherwise not.
Syntax:
if condition:
# Statements to execute if
# condition is true
Example:
# if statement example
if 10 > 5:
print("10 greater than 5")
print("Program ended")
Output:
10 greater than 5
Program ended

Indentation(White space) is used to delimit the block of code

 if-elif Statement

The if-elif statement is shortcut of if..else chain. While using if-elif statement at the end else
block is added which is performed if none of the above if-elif statement is true.
Syntax:

if (condition):
statement
elif (condition):
statement
else:
statement

36
Example:
# if-elif statement example
letter = "A"
if letter == "B":
print("letter is B")
elif letter == "C":
print("letter is C")
elif letter == "A":
print("letter is A")
else:
print("letter isn't A, B or C")
Output: letter is A

 For Loop

Python For loop is used for sequential traversal i.e. it is used for iterating over an iterable like
String, Tuple, List, Set or Dictionary. In Python, there is no C style for loop, i.e., for (i=0; i<n;
i++). There is “for” loop which is similar to each loop in other languages. Let us learn how to
use for in loop for sequential traversals

Note: In Python, for loops only implements the collection-based iteration.

For Loops Syntax


for var in iterable: # statements

Here the iterable is a collection of objects like lists, tuples. The indented statements inside the for
loops are executed once for each item in an iterable. The variable var takes the value of the next
item of the iterable each time through the loop.

Some examples of For Loops in Python are listed below

37
Example 1:
# Iterating over a list
l = ["geeks", "for", "geeks"]
for i in l:
print(i)
Output: Geeks for geeks
Example 2: Using For Loops in Python Dictionary
# Iterating over dictionary
print("Dictionary Iteration")
d = dict()
d['xyz'] = 123
d['abc'] = 345
for i in d:
print("% s % d" % (i, d[i]))
Output:
Dictionary Iteration
xyz 123
abc 345
Example 3: Using For Loops in Python String
# Iterating over a String
print("String Iteration")
s = "Geeks"
for i in s:
print(i)
Output:
String Iteration
G
e
e
k
s

38
 While loop

Python While Loop is used to execute a block of statements repeatedly until a given condition is
satisfied. And when the condition becomes false, the line immediately after the loop in the
program is executed.

Syntax:
while expression:
statement(s)
Example:
# Python program to illustrate
# while loop
count = 0
while (count < 3):
count = count + 1
print("Hello Geek")
Output:
Hello Geek
Hello Geek
Hello Geek

 Break statement

Python break statement brings control out of the loop.


Example: Python For Loop with Break Statement
for letter in 'geeksforgeeks':
# break the loop as soon it sees 'e'
# or 's'
if letter == 'e' or letter == 's':
break
print('Current Letter :', letter)
Output: Current Letter : e

39
 Continue Statement

Continue is also a loop control statement just like the break statement. continue statement is
opposite to that of break statement, instead of terminating the loop, it forces to execute the next
iteration of the loop. As the name suggests the continue statement forces the loop to continue or
execute the next iteration. When the continue statement is executed in the loop, the code inside
the loop following the continue statement will be skipped and the next iteration of the loop will
begin.
Syntax: Continue
Example:
# loop from 1 to 10
for i in range(1, 11):
# If i is equals to 6,
# continue to next iteration
# without printing
if i == 6:
continue
else:
# otherwise print the value
# of i
print(i, end = " ")
Output: 1 2 3 4 5 7 8 9 10

 Pass Statement

The pass statement to write empty loops. Pass is also used for empty control statements,
functions, and classes.
Example: Python For Loop with Pass Statemet
# An empty loop
for letter in 'geeksforgeeks':
pass
print('Last Letter :', letter)
Output: Last Letter : s

40
UNIT 3
FUNCTIONS

PYTHON FUNCTION
It is a block of statements that return the specific task. The idea is to put some commonly or
repeatedly done tasks together and make a function so that instead of writing the same code
again and again for different inputs, we can do the function calls to reuse code contained in it
over and over again.
Syntax: Python Functions

 Creating a Python Function

We can create a Python function using the def keyword.


Example
# A simple Python function def fun():
print("Welcome to GFG")

 Calling a Python Function

After creating a function we can call it by using the name of the function followed by parenthesis
containing parameters of that particular function.
Example:
# A simple Python function

41
def fun():
print("Welcome to GFG")
# Driver code to call a function
fun()
Output: Welcome to GFG

 Defining and calling a function with parameters

If you have experience in C/C++ or Java then you must be thinking about the return type of the
function and data type of arguments. That is possible in Python as well (specifically for Python
3.5 and above).

Syntax: Python Function with parameters

def function_name(parameter: data_type) -> return_type:


"""Docstring"""
# body of the function
return expression
The following example uses arguments that you will learn later in this article so you can come
back on it again if not understood. It is defined here for people with prior experience in
languages like C/C++ or Java.

def add(num1: int, num2: int) -> int:


"""Add two numbers"""
num3 = num1 + num2
return num3
# Driver code
num1, num2 = 5, 15
ans = add(num1, num2)
print(f"The addition of {num1} and {num2} results {ans}.")
Output: The addition of 5 and 15 results 20.

42
Example:
# some more functions
def is_prime(n):
if n in [2, 3]:
return True

if (n == 1) or (n % 2 == 0):
return False
r=3
while r * r <= n:
if n % r == 0:
return False
r += 2
return True
print(is_prime(78), is_prime(79))
Output: False True

ARGUMENTS OF PYTHON FUNCTION


Arguments are the values passed inside the parenthesis of the function. A function can have any
number of arguments separated by a comma. In this example, we will create a simple function to
check whether the number passed as an argument to the function is even or odd.
Example:
# A simple Python function to check # whether x is even or odd
def evenOdd(x):
if (x % 2 == 0):
print("even")
else:
print("odd")
# Driver code to call the function
evenOdd(2)
evenOdd(3)

43
Output:
even
odd

 Types of Arguments

Python supports various types of arguments that can be passed at the time of the function call.
Let’s discuss each type in detail.

1. Default arguments

A default argument is a parameter that assumes a default value if a value is not provided in the
function call for that argument. The following example illustrates Default arguments.
Example:
# Python program to demonstrate # default arguments
def myFun(x, y=50):
print("x: ", x)
print("y: ", y)
# Driver code (We call myFun() with only argument)
myFun(10)
Output:
x: 10
y: 50
Like C++ default arguments, any number of arguments in a function can have a default value.
But once we have a default argument, all the arguments to its right must also have default values.

2. Keyword arguments

The idea is to allow the caller to specify the argument name with values so that caller does not
need to remember the order of parameters.

44
Example:
# Python program to demonstrate Keyword Arguments
def student(firstname, lastname):
print(firstname, lastname)
# Keyword arguments
student(firstname='Geeks', lastname='Practice')
student(lastname='Practice', firstname='Geeks')
Output:
Geeks Practice
Geeks Practice

3. Variable-length arguments

In Python, we can pass a variable number of arguments to a function using special symbols.
There are two special symbols:
 *args (Non-Keyword Arguments)
 **kwargs (Keyword Arguments)

Example 1: Variable length non-keywords argument

# Python program to illustrate


# *args for variable number of arguments
def myFun(*argv):
for arg in argv:
print(arg)
myFun('Hello', 'Welcome', 'to', 'GeeksforGeeks')
Output:
Hello
Welcome
to
GeeksforGeeks

45
Example 2: Variable length keyword arguments
# Python program to illustrate
# *kwargs for variable number of keyword arguments
def myFun(**kwargs):
for key, value in kwargs.items():
print("%s == %s" % (key, value))
# Driver code
myFun(first='Geeks', mid='for', last='Geeks')
Output:
first == Geeks
mid == for
last == Geeks

ANONYMOUS FUNCTIONS IN PYTHON FUNCTION


In Python, an anonymous function means that a function is without a name. As we already know
the def keyword is used to define the normal functions and the lambda keyword is used to create
anonymous functions.

Example:
# Python code to illustrate the cube of a number
# using lambda function
def cube(x): return x*x*x
cube_v2 = lambda x : x*x*x
print(cube(7))
print(cube_v2(7))

Output:
343
343

46
FRUITFUL FUNCTIONS
These are the functions that return a value after their completion. A fruitful function must always
return a value to where it is called from. A fruitful function can return any type of value may it
be string, integer, boolean, etc. It is not necessary for a fruitful function to return the value of one
variable, the value to be returned can be an array or a vector. A fruitful function can also return
multiple values.

Example:
# Creation of Function
function add_f(a, b);
c = a + b;
# Returning the value
return c;
end
# Function call
d = add_f(3, 4);
print(d)

Output:

47
PYTHON SCOPE OF VARIABLES
In Python, variables are the containers for storing data values. They are reference, or pointers, to
an object in memory which means that whenever a variable is assigned to an instance, it gets
mapped to that instance. Unlike other languages like C/C++/JAVA, Python is not “statically
typed”. We do not need to declare variables before using them or declare their type. A variable is
created the moment we first assign a value to it.
Example:
# Python program to demonstrate # variable assignment
# An integer assignment
age = 45
# A floating point
salary = 1456.8
# A string
name = "John"
print(age)
print(salary)
print(name)
Output:
45
1456.8
John

 Scope of Variable

The location where we can find a variable and also access it if required is called the scope of a
variable.

 Global variables

Global variables are the ones that are defined and declared outside any function and not specified
to any function. They can be used by any part of the program.

48
Example 1:

# This function uses global variables


def f():
print(s)
# Global scope
s = "I love Geeksforgeeks" f()
Output:
I love Geeksforgeeks

Example 2:
# This function has a variable with
# name same as s.
def f():
s= “Me too.”
print(s)
# Global scope
s = "I love Geeksforgeeks"
f()
print(s)
Output:
Me too.
I love Geeksforgeeks

The variable s is defined as the string “I love Geeksforgeeks”, before we call the function f().
The only statement in f() is the print(s) statement. As there is no local s, the value from the
global s will be used.

49
UNIT 4
LIST, TUPLES AND DICTIONARIES

LIST
Lists are one of the most versatile data types that you can work on in Python. In this language,
the list is going to contain different items that are either enclosed with the square brackets or
separated out with commas.

They are similar to the arrays that you would see in C if you’ve worked with that program. The
one difference that comes up with these is that the items that are in a list can be from different
data types.

The values that are stored inside the list can be accessed with a slice operator as well as the [:}
symbol with the indexes starting at 0 at the beginning of the list and then working down until
you get to -1. The plus sign will be the concatenation operator while you can use the asterisk as
the repetition operator

 List Operations

The + operator concatenates lists:

>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> c = a + b
>>> c [1, 2, 3, 4, 5, 6]

The * operator repeats a list a given number of times:


>>> [0] * 4
[0, 0, 0, 0]
>>> [1, 2, 3] * 3
[1, 2, 3, 1, 2, 3, 1, 2, 3]

50
The first example repeats [0] four times. The second example repeats the list [1, 2, 3] three times.

 List Slices

The slice operator also works on lists:

>>> t = ['a', 'b', 'c', 'd', 'e', 'f']


>>> t[1:3] ['b', 'c']
>>> t[:4] ['a', 'b', 'c', 'd']
>>> t[3:] ['d', 'e', 'f']

If you omit the first index, the slice starts at the beginning. If you omit the second, the slice goes
to the end. So if you omit both, the slice is a copy of the whole list: >>> t[:] ['a', 'b', 'c', 'd', 'e', 'f']
Since lists are mutable, it is often useful to make a copy before performing operations that
modify lists.

A slice operator on the left side of an assignment can update multiple elements: >>> t = ['a', 'b',
'c', 'd', 'e', 'f'] >>> t[1:3] = ['x', 'y'] >>> t ['a', 'x', 'y', 'd', 'e', 'f']

 List Methods

Python provides methods that operate on lists.

For example, append adds a new ele‐ ment to the end of a list:
>>> t = ['a', 'b', 'c']
>>> t.append('d')
>>> t ['a', 'b', 'c', 'd']
extend takes a list as an argument and appends all of the elements:
>>> t1 = ['a', 'b', 'c']
>>> t2 = ['d', 'e']
>>> t1.extend(t2)
>>> t1 ['a', 'b', 'c', 'd', 'e']

51
This example leaves t2 unmodified. sort arranges the elements of the list from low to high:
>>> t = ['d', 'c', 'e', 'b', 'a']
>>> t.sort() >>> t ['a', 'b', 'c', 'd', 'e']
Most list methods are void; they modify the list and return None. If you accidentally write t =
t.sort(), you will be disappointed with the result.

 List loop:

One common way to iterate through a list is to use a for loop. Example:
for item in my_list:
print(item)
This will print each item in the list on a new line.

Another way to loop through a list is to use a while loop and an index variable.
Example:
i=0
while i<len(my_list);
print(my_list[i])
i+=1
This will also print each item in the list on a new line.

You can also use list comprehension to create a new list based on an existing list.
Example:
new_list=[item*2 for item in my_list if type(item)==int]

This will create a new list that contains the integer items in new_list multiplied by 2.

 Mutability

The mutability of lists means that you can add, remove, or modify elements in a list after it has
been created. Here are some examples of list mutations:

52
Adding elements: You can add elements to a list using the append() method or the extend()
method. For example:
my_list = [1, 2, 3]
my_list.append(4)
print(my_list)
# [1, 2, 3, 4]
my_list.extend([5, 6])
print(my_list)
# [1, 2, 3, 4, 5, 6]

Removing elements: You can remove elements from a list using the remove() method, the pop()
method, or the del statement. For example:
my_list = [1, 2, 3, 4, 5]
my_list.remove(3)
print(my_list)
# [1, 2, 4, 5]
popped_item = my_list.pop(1)
print(my_list)
# [1, 4, 5]
print(popped_item)
#2
del my_list[0]
print(my_list)
# [4, 5]

Modifying elements: You can modify elements in a list by assigning new values to specific
indices. For example:
my_list = [1, 2, 3]
my_list[1] = 4
print(my_list)
# [1, 4, 3]

53
It's important to note that because lists are mutable, they can be modified in place, which means
that any variables that reference the list will also see the changes. This can be useful, but it can
also lead to unexpected behavior if you're not careful.

Aliasing
If a refers to an object and you assign b = a, then both variables refer to the same object:
>>> a = [1, 2, 3]
>>> b = a
>>> b is a True

The association of a variable with an object is called a reference. In this example, there are two
references to the same object.

An object with more than one reference has more than one name, so we say that the object is
aliased. If the aliased object is mutable, changes made with one alias affect the other:
>>> b[0] = 42
>>> a [42, 2, 3]
Although this behavior can be useful, it is error-prone. In general, it is safer to avoid aliasing
when you are working with mutable objects.

For immutable objects like strings, aliasing is not as much of a problem. In this example: a =
'banana'
b = 'banana'

It almost never makes a difference whether a and b refer to the same string or not.

 List Comprehension

List comprehension offers a shorter syntax when you want to create a new list based on the
values of an existing list.

54
Based on a list of fruits, you want a new list, containing only the fruits with the letter "a" in the
name. Without list comprehension you will have to write a for statement with a conditional test
inside
Example
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = []
for x in fruits:
if "a" in x:
newlist.append(x)
print(newlist)
Output: ['apple', 'banana', 'mango']

 List Methods

Python has a set of built-in methods that you can use on lists.

Method Description

append() Adds an element at the end of the list

clear() Removes all the elements from the list

copy() Returns a copy of the list

count() Returns the number of elements with the specified value

extend() Add the elements of a list (or any iterable), to the end of the current list

index() Returns the index of the first element with the specified value

insert() Adds an element at the specified position

pop() Removes the element at the specified position

remove() Removes the item with the specified value

reverse() Reverses the order of the list

sort() Sorts the list

55
TUPLES
Tuples are just like lists, but you cannot modify their values. The initial values are the values that
will stay for the rest of the program. An example where tuples are useful is when your program
needs to store the names of the months of the year.

To declare a tuple, you write tupleName = (initial values). Notice that we use round brackets ( )
when declaring a tuple. Multiple values are separated by a comma.

Example: monthsOfYear = (“Jan” , “Feb” , “Mar” , “Apr” , “May” , “Jun” , “Jul” , “Aug” ,
“Sep” , “Oct” , “Nov” , “Dec”)

You access the individual values of a tuple using their indexes, just like with a list. Hence,
monthsOfYear[0] = “Jan” , monthsOfYear[-1] = “Dec”

 Tuple Assignment

It is often useful to swap the values of two variables. With conventional assignments, you have
to use a temporary variable.
For example, to swap a and b:
>>> temp = a
>>> a = b
>>> b = temp

This solution is cumbersome; tuple assignment is more elegant:


>>> a, b = b, a

The left side is a tuple of variables; the right side is a tuple of expressions. Each value is assigned
to its respective variable. All the expressions on the right side are evalu‐ ated before any of the
assignments. The number of variables on the left and the number of values on the right have to
be the same:

56
>>> a, b = 1, 2, 3
ValueError: too many values to unpack

More generally, the right side can be any kind of sequence (string, list or tuple). For example, to
split an email address into a user name and a domain, you could write:
>>> addr = '[email protected]'
>>> uname, domain = addr.split('@')

The return value from split is a list with two elements; the first element is assigned to uname, the
second to domain:
>>> uname 'monty'
>>> domain 'python.org'

 Tuples as Return Values

Strictly speaking, a function can only return one value, but if the value is a tuple, the effect is the
same as returning multiple values. For example, if you want to divide two integers and compute
the quotient and remainder, it is inefficient to compute x/y and then x%y. It is better to compute
them both at the same time.

The built-in function divmod takes two arguments and returns a tuple of two values: the quotient
and remainder. You can store the result as a tuple
>>> t = divmod(7, 3)
>>> t (2, 1)

Or use tuple assignment to store the elements separately:


>>> quot, rem = divmod(7, 3)
>>> quot 2
>>> rem 1

57
Here is an example of a function that returns a tuple:
def min_max(t):
return min(t), max(t)

max and min are built-in functions that find the largest and smallest elements of a sequence.
min_max computes both and returns a tuple of two values

DICTIONARY
Dictionary is a collection of related data PAIRS. For instance, if we want to store the username
and age of 5 users, we can store them in a dictionary.

To declare a dictionary, you write dictionaryName = {dictionary key : data}, with the
requirement that dictionary keys must be unique (within one dictionary). That is, you cannot
declare a dictionary like this
myDictionary = {“Peter”:38, “John”:51, “Peter”:13}.

This is because “Peter” is used as the dictionary key twice. Note that we use curly brackets { }
when declaring a dictionary. Multiple pairs are separated by a comma. Example:
userNameAndAge = {“Peter”:38, “John”:51, “Alex”:13, “Alvin”:“Not Available”}

You can also declare a dictionary using the dict( ) method. To declare the userNameAndAge
dictionary above, you write
userNameAndAge = dict(Peter = 38, John = 51, Alex = 13, Alvin = “Not Available”)

When you use this method to declare a dictionary, you use round brackets ( ) instead of curly
brackets { } and you do not put quotation marks for the dictionary keys.

To access individual items in the dictionary, we use the dictionary key, which is the first value in
the {dictionary key : data} pair. For instance, to get John’s age, you write
userNameAndAge[“John”]. You’ll get the value 51.

58
To modify items in a dictionary, we write dictionary Name[dictionary key of item to be
modified] = new data. For instance, to modify the “John”:51 pair, we write
userNameAndAge[“John”] = 21.

Our dictionary now becomes


userNameAndAge = {“Peter”:38, “John”:21, “Alex”:13, “Alvin”: “Not Available”}.

We can also declare a dictionary without assigning any initial values to it. We simply write
dictionaryName = { }. What we have now is an empty dictionary with no items in it.

To add items to a dictionary, we write dictionaryName [dictionary key] = data. For instance, if
we want to add “Joe”:40 to our dictionary, we write userNameAndAge[“Joe”] = 40. Our
dictionary now becomes userNameAndAge = {“Peter”:38, “John”:21, “Alex”:13, “Alvin”:“Not
Available” , “Joe”:40}. To remove items from a dictionary, we write del
dictionaryName[dictionary key]. For instance, to remove the “Alex”:13 pair, we write del
userNameAndAge[“Alex”]. Our dictionary now becomes userNameAndAge = {“Peter”:38,
“John”:21, “Alvin”:“Not Available” , “Joe”:40}

Example:
#declaring the dictionary, dictionary keys and data can be of different data types
myDict = {“One”:1.35, 2.5:”Two Point Five” , 3:”+” , 7.9:2}
#print the entire dictionary
print(myDict)
#You’ll get {2.5: 'Two Point Five' , 3: '+' , 'One': 1.35, 7.9: 2}
#Note that items in a dictionary are not stored in the same order as the way you declare them
#print the item with key = “One”.
print(myDict[“One”])
#You’ll get 1.35
#print the item with key = 7.9
print(myDict[7.9])
#You’ll get 2

59
#modify the item with key = 2.5 and print the updated dictionary
myDict[2.5] = “Two and a Half”
print(myDict)
#You’ll get {2.5: 'Two and a Half' , 3: '+' , 'One': 1.35, 7.9: 2}
#add a new item and print the updated dictionary
myDict[“New item”] = “I’m new”
print(myDict)
#You’ll get {'New item': 'I’m new' , 2.5: 'Two and a Half' , 3: '+' , 'One': 1.35, 7.9: 2}
#remove the item with key = “One” and print the updated dictionary
del myDict[“One”]
print(myDict)
#You’ll get {'New item': 'I’m new' , 2.5: 'Two and a Half' , 3: '+' , 7.9: 2}

 Dictionary Methods

Python has a set of built-in methods that you can use on dictionaries.
Method Description

clear() Removes all the elements from the dictionary

copy() Returns a copy of the dictionary

fromkeys() Returns a dictionary with the specified keys and value

get() Returns the value of the specified key

items() Returns a list containing a tuple for each key value pair

keys() Returns a list containing the dictionary's keys

pop() Removes the element with the specified key

popitem() Removes the last inserted key-value pair

setdefault() Returns the value of the specified key. If the key does not exist: insert the key,
with the specified value
update() Updates the dictionary with the specified key-value pairs

values() Returns a list of all the values in the dictionary

60
INSERTION SORT
The Insertion sort is a straightforward and more efficient algorithm than the previous bubble sort
algorithm. The insertion sort algorithm concept is based on the deck of the card where we sort
the playing card according to a particular card. It has many advantages, but there are many
efficient algorithms available in the data structure. While the card-playing, we compare the
hands of cards with each other. Most of the player likes to sort the card in the ascending order so
they can quickly see which combinations they have at their disposal.

The insertion sort implementation is easy and simple because it's generally taught in the
beginning programming lesson. It is an in-place and stable algorithm that is more beneficial for
nearly-sorted or fewer elements. The insertion sort algorithm is not so fast because of it uses
nested loop for sort the elements.

Code:
# Insertion sort in Python
def insertionSort(array):
for step in range(1, len(array)):
key = array[step]
j = step - 1
# Compare key with each element on the left of it until an element smaller than it is found
# For descending order, change key<array[j] to key>array[j].
while j >= 0 and key < array[j]:
array[j + 1] = array[j]
j=j-1
# Place key at after the element just smaller than it.
array[j + 1] = key

data = [9, 5, 1, 4, 3]
insertionSort(data)
print('Sorted Array in Ascending Order:')
print(data)

61
SELECTION SORT

In this algorithm, we select the smallest element from an unsorted array in each pass and swap
with the beginning of the unsorted array. This process will continue until all the elements are
placed at right place. It is simple and an in-place comparison sorting algorithm.

Working of Selection Sort


The following are the steps to explain the working of the Selection sort in Python.

Let's take an unsorted array to apply the selection sort algorithm. [30, 10, 12, 8, 15, 1]
Step - 1: Get the length of the array. length = len(array) → 6
Step - 2: First, we set the first element as minimum element.
Step - 3: Now compare the minimum with the second element. If the second element is smaller
than the first, we assign it as a minimum. Again we compare the second element to the third and
if the third element is smaller than second, assign it as minimum. This process goes on until we
find the last element.
Step - 4: After each iteration, minimum element is swapped in front of the unsorted array.
Step - 5: The second to third steps are repeated until we get the sorted array.

Code:
# Selection sort in Python
def selectionSort(array, size):
for step in range(size):
min_idx = step
for i in range(step + 1, size):
# to sort in descending order, change > to < in this line
# select the minimum element in each loop
if array[i] < array[min_idx]:
min_idx = i
# put min at the correct position
(array[step], array[min_idx]) = (array[min_idx], array[step])

62
data = [-2, 45, 0, 11, -9]
size = len(data)
selectionSort(data, size)
print('Sorted Array in Ascending Order:')
print(data)

MERGE SORT
Merge sort is similar to the quick sort algorithm as works on the concept of divide and conquer.
It is one of the most popular and efficient sorting algorithm. It is the best example for divide and
conquer category of algorithms. It divides the given list in the two halves, calls itself for the two
halves and then merges the two sorted halves. We define the merge() function used to merging
two halves.

The sub lists are divided again and again into halves until we get the only one element each.
Then we combine the pair of one element lists into two element lists, sorting them in the process.
The sorted two element pairs is merged into the four element lists, and so on until we get the
sorted list.

Code:
# MergeSort in Python
def mergeSort(array):
if len(array) > 1:

# r is the point where the array is divided into two subarrays


r = len(array)//2
L = array[:r]
M = array[r:]
# Sort the two halves
mergeSort(L)
mergeSort(M)
i=j=k=0

63
# Until we reach either end of either L or M, pick larger among
# elements L and M and place them in the correct position at A[p..r]
while i < len(L) and j < len(M):
if L[i] < M[j]:
array[k] = L[i]
i += 1
else:
array[k] = M[j]
j += 1
k += 1
# When we run out of elements in either L or M,
# pick up the remaining elements and put in A[p..r]
while i < len(L):
array[k] = L[i]
i += 1
k += 1
while j < len(M):
array[k] = M[j]
j += 1
k += 1
# Print the array
def printList(array):
for i in range(len(array)):
print(array[i], end=" ")
print()
# Driver program
if __name__ == '__main__':
array = [6, 5, 12, 10, 9, 1]
mergeSort(array)
print("Sorted array is: ")
printList(array)

64
UNIT 5
OBJECT ORIENTED PROGRAMMING (OOP) IN PYTHON

INTRODUCTION TO OBJECT ORIENTED PROGRAMMING


Python has been an object-oriented language since it existed. Because of this, creating and using
classes and objects are very easy. The OOP is more value as the program size is growing. The
procedural programming may produce some side affect and have no data security. The main
advantage of the OOP is that, the data can be combined with functions that are acting on the data
into a single unit. This process is called “encapsulation”. The basic unit that provides this
encapsulation is the “class” keyword.

CLASS
Defining the class in python is very easy. The class definition can appear anywhere in the
program, but usually they are written in the beginning. The definition contains two things:
● Class header
● Class body
Class header begins with “class” keyword followed by the class_name, and colon (:) at the end.
The body of the class contains one or more statements. These statements are normally data
members and member function. The class variables and methods together called “Class
Members”. The data members are also called as instance variables.
#defining the class
class Employee:
# class header class variable
Data Member1
Data Member2
Member function1 class body
Member function 2

Where class is the keyword, Employee is the class name. The class header contains class
keyword, class name and colon (:) operator. The class body contains class variables, data
members and member functions.

65
SELF VARIABLE:
The self argument refers to the current object. Python takes care of passing the current object as
argument to the method while calling. Even if the method does not contain the argument, Python
passes this “current object” that called the method as argument, which in turn is assigned to the
self variable in the method definition.

Similarly a method defined to take one argument will actually take two arguments: self and
parameter.

#defining class and creating the object class


ABC:
def init (self,b):
self.balance=b
def disp(self): # method with self argument
print("The amount is:",self.balance)

ob=ABC(1000);
ob.disp() //method is called without argument, python passes „ob‟ as argument at the
background.

INHERITANCES:

Inheritance allows us to define a class that inherits all the methods and properties from
another class. Parent class is the class being inherited from, also called base class. Child class is
the class that inherits from another class, also called derived class.

 Types of Inheritances
1. Single Inheritance:

Single inheritance enables a derived class to inherit properties from a single parent class, thus
enabling code reusability and the addition of new features to existing code.

66
Example:
# Python program to demonstrate
# single inheritance
# Base class
class Parent:
def func1(self):
print("This function is in parent class.")
# Derived class
class Child(Parent):
def func2(self):
print("This function is in child class.")
# Driver's code
object = Child()
object.func1()
object.func2()

Output:
This function is in parent class.
This function is in child class.

2. Multiple Inheritance:

When a class can be derived from more than one base class this type of inheritance is called
multiple inheritances. In multiple inheritances, all the features of the base classes are inherited
into the derived class.

67
Example:
# Python program to demonstrate
# multiple inheritance
# Base class1
class Mother:
mothername = ""
def mother(self):
print(self.mothername)
# Base class2
class Father:
fathername = ""
def father(self):
print(self.fathername)
# Derived class
class Son(Mother, Father):
def parents(self):
print("Father :", self.fathername)
print("Mother :", self.mothername)
# Driver's code
s1 = Son()
s1.fathername = "RAM"
s1.mothername = "SITA"
s1.parents()

68
Output:
Father : RAM
Mother : SITA

3. Multilevel Inheritance :

In multilevel inheritance, features of the base class and the derived class are further inherited into
the new derived class. This is similar to a relationship representing a child and a grandfather.

Example
# Python program to demonstrate
# multilevel inheritance
# Base class
class Grandfather:
def init (self, grandfathername):
self.grandfathername = grandfathername
# Intermediate class
class Father(Grandfather):
def init (self, fathername, grandfathername):
self.fathername = fathername
# invoking constructor of Grandfather class
Grandfather. init (self, grandfathername)

69
# Derived class
class Son(Father):
def init (self, sonname, fathername, grandfathername):
self.sonname = sonname
# invoking constructor of Father class
Father. init (self, fathername, grandfathername)

def print_name(self):
print('Grandfather name :', self.grandfathername)
print("Father name :", self.fathername)
print("Son name :", self.sonname)
# Driver code
s1 = Son('Prince', 'Rampal', 'Lal mani')
print(s1.grandfathername)
s1.print_name()
Output:
Lal mani
Grandfather name : Lal mani
Father name : Rampal
Son name : Prince

Hierarchical Inheritance:
When more than one derived class are created from a single base this type of inheritance is called
hierarchical inheritance. In this program, we have a parent (base) class and two child (derived)
classes.

70
Example:
# Python program to demonstrate
# Hierarchical inheritance
# Base class
class Parent:
def func1(self):
print("This function is in parent class.")
# Derived class1
class Child1(Parent):
def func2(self):
print("This function is in child 1.")
# Derivied class2
class Child2(Parent):
def func3(self):
print("This function is in child 2.")
# Driver's code
object1 = Child1()
object2 = Child2()
object1.func1()
object1.func2()
object2.func1()
object2.func3()

Output:
This function is in parent class.
This function is in child 1.
This function is in parent class.
This function is in child 2.

71
Hybrid Inheritance:
Inheritance consisting of multiple types of inheritance is called hybrid inheritance.

Example:
# Python program to demonstrate
# hybrid inheritance
class School:
def func1(self):
print("This function is in school.")
class Student1(School):
def func2(self):
print("This function is in student 1. ")
class Student2(School):
def func3(self):
print("This function is in student 2.")
class Student3(Student1, School):
def func4(self):
print("This function is in student 3.")

72
# Driver's code
object = Student3()
object.func1()
object.func2()

Output:
This function is in school.
This function is in student 1.

OVER-RIDING
Method overriding is an ability of any object-oriented programming language that allows a
subclass or child class to provide a specific implementation of a method that is already provided
by one of its super-classes or parent classes. When a method in a subclass has the same name,
same parameters or signature and same return type (or sub-type) as a method in its super-class,
then the method in the subclass is said to override the method in the super-class.

The version of a method that is executed will be determined by the object that is used to invoke
it. If an object of a parent class is used to invoke the method, then the version in the parent class
will be executed, but if an object of the subclass is used to invoke the method, then the version in
the child class will be executed. In other words, it is the type of the object being referred to (not

73
the type of the reference variable) that determines which version of an overridden method will be
executed.

Example:
# Python program to demonstrate
# method overriding
# Defining parent class
class Parent():
# Constructor
def init (self):
self.value = "Inside Parent"
# Parent's show method
def show(self):
print(self.value)
# Defining child class
class Child(Parent):
# Constructor
def init (self):
self.value = "Inside Child"
# Child's show method
def show(self):
print(self.value)
# Driver's code
obj1 = Parent()
obj2 = Child()
obj1.show()
obj2.show()

Output:
Inside Parent
Inside Child

74
DATA HIDING
Data hiding is a concept which underlines the hiding of data or information from the user. It is
one of the key aspects of Object-Oriented programming strategies. It includes object details such
as data members, internal work. Data hiding excludes full data entry to class members and
defends object integrity by preventing unintended changes. Data hiding also minimizes system
complexity for increase robustness by limiting interdependencies between software
requirements. Data hiding is also known as information hiding. In class, if we declare the data
members as private so that no other class can access the data members, then it is a process of
hiding data.

The Python document introduces Data Hiding as isolating the user from a part of program
implementation. Some objects in the module are kept internal, unseen, and unreachable to the
user. Modules in the program are easy enough to understand how to use the application, but the
client cannot know how the application functions. Thus, data hiding imparts security, along with
discarding dependency. Data hiding in Python is the technique to defend access to specific users
in the application. Python is applied in every technical area and has a user-friendly syntax and
vast libraries. Data hiding in Python is performed using the double underscore before done
prefix. This makes the class members non-public and isolated from the other classes.

Example:
class Solution:
privateCounter = 0
def sum(self):
self. privateCounter += 1
print(self. privateCounter)
count = Solution()
count.sum()
count.sum()
# Here it will show error because it unable
# to access private member
print(count. privateCount)

75
Output:
Traceback (most recent call last):
File "/home/db01b918da68a3747044d44675be8872.py", line 11, in
<module>
print(count. privateCount)
AttributeError: 'Solution' object has no attribute ' privateCount'

 Advantages of Data Hiding:

1. It helps to prevent damage or misuse of volatile data by hiding it from the public.
2. The class objects are disconnected from the irrelevant data.
3. It isolates objects as the basic concept of OOP.
4. It increases the security against hackers that are unable to access important data.

 Disadvantages of Data Hiding:

1. It enables programmers to write lengthy code to hide important data from common
clients.
2. The linkage between the visible and invisible data makes the objects work faster, but
data hiding prevents this linkage.

76

You might also like