Study Material for Python (Advanced)

Python Programming

 

 

1. Introduction: Python is a widely used high-level programming language. It was created by Guido van Rossum and first released in 1991. Python has various features:

 

  • Object-Oriented.

  • Functional programming.

  • Automatic memory management

  • Supports multiple programming paradigms and procedural styles. 

  • It has a large and comprehensive standard library.

 

a) Two major versions of Python are currently in active use:

 

  • Python 3.x is the current version and is under active development.

  • Python 2.x is the legacy version and will receive only security updates until 2020. No new features will be implemented. 

  • Many projects are still using Python 2 but can be easily migrated into Python 3.

 

b) Some important points: 

 

  • IDLE is a simple editor for Python that comes bundled with Python.

  • You can simply type the code in the prompt.

>>> print(“ Hello World”) and press enter you will get your output on the prompt.

  • You can create a Python file with an extension .py.

hello.py

  • If using Python 2, you may also type the print statement given below but this is not valid in Python 3 as it reduces cross-version code compatibility.

print 'Hello, World'

  • In your terminal, navigate to the directory containing the file hello.py. Type python hello.py then hit the Enter key.

$ python hello.py

Hello, World

You should see Hello, World printed on the console.

 

2. Creating Variables: To create a variable in Python, all you need to do is specify the variable name, and then assign a value to it.

<variable name> = <value>

Python uses = to assign values to variables. There is no need to declare a variable in advance or to assign data types because these tasks are done automatically when you create any variable.

For Example,   

a = 2

print(a)

# Output: 2

 

name = 'John Doe'

print(name)

# Output: John Doe

 

a) Rules for naming variables:

 

  • Variable names must start with a letter or an underscore.

  • The variable name may consist of letters, numbers, and underscores.

  • Names are case-sensitive.

x = 2

y = X*3

=>NameError: name 'X' is not defined

Even though there is no need to specify a data type when declaring a variable in Python, while allocating the necessary area in memory for the variable, the Python interpreter automatically picks the most suitable built-in type for it:

a = 2

print(type(a))

# Output: <type 'int'>

 

name = 'John Doe'

print(type(name))

# Output: <type 'str'>

  • You can assign multiple values to multiple variables in one line. But keep in mind that the number of values should be equal to the number of variables.

a, b, c = 1, 2, 3

print(a, b, c)

# Output: 1 2 3

You can use the dummy variable, rather than giving them names you can use (_) for assigning unwanted values.

a, b, _ = 1, 2, 3

print(a, b)

# Output: 1, 2

  • You can also assign a single value to several variables simultaneously.

a = b = c = 1

print(a, b, c)

# Output: 1 1 1

 

b) Deleting Variables in Python: You can delete python variables by using del keyword.

For Example,

color = "Orange"

print(color)

del (color)

print(color)

Output: 

Orange

Traceback (most recent call last):

  File "<string>", line 7, in <module>

NameError: name 'color' is not defined

 

c) Block indentation: Python uses indentation to define control and loop constructs. It improves Python's readability, and the programmer has to pay attention to use the whitespaces. Python uses the colon symbol ( : ) and indentation for showing where blocks of code begin and end. All blocks start with a colon and then contain the indented lines below it.

if a > b:

print(a)

else:

print(b)

 

d) Swapping in Python: Swapping means interchanging the values of two variables. eg - if x is 10 and y is 20 then after swapping x will be 20 and y will be 10.

For Example,

x = 10

0y = 20

x,y = y,x

print(x)

print(y)

Output: 

20

10

 

3. Data Types:

 

a) Built-in data types: 

 

i) bool: A boolean gives you True or False values. Logical operations like and, or, not can be performed on booleans.

x or y       # if x is False then y otherwise x

x and y    # if x is False then x otherwise y

not x        # if x is True then False, otherwise True

 

ii) Numbers:

  • int (Integer) 

a = 5

b = 150

c = 123456789

d = 3812345678912345

 

  • float: Floating point number

a = 3.14

b = 10.e2

 

  • complex: Complex numbers

a = 12 + 12j

b = 15 + 10j

complex_num= 3.14j

 

  • Long:

long_num = 234578956L

 

iii)  Strings: 

  • str: str consists of sequences of Unicode code points that represent textual characters from human languages. Strings are completely immutable, any changes if you make it will create a new string.

  • bytes consist of sequences of 8-bit unsigned values. 

b = b'hello'

print(b)

print(type(b))

s = 'hello'

print(s)

print(type(s))

Output: 

B'hello'

<class 'bytes'>

Hello

<class 'str'>

  • A string consists of a sequence of characters enclosed in single or double quotes. You can access the individual characters or substrings from the given string by specifying their index values.

For Example,

s_str = 'Welcome'

print(s_str)

#output it will display the whole string

print(s_str[0])

#output it will display the first  character. W

print(s_str[3:7])

#output it will display the characters from 4 to 7.

Output: 

Welcome

W

come


 

iv) Sequences and Collections: Python differentiates between ordered sequences and unordered collections.

  • strings ( str, bytes, Unicode ) are sequences.

 

Following are the collectors in Python: 

 tuple: An ordered collection of n values of any type. tuples are enclosed in parentheses ( ) and cannot be updated. 

a = (1, 2, 3)

b = ('a', 1, 'Study Section', (3,4,5))

print(a)

print(b)

b[2] = 'something else' # returns a TypeError

Note: Tuples are immutable.

Output: 

(1, 2, 3)

('a', 1, 'Study Section', (3, 4, 5))

Traceback (most recent call last):

   File "<string>", line 7, in <module>

TypeError: 'tuple' object does not support item assignment

 

list: An ordered collection of n values of any type. Items belonging to a list can be of different data types.

a = [1, 2, 3]

b = ['a', 1, 'python', (1, 2), [1, 2]]

b[2] = 'Study Section' # allowed

print(a)

print(b)

Output: 

[1, 2, 3]

['a', 1, 'Study Section', (1, 2), [1, 2]]

Note: List is mutable.

 

Important Point:

Hashable data types: int, float, str, tuple, and NoneType.  These data types are all immutable in nature.

Unhashable data types: dict, list, and set. These data types are all mutable in nature.

 

set: An unordered collection of unique values. Items must be hashable. 

a = {1, 2, 'a'}

print(a)

Output: 

{1, 2, 'a'} // all the elements are hashable

 

This code will give an error because the third element in it is a list and the list is unhashable.

a = {1, 2, [1,2]}

print(a)

Output: 

Traceback (most recent call last):

File "<string>", line 3, in <module>

TypeError: unhashable type: 'list'

 

i) Sets - They are mutable and new elements can be added once sets are defined.

For Example,

colors = {'red', 'blue', 'green', 'red', 'yellow', 'blue'}

print(colors)

colors.add('orange')

print(colors)

Output:

{'red', 'blue', 'yellow', 'green'}

{'blue', 'green', 'yellow', 'orange', 'red'}

ii) Frozen Sets - They are immutable and new elements cannot be added after they are defined. It consists of one argument only. Once you specified that argument you cannot make changes in that argument.

For Example,

colors = frozenset('Orange')

print(colors)

colors.add('s')

# Above line will cause an error.

print(colors)

Output:

frozenset({'r', 'e', 'a', 'g', 'O', 'n'})

Traceback (most recent call last):

  File "<string>", line 6, in <module>

AttributeError: 'frozenset' object has no attribute 'add'

 

dict: An unordered collection of unique key-value pairs; keys must be hashable.

a = {1: 'one',2: 'two'}

b = {'a': [1, 2, 3],'b': 'a string'}

print(a)

print(b)

Output: 

{1: 'one', 2: 'two'}

{'a': [1, 2, 3], 'b': 'a string'}

 

b) Built-in Constants: 

  • True: The true value of the built-in type bool.

  • False: The false value of the built-in type bool

  • None: A singleton object is used to signal that a value is absent.

  • Ellipsis or ...: Numpy and related packages use this as a 'include everything' reference in arrays.

  • NotImplemented: a singleton is used to indicate to Python that a special method doesn't support the specific arguments, and Python will try alternatives if available.

 

c) Type casting in Python: The process of converting the value of one data type to another data type is called type conversion. Python has two types of type conversion.

 

  • Implicit Type Conversion: In Implicit type conversion, Python automatically converts one data type to another data type. This process doesn't need any user involvement.

n_int = 100

n_flo = 10.5

n_new = n_int + n_flo

print(type(n_int))

print(type(n_flo))

print(n_new)

print(type(n_new))

Output: 

<class 'int'>

<class 'float'>

110.5

<class 'float'>

  • Explicit Type Conversion: In Explicit Type Conversion, users convert the data type of an object to required data type. This type of conversion is also called typecasting because the user casts (changes) the data type of the objects.

n_int = 100

n_str = "105"

print(type(n_int))

print("Before Type Casting:",type(n_str))

n_str = int(n_str) // Type casting operation performed

print("After Type Casting:",type(n_str))

n_sum = n_int + n_str

print(n_sum)

print(type(n_sum))

Output: 

<class 'int'>

Before Type Casting: <class 'str'>

After Type Casting: <class 'int'>

205

<class 'int'>

 

d) Mutable and Immutable Data Types: An object is called mutable if it can be changed. an object is called immutable if it cannot be changed in any way. 

 

  • Examples of immutable Data Types:

int, long, float, complex

Str

bytes

tuple

  • Examples of mutable Data Types:

bytearray

list

set

dict

 

e) Collection Types: Data types like int and str hold a single value, collection types hold multiple values. Following are the collection types in Python: 

 

  • List: List is like an array in other programming languages. It is an ordered collection of valid python values enclosed in square brackets and is separated by a comma.

For Example,

int_list = [1, 2, 3]

string_list = ['abc', 'defghi']

 

  • Tuple: A tuple is similar to a list except that it is fixed-length and immutable. So the values in the tuple cannot be changed nor the values are added to or removed from the tuple. Tuples are represented with parentheses instead of square brackets:

For Example,

ip_address = ('10.20.30.40', 8080)

A tuple with only one member must be defined (note the comma) this way:

one_member_tuple = ('Only member',)

 

  • Dictionary: A dictionary in Python is a collection of key-value pairs. The dictionary is surrounded by curly braces. Each pair is separated by a comma and the key and value are separated by a colon. 

For Example,

phone_directory = {

'Aakash': 7963218439,

'Anjana': 9635648721,

'Sam': 8763549241,

'Rohan': 9643218672

}

print(phone_directory)

 

  • Set: A set is a collection of elements with no repeats and without insertion order but sorted order. They are used in situations where it is only important that some things are grouped together, and not in what order they were included. It is much faster for large groups of data to check whether or not an element is in a set than it is to do the same for a list.

For Example,

first_names = {'Adam', 'Beth', 'Charlie'}

 

4) User Input: To get input from the user, the input function is used. The function takes a string argument, which displays it as a prompt and returns a string.

For Example,

name = input("What is your name? ")

print("My name is",name)

Output: 

What is your name? Sam

My name is Sam

Note: The input is always of type str, but what if you want to enter numbers. In that case, you have to convert it into a number before trying to use it.

For Example,

x = input("Write a number:")   

# Out: Write a number: 20

x / 2

Output: It will cause an error

Write a number:20

Traceback (most recent call last):

   File "<string>", line 5, in <module>

TypeError: unsupported operand type(s) for /: 'str' and 'int'

Correct Code:

x = input("Write a number:")

x= float(x) / 2

print(x)

# to get integer input write the input statement like this:

y = int(input("Write a number:"))

y= y/2

print(int(y))

Output: 

Write a number:20

10.0

Write a number:20

10

You can accept numbers of any base and convert them directly to base-10 with the int function, like this:

For Example,

data = int(input("Enter a number: "), 8)

print(data)

data = int(input("Enter a number: "), 16)

print(data)

data = int(input("Enter a number: "), 2)

print(data)

Output: 

Enter a number: 77

63

Enter a number: 77

119

Enter a number: 101010

42

 

5) Python Operators: Operators are the symbols that perform operations on operands. Following are the operators defined in Python:

  • Arithmetic Operators: These operators perform mathematical calculations on data. Let’s take the value of a and b are 10 and 4

 

Operator

Description

Example

+

Adds operands

a + b = 14

-

Subtracts right operand from the left operand

a - b = 6

*

Multiplies both operands

a * b = 40

/

The quotient of the division of the left operand by the right operand

a / b = 2.5 (float)

//

The quotient of the division of left operand by right

a//b=2(int)

%

The remainder of the division of the left operand by the right operand

a % b = 2

**

Left operand raised to the power of right operand

a ** b = 10000

 

For Example,

a = 10          

b = 4

print("Addition =", a + b)

print("Subtraction =", a - b)

print("Multiplication =", a * b)

print("Division (Float) =", a / b)

print("Division (integer) =", a // b)

print("Remainder =", a % b)

print("Power =", a ** b)

Output: 

Addition = 14

Subtraction = 6

Multiplication = 40

Division (Float) = 2.5

Division (integer) = 2

Remainder = 2

Power = 10000

 

  • Relational Operator: Relational Operators finds the relationship between two operands. It returns True if they are equal and False if they are not equal. Let’s take the value of a and b are 10 and 4

 

Operator

Description

Example

==

Equal to

(a == b) is False

!=

Not equal to

(a != b) is True

>

Greater than

(a > b) is True

<

Less than

(a < b) is False

>=

Greater than or equal to

(a >= b) is True

<=

Less than or equal to

(a <= b) is False

 

For Example,

a = 10

b = 4

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

print("(a != b) is ", a != b)

print("(a > b) is ", a > b)

print("(a < b) is ", a < b)

print("(a >= b) is ", a >= b)

print("(a <= b) is ", a <= b)

Output: 

(a == b) is  False

(a != b) is  True

(a > b) is  True

(a < b) is  False

(a >= b) is  True

(a <= b) is  False

  • Logical Operators: The logical operators return TRUE or FALSE, which are defined as 1 and 0, respectively, depending on the relationship between the parameters.  Let’s assume the value of a to be True and that of b to be False.

 

Operator

Description

Example

and

If both the operands are true, then the condition becomes True

(a and b) is False

or

If both the operands or anyone is true, then the condition becomes True and If both the operands are false, then the condition becomes false

(a or b) is True

not

It is used to reverse the condition. So, if a condition is True, not makes it False and vice versa.

not(a) is False

not(b) is True


 

 

For Example,

x = 7

print(x > 4 and x < 9)

print(x > 4 or x > 9)

print(not(x > 4 and x > 9))

Output: 

True

True

True

 

  • Assignment Operator: Assignment Operators are used to assigning values from its right side operands to its left side operands. The most common assignment operator is =.  There are some other assignment operators which are listed below:

+=,  -=, *=, /=, //=, %=, **=

For Example,

a = 5

a += 5  # It is equivalent to a = a + 5

print("Value of a is:", a)

a -= 5  # It is equivalent to a = a - 5

print("Value of a is :", a)

Output: 

Value of a is: 10

Value of a is : 5

 

  • Identity Operators: It specifies whether the two operands belong to the same memory location or not. 

 

Operator

Description

is

Returns True if the operands refer to the same object. Otherwise returns False.

is not

Returns True if the operands do not refer to the same object. Otherwise returns False.

 

For Example, 

a = [2, 3, 4]

b = [2, 3, 4]

print(a == b)

# It returns true because both the variables contain the same values.

print(a is b)

# It returns false because both the variables belong to different memory locations.

Output:

True

False

 

For Example,

a = [1, 2, 3]

b = a

print(a == b)

# It returns true because both the variables contain the same values.

print(a is b)

# it returns true because both the variables belong to the same memory location.

print(a is not b)

# it returns false because both the variables belong to the same memory locations.

Output: 

True

True

False

 

  • Membership Operator: These operators are used to check if a value is present in a sequence like string, list, tuple, etc. There are two membership operators in Python - in and not in.

 

Operator

Description

in

Returns True if the value is present in the sequence. Otherwise returns False.

not in

Returns True if the value is not present in the sequence. Otherwise returns False

 

For Example, 

a = "Python programming"

print('ing' in a)

print('g' not in a)

Output: 

True

False

 

  • Bitwise Operators: Bitwise operators are used to comparing (binary) numbers:

 

Operator

Name

Description

&

AND

Sets each bit to 1 if both bits are 1

|

OR

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

^

XOR

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

~

NOT

Inverts all the bits

<<

Zero fill left shift

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

>>

Signed right shift

Shift right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off

 

b) Precedence of operators in Python:

 

Operator

Associativity

**

Right to left

* / // %

Left to right

+ =

left to right

== != > < >= <= is, is not, in, not in

Left to right

not

Right to left

and

Left to right

or

Left to right

= += -= *= /= //= %=

Right to left


 

6) Python Conditional statements: Conditional statements involve checking the conditions to take any decision. After checking the conditions it will be decided to execute which set of statements. In these conditional statements indentation matters, so always keep in mind the right indentation while writing the code. 

  • if statement: The code written under this statement executes only when this condition is true.

Syntax:

if condition:

     statement

     statement

      ...

For Example: 

a=10

if(a%2==0):

    print("Number is Even")

Output: 

Number is Even

 

  • if-else statement:  In this statement, if the if block is true it will execute otherwise the else block will execute.

Syntax:

if condition:

     statement

    statement

    …

else:

     statement

    statement

    ...

For Example,

a= int(input("Enter the number"))

if(a%2==0):

     print("Number is Even")

else:

     print("Number is odd")

  • if...elif...else Statement: elif is a short form of else if. It is a combination of multiple if...else statements.

Syntax: 

if condition:

     statement

     statement

     …

elif condition:

     statement

     statement

     …

elif condition:

     statement

     statement

     …

else:

     statement

     statement

     ...

For Example,

marks = int(input("Enter your marks"))

if marks >= 90: 

    print("Excellent!! you got A+")

elif marks < 90 and marks >= 80:

    print("Very Good, You got A grade")

elif marks < 80 and marks >= 70:

     print("You got B+ grade")

elif marks < 70 and marks >= 60:

     print("You got B grade")

elif marks < 60 and marks >= 40:

     print("You got C grade")

else:

     print("You are Fail")

Output:

Enter your marks87

Very Good, You got A grade

 

  • Nested if Statements: When a series of decisions are required, nested if-else is used. Nesting means using one if-else construct within another one.

For Example,

a = int(input("Enter first number")) 

b = int(input("Enter first number"))

c = int(input("Enter first number"))

if (a>b): 

         if (a>c):

         print("a is the greatest number", a)

         else:

         print("c is the greatest number",c)

elif(b>c):

print("b is the greatest number", b)

else:

print("c is the greatest number", c)

Output:

Enter first number10

Enter first number20

Enter first number15

b is the greatest number 20

 

  • pass statement: The pass statement is used if you want to skip if, elif, or else. If we don’t want to give anything in the body of if, elif or else, then we give the pass statement in the body. On executing pass, nothing happens.

For Example,

a= int(input("Enter the number"))

if(a%2==0):

     print("Number is Even")

else:

     pass

print("I don't bother about odd numbers. I just want to check either the number is 

even.")

Output: 

Enter the number 23

I don't bother about odd numbers. I just want to check whether the number is even.


 

7) Python Loop statements: Loop executes the sequence of statements several times until the condition defined becomes false. The purpose of using the loop statements is that when you want to repeat the same code a number of times. There are two types of loops in Python:

 

  • while loop: while loop checks whether the condition is True or not. If the condition is True, the statements written in the body of the while loop are executed. Then again the condition is checked, and if found True again, the statements in the body of the while loop are executed again. This process continues until the condition becomes False.

For Example,

n = 1

while n <= 10:

    print(n)

     n = n + 1

 

For Example,

my_list = [7, 9, 6, 8, 4, 2, 1]

index = 0

while index < len(my_list):

     item = my_list[index]

     if item % 2 == 0:

         print('Even')

     else:

         print('Odd')

     index += 1

Output:

Odd

Odd

Even

Even

Even

Even

Odd

 

  • break and continue statement:

 

a) break: When a break statement executes inside a loop, control flow "breaks" out of the loop immediately:

For Example,

i=1

while i < 8:

     print(i)

     if i == 5:

         print("Break statement, it will break the loop")

         break

     i += 1

b) continue: A continue statement will skip to the next iteration of the loop bypassing the rest of the current block but continuing the loop.

For Example,

i = 1

while i < 10:

     if i == 5:

        i = i + 1

         continue

     print(i)

     i = i + 1

 

  • for loop: If you want to iterate over a certain collection of items, such as list or dict, and want to traverse over every element for loop is used.

For Example,

for i in [1, 2, 3, 4,5]:

     print(i)

Output:

1 2 3 4 5

a) range is a function used to return a sequence of numbers given under an iteration, thus it can be used in for loops:

Syntax:

range(start, stop, step_size)

start: Integer from where the loop starts. It is optional. By default, its value is 0.

stop: It specifies the integer value before which the loop stops iterating. It is 

mandatory.

step_size: It specifies the increment value after each iteration. It is optional. Its 

The default value is 1.

For Example,

for i in range(5):

     print(i)

Output: 

0 1 2 3 4

For Example,

for i in range(1,6):

    print(i)

Output: 

1 2 3 4 5 

For Example,

for i in range(2,11,2):

    print(i)

Output: 

2 4 6 8 10

 

For Example,

numbers = [10, 20, 30, 40, 50]

sum = 0

for i in numbers:

     sum = sum + i

print(sum)

Output:

150

b) If you want your output to show index value with data item,you can use enumerate in for 

Loop.

For Example,

for index, fruits in enumerate(['banana', 'orange', 'apple', 'peach']):

     print(index, ':', fruits)

Output: 

0 : banana

1 : orange

2 : apple

3 : peach

 

  • Loops with an else clause: You can use an else clause with for and while loop, but this loop executes only after the execution of for and while loops. 

For Example, 

for with else:

n1 = [13,22,34,43,35,68,27,88,94,100]

for i in n1:

     if(i%2==0):

         print("Number is Even", i)

else:

     print("Rest of the numbers are odd")

 

For Example,

while with else:

n = [13,22,34,43,35,68,27,88,94,100]

index=0

while(index<len(n)):

     if(n[index]%2==0):

         print("Number is Even", n[index])

     index+=1

else:

     print("Rest of the numbers are odd")

 

Output: Output is the same for both the programs written above.

Number is Even 22

Number is Even 34

Number is Even 68

Number is Even 88

Number is Even 94

Number is Even 100

Rest of the numbers are odd

 

8) Python List: List is a data structure in python, it is a mutable and sequence data type that allows the list to be indexed and sliced. It may contain different types of data. You can access the elements of a list from its index values. 

The below program includes all the slicing operations you can perform on list:

For Example,

a=[1,2,3,4,5,6,7,8]

print(a)

print("Access an element from its index value",a[3])

print("Negative Indexing starts accessing an element from the last", a[-3])

print("Following are slicing operations to access some elements from a list")

print("from 3rd element till 5th element",a[2:5])

print("Print from start to particular index",a[:5])

print("Print from next to a particular index to End", a[4:])

print("from 7th last element till 3rd last element",a[-7:-2])

print("from 3rd element till 3rd last element", a[2:-2])

print("To print the complete list",a[:])

print(a[2:8:2])

print("Print list in reverse order", a[::-1])

Output: 

[1, 2, 3, 4, 5, 6, 7, 8]

Access an element from its index value 4

Negative Indexing starts accessing an element from the last 6

Following are slicing operations to access some elements from a list

from 3rd element till 5th element [3, 4, 5]

Print from start to particular index [1, 2, 3, 4, 5]

Print from next to a particular index to End [5, 6, 7, 8]

from 7th last element till 3rd last element [2, 3, 4, 5, 6]

from 3rd element till 3rd last element [3, 4, 5, 6]

To print the complete list [1, 2, 3, 4, 5, 6, 7, 8]

[3, 5, 7]

Print list in reverse order [8, 7, 6, 5, 4, 3, 2, 1]

 

Method

Description

Example 

Output

append

Add an element at the end of the list.

a = [1, 2, 3, 4, 5]

print("Before")

print(a)

a.append(6)

print("After")

print(a)

Before

[1, 2, 3, 4, 5]

After

[1, 2, 3, 4, 5, 6]

[1, 2, 3, 4, 5, 6, 7]

extend

Add a list within a list.

a = [1, 2, 3, 4, 5, 6, 7]

b = [8, 9]

a.extend(b)

print(a)

print("Extend list with elements from a non-list enumerable")

a.extend(range(10,16))

print(a)

[1, 2, 3, 4, 5, 6, 7, 8, 9]

Extend list with elements from a non-list enumerable

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]

index(value, [startIndex])

Provides the index value of the first occurrence of an element. When an element is not in the list then ValueError Exception is raised. 

a = [1, 2, 3, 4, 5, 6, 7]

print(a.index(6))

# returns output only when value is present at the index specified in the code

print(a.index(7,6))

print(a.index(8))

5

6

Traceback (most recent call last):

File "<string>", line 7, in <module>

ValueError: 8 is not in list

insert(index, value):

inserts value at the specified index.

a = [10, 20, 30, 40, 50, 60, 70]

print(a)

a.insert(4, 80)

print(a)

[10, 20, 30, 40, 50, 60, 70]

[10, 20, 30, 40, 80, 50, 60, 70]

pop([index])

removes and returns the item at index. With no argument, it removes and returns the last element of the list.

a = [10, 20, 30, 40, 50, 60, 70]

print(a)

a.pop(5)

print(a)

a.pop() # pop the last element when left blank

print(a)

[10, 20, 30, 40, 50, 60, 70]

[10, 20, 30, 40, 50, 70]

[10, 20, 30, 40, 50]

remove(value)

It removes the first occurrence of the specified value. If the provided value cannot be found, a ValueError is raised.

a = [10, 20, 30, 50, 40, 50, 60, 70, 80, 70]

print(a)

a.remove(50)

a.remove(70)

print(a)

[10, 20, 30, 50, 40, 50, 60, 70, 80, 70]

[10, 20, 30, 40, 50, 60, 80, 70]

reverse()

reverses the list from the last index value.

a = [10, 20, 30, 40, 50, 60, 70, 80]

print(a)

a.reverse()

print(a)

[10, 20, 30, 40, 50, 60, 70, 80]

[80, 70, 60, 50, 40, 30, 20, 10]

count(value)

counts the number of occurrences of some value in the list.

a = [10, 20, 30, 40, 50, 50, 60, 70, 50, 80, 50]

print(a)

print(a.count(50))

[10, 20, 30, 40, 50, 50, 60, 70, 50, 80, 50]

4

sort()

sorts the list in numerical and dictionary-making order.

a=[90,30,50,10,20,40,80,70,60]

print(a)

a.sort()

print("Sorted data is:")

print(a)

a.sort(reverse=True)

print("Sorted List in Reverse Order")

print(a)

[90, 30, 50, 10, 20, 40, 80, 70, 60]

Sorted data is:

[10, 20, 30, 40, 50, 60, 70, 80, 90]

Sorted List in Reverse Order

[90, 80, 70, 60, 50, 40, 30, 20, 10]


 

9) Python tuples: A tuple is an immutable list of values. Tuples are one of Python's simplest and most common collection types. Elements in a tuple are separated by a comma.

  • If you are adding a single element in a tuple, it will be considered as a tuple if you add a comma after that otherwise it will become a string.

For Example, 

v1 = ("Study Section",)

print(v1)

print(type(v1))

v2 = ("Study Section")

print(v2)

print(type(v2))

Output: 

('Study Section',)

<class 'tuple'>

Study Section

<class 'str'>

  • You can access elements of a tuple from its index value also.

  • Tuples are not mutable, so no new element cannot be added or deleted from an already existing tuple.

 

a) Python Tuple Operations:

 

 

Method

Description

Example 

Output

concatenation(+)

+ Operator is used to combining two strings.

t1 = (1, 2, 3,4)

t2 = ('a', 'b', 'c', 'd')

t3 = t1 + t2

print(t3)

(1, 2, 3, 4, 'a', 'b', 'c', 'd')

repetition(*)

*operator is used to repeat a tuple to a specified number of times

t1 = (1, 2,3)

t2 = t1 * 2

print(t2)

(1, 2, 3, 1, 2, 3)

Tuple membership test

You can test whether an element is present in the tuple or not by using in or not in.

my_t = (3, 4, "Red", "Yellow")

print(3 in my_t)

print(2 in my_t)

print("Red" not in my_t)

True

False

False


 

Tuple iteration

we can iterate through a tuple also using a for a loop.

fruits = ("Apple", "Grapes", "banana")

for fruit in fruits:

        print(fruit)

Apple

Grapes

banana

len()

To find the length of the tuple.

my_t = (1, 2, 3, 4, 5, 6)

print(len(my_t))

6

max()

Returns an element having maximum length in the tuple.

my_t = (10, 12, 15, 53, 16, 48)

print(max(my_t))

53

min()

Returns an element having a minimum length in the tuple.

my_t = (10, 12, 15, 53, 16, 48)

print(min(my_t))

10

sum()

Returns the sum of all the elements of a tuple.

my_t = (10, 12, 15, 53, 16, 48)

print(sum(my_t))

154

sorted()

Returns a list of sorted elements in a tuple.

my_t = (10, 12, 15, 53, 16, 48)

print(sorted(my_t))

[10, 12, 15, 16, 48, 53]


 

10) Python Dictionary: Dictionary is the most important data structure of Python. a dictionary is a collection of items, where each item is in the form of a key-value pair.

Syntax:

d={‘key’ : ’value’}

For Example,

fruit = {'Orange':40, 'Apple':10, 'Papaya':20}

print(fruit)

Output: 

 

{'Orange': 40, 'Apple': 10, 'Papaya': 20}

  • Another way to create a dictionary:

For Example,

fruit = {}

fruit['Orange'] = 40

fruit['Apple'] = 10

fruit['Papaya'] = 20

print(fruit)

Output:

{'Orange': 40, 'Apple': 10, 'Papaya': 20}

  • Rules for creating dictionary:

i)  Keys must be unique.

ii) Keys are immutable but values can be both mutable and immutable.

 

a) Python Dictionary Operations:

 

Method

Description

Example 

Output

get()

You can access the values of a dictionary either by using the [] or get() function.

fruit = {'Orange':40, 'Apple':10, 'Papaya':20}

print(fruit['Apple'])

print(fruit.get('Papaya'))

10

20

update(): To change values

You can change values either by directly assigning new values or by using the update() function.

fruit = {'Orange':40, 'Apple':10, 'Papaya':20}

print(fruit)

fruit['Orange'] = 50

fruit.update(Apple = 30)  

print(fruit)

{'Orange': 40, 'Apple': 10, 'Papaya': 20}

{'Orange': 50, 'Apple': 30, 'Papaya': 20}


 

update(): To add new keys

You can add keys either by direct addition or by using the update() function.

fruit = {'Orange':40, 'Apple':10, 'Papaya':20}

print(fruit)

fruit['Mango'] = 50

fruit.update(Plum = 30)  

print(fruit)

{'Orange': 40, 'Apple': 10, 'Papaya': 20}

{'Orange': 40, 'Apple': 10, 'Papaya': 20, 'Mango': 50, 'Plum': 30}

del

Del keyword is used to delete a single key or an entire dictionary.

fruit = {'Orange':40, 'Apple':10, 'Papaya':20}

print(fruit)

del fruit['Apple']  

print(fruit)

del fruit

print(fruit)

{'Orange': 40, 'Apple': 10, 'Papaya': 20}

{'Orange': 40, 'Papaya': 20}

Traceback (most recent call last):

  File "<string>", line 8, in <module>

NameError: name 'fruit' is not defined

pop()

Removes an element having the specified key and returns the value of the removed element.

fruit = {'Orange':40, 'Apple':10, 'Papaya':20}

print(fruit)

print(fruit.pop('Apple'))

{'Orange': 40, 'Apple': 10, 'Papaya': 20}

10

popitem()

removes the last element from a dictionary and returns the (key, value) pair of the removed element.

fruit = {'Orange':40, 'Apple':10, 'Papaya':20}

print(fruit)

print(fruit.popitem())

{'Orange': 40, 'Apple': 10, 'Papaya': 20}

('Papaya', 20)

clear()

removes all the elements from a dictionary.

fruit = {'Orange':40, 'Apple':10, 'Papaya':20}

fruit.clear()

print(fruit)

{}

in and not in

You can test whether a key is present in the dictionary or not by using in or not in.


 

fruit = {'Orange':40, 'Apple':10, 'Papaya':20}

print('Apple' in fruit)

print('Mango' in fruit)

print('Papaya' not in fruit)

True

False

False

Looping through keys

We can iterate through the keys of a dictionary using a for loop.

fruit = {'Orange':40, 'Apple':10, 'Papaya':20}

for k in fruit:

   print("key =", k)

   print("value =", fruit[k])

key = Orange

value = 40

key = Apple

value = 10

key = Papaya

value = 20

Looping through values

We can iterate through the values of a dictionary using a values() function. 

fruit = {'Orange':40, 'Apple':10, 'Papaya':20}

for v in fruit.values():

     print("value =", v)

value = 40

value = 10

value = 20

Looping Through Keys and Values

 

We can iterate through the keys and values of a dictionary using a items() function. 

fruit = {'Orange':40, 'Apple':10, 'Papaya':20}

for k,v in fruit.items():

    print("Keys =", k)

    print("value =", v)

Keys = Orange

value = 40

Keys = Apple

value = 10

Keys = Papaya

value = 20

Simple Assignment

You can simply assign a dictionary to a single variable by using assignment operator.

fruit = {'Orange':40, 'Apple':10, 'Papaya':20}

fruit1 = fruit

print(fruit)

print(fruit1)

{'Orange': 40, 'Apple': 10, 'Papaya': 20}

{'Orange': 40, 'Apple': 10, 'Papaya': 20}

copy()

This function creates a shallow copy of a dictionary.

fruit = {'Orange':40, 'Apple':10, 'Papaya':20}

fruit1 = fruit.copy()

fruit1['Mango'] = 30

fruit1['Plum'] = [30,40]

print("Original Fruit List:", fruit)

print("New Fruit List:", fruit1)

Original Fruit List: {'Orange': 40, 'Apple': 10, 'Papaya': 20}

New Fruit List: {'Orange': 40, 'Apple': 10, 'Papaya': 20, 'Mango': 30, 'Plum': [30, 40]}

dict()

Dictionaries can be copied by passing it to the dict() function.

fruit = {'Orange':40, 'Apple':10, 'Papaya':20}

fruit1 = dict(fruit)

fruit1['Mango'] = 30

fruit1['Plum'] = [30,40]

print("Original Fruit List:", fruit)

print("New Fruit List:", fruit1)

Original Fruit List: {'Orange': 40, 'Apple': 10, 'Papaya': 20}

New Fruit List: {'Orange': 40, 'Apple': 10, 'Papaya': 20, 'Mango': 30, 'Plum': [30, 40]}

len()

To find the length of the dictionary.

fruit = {'Orange':40, 'Apple':10, 'Papaya':20}

print(len(fruit))

3

sorted()

To sort the keys.

fruit = {'Orange':40, 'Apple':10, 'Papaya':20}

print(sorted(fruit))

print(sorted(fruit, reverse=True))

['Apple', 'Orange', 'Papaya']

['Papaya', 'Orange', 'Apple']

keys()

It returns the keys of a dictionary.

fruit = {'Orange':40, 'Apple':10, 'Papaya':20}

print(fruit.keys())

dict_keys(['Orange', 'Apple', 'Papaya'])

values()

It returns the values of a dictionary.

fruit = {'Orange':40, 'Apple':10, 'Papaya':20}

print(fruit.values())

dict_values([40, 10, 20])

items()

It returns the key value pair of a dictionary.

fruit = {'Orange':40, 'Apple':10, 'Papaya':20}

print(fruit.items())

dict_items([('Orange', 40), ('Apple', 10), ('Papaya', 20)])

Dictionary Comprehension

Dictionary comprehension makes creating dictionaries easier and more readable.

cube_root = {}

 

for num in range(1, 11):

    cube_root[num] = num**3

 

print(cube_root)

{1: 1, 2: 8, 3: 27, 4: 64, 5: 125, 6: 216, 7: 343, 8: 512, 9: 729, 10: 1000}

Conditional if with dictionary comprehension

Syntax: new_dictionary = {key: value for_loop if condition}

fruit = {'Orange':40, 'Apple':10, 'Papaya':20}

new_fruit = {}

 

for i, price in fruit.items():

    if price > 15:

        new_fruit[i] = price * 2

print(new_fruit)

{'Orange': 80, 'Papaya': 40}

 

11) Python Sets: Just like other data types, a set is also a collection of items, but the difference is that other data elements contain duplicate values but a set cannot store duplicate data. A set can have data of a similar type or of different types. 

For Example,

myset = {1, 2, 3, "Hello"}

print(myset)

Output: 

{1, 2, 3, "Hello"}

Properties of Python sets are:

  • Each element in a set is unique.

  • Elements in a set are unordered. Every time you set its order gets changed.

  • Elements of a set are immutable.

  • Sets are mutable. That means you can add or delete elements from a set but you cannot change an element from its index value.

 

a) Python Set Operations:

 

Method

Description

Example 

Output

add()

Add elements to the set.

my_set = {1, 2, 3}

my_set.add(4)

my_set.add(5)

print(my_set)

{1, 2, 3, 4, 5}

update()

The update() function takes lists, strings, tuples, and other sets as an argument and adds the elements in the passed arguments to the set.

my_set = {1, 2, 3}

my_set.update([5, 6],(7,8))

print(my_set)

{1, 2, 3, 5, 6, 7, 8}


 

discard()

To remove a particular element from a set.It does not show an error if an element is not present in the list.

my_set = {1, 2, 3,4,5,6}

my_set.discard(5)

print(my_set)

{1, 2, 3, 4, 6}

remove()

To remove a particular element from a set. It shows an error if the element is not present in the list.

my_set = {1, 2, 3,4,5,6}

my_set.remove(5)

print(my_set)

{1, 2, 3, 4, 6}

pop()

It selects the random element and removes it from the set.

my_set = {1, 2, 3, 4, 5, 6, 7}

my_set.pop()

print(my_set)

{2, 3, 4, 5, 6, 7}

clear()

Removes all the elements from the set.

my_set = {90, 20, 10, 40, 50, 60, 70}

my_set.clear()

print(my_set)

set()

in and not in

You can test either an element is present in the set or not by using in or not in.

s1 = {10, 22, 23, 44, 56, 67}

print(22 in s1)

print(46 in s1)

print(84 not in s1)

True

False

True

Iteration through sets

We can iterate through a set using a for loop.

s1 = {10, 22, 23, 44, 56, 67}

for i in s1:

    print(i)

67

10

44

22

23

56

Simple Assignment

You can simply assign a set to a single variable by using the assignment operator.

s1 = {10, 22, 23, 44, 56, 67}

s2=s1

print(s2)

{67, 10, 44, 22, 23, 56}

copy()

used to create a shallow copy of a set.

s1 = {10, 22, 23, 44, 56, 67}

s2=s1.copy()

s2.add(60)

print("Original set:", s1)

print("New set:", s2)

Original set: {67, 10, 44, 22, 23, 56}

New set: {67, 22, 23, 56, 10, 44, 60}

set()

A set can be copied by passing it to the set() function.

s1 = {10, 22, 23, 44, 56, 67}

s2=set(s1)

s2.add(60)

print("Original set:", s1)

print("New set:", s2

Original set: {67, 10, 44, 22, 23, 56}

New set: {67, 22, 23, 56, 10, 44, 60}

len()

To find the length of the set.

s1 = {10, 22, 23, 44, 56, 67}

print(len(s1))

6

max()

Returns an element having a maximum length in the set.

s1 = {10, 22, 23, 44, 56, 67}

print(max(s1))

67

min()

Returns an element having a minimum length in the set.

s1 = {10, 22, 23, 44, 56, 67}

print(min(s1))

10

sum()

Returns the sum of all the elements of a set.

s1 = {10, 22, 23, 44, 56, 67}

print(sum(s1))

222

sorted()

Returns a list of sorted elements in a set.

s1 = {10, 22, 23, 44, 56, 67}

print(sorted(s1))

print(sorted(s1,reverse=True))

s1 = {10, 22, 23, 44, 56, 67}

print(sorted(s1))

print(sorted(s1,reverse=True))

 

b) Python set operations: Some basic mathematical set operations like union, intersection, difference, and symmetric difference can also be implemented in Python. It requires two sets s1 and s2.

 

Method

Description

Example 

Output

Union(|)

It creates a new set that contains all the elements of both sets (s1 and s2).

s1 = {10, 22, 23, 44, 56, 67}

s2 = {44, 22, 67, 17, 28}

print(s1 | s2)

{67, 10, 44, 17, 22, 23, 56, 28}

Intersection(&)

It creates a new set that contains the common elements of both sets (s1 and s2).

s1 = {10, 22, 23, 44, 56, 67}

s2 = {44, 22, 67, 17, 28}

print(s1 & s2)

{67, 44, 22}

difference() or -

It displays all the elements of s1 which are not displayed in s2 and vice versa.

s1 = {10, 22, 23, 44, 56, 67}

s2 = {44, 22, 67, 17, 28}

print(s1-s2)

print(s2-s1)

s1 = {15, 24, 25, 44, 58, 78}

s2 = {34, 24, 57, 44, 78}

print(s1.difference(s2))

print(s2.difference(s1))

{56, 10, 23}

{17, 28}

{25, 58, 15}

{57, 34}

symmetric_difference() or ^

Symmetric Difference of sets s1 and s2 is a new set having the elements in s1 and s2 but not the common elements in both.

s1 = {10, 22, 23, 44, 56, 67}

s2 = {44, 22, 67, 17, 28}

print(s1^s2)

print(s1.symmetric_difference(s2))

{17, 23, 56, 10, 28}

{17, 23, 56, 10, 28}

isdisjoint()

If two sets don’t have any common element, it returns true otherwise false.

s1 = {10, 22, 23, 44, 56, 67}

s2 = {44, 22, 67, 17, 28}

print(s1.isdisjoint(s2))

print(s2.isdisjoint(s1)

False

False

intersection_update()

It calculates the intersection of two or more sets and assigns the result to the set which calls the function.

s1 = {10, 20, 30, 40, 50, 60}

s2 = {40, 50, 60, 70, 80}

s3 = {20, 50, 60, 80}

result = s1.intersection_update(s2, s3)

print('updated results are:', result)

print('set1:', s1)

print('set2:', s2)

print('set3:', s3)

updated results are: None

set1: {50, 60}

set2: {70, 40, 80, 50, 60}

set3: {80, 50, 20, 60}

difference_update()

It computes the difference of one set from another set and assigns the result to the set which calls the function.

s1 = {10, 20, 30, 40, 50, 60}

s2 = {40, 50, 60, 70, 80}

s1.difference_update(s2)

print('set1:', s1)

print('set2:', s2)

set1: {10, 20, 30}

set2: {70, 40, 80, 50, 60}

symmetric_difference_update()

It computes the symmetric difference of one set from another set and assigns the result to the set which calls the function.

s1 = {10, 20, 30, 40, 50, 60}

s2 = {40, 50, 60, 70, 80}

s1.symmetric_difference_update(s2)

print('set1:', s1)

print('set2:', s2)

set1: {70, 10, 80, 20, 30}

set2: {70, 40, 80, 50, 60}


 

issubset()

It returns True if a set is a subset of another set, otherwise, it returns False. A set set1 is a subset of set set2 if all the elements of a set1 are present in set2.

s1 = {40, 50, 60}

s2 = {40, 50, 60, 70, 80}

print(s1.issubset(s2))  

print(s2.issubset(s1))

True

False

issuperset()

It returns True if a set is a superset of another set, otherwise, it returns False. A set set1 is a superset of set set2 if set1 has all the elements of set2.

s1 = {40, 50, 60}

s2 = {40, 50, 60, 70, 80}

print(s1.issuperset(s2))  

print(s2.issuperset(s1))

False 

True

frozenset()

Converts a sequence (list, string, tuple) or a collection(dictionary, set) into a frozenset. Functions like update(), add() or remove cannot be used with fozenset.

frozen1 = frozenset([1, 2, 3,4])  

frozen2 = frozenset("Study Section") 

frozen3 = frozenset((5, 6, 7, 7, 8))

print(frozen1)

print(frozen2)

print(frozen3)

frozenset({1, 2, 3, 4})

frozenset({'u', 'n', ' ', 'y', 'c', 'o', 'd', 'i', 'S', 'e', 't'})

frozenset({8, 5, 6, 7})


 

 

12) Python Functions: Python is a set of statements, these statements under a common name provide you modular, non-redundant, reusable, and organized code. This code can be called any number of times without rewriting it again and again. 

  • Python has a number of in-built functions but you can also create your functions by giving them any names. These functions are called user-defined functions. 

  • def statement is used to create a function. This statement is called a single clause compound statement with the following syntax:

def function_name(parameters):

statement(s)

Parameters are optional, but when you pass parameters then in the function call, arguments should be passed equally to the number of parameters. Function call syntax:

function_name(arguments)

 

Function with parameters

def sum(x,y):

      print("Sum of two numbers is:", x+y)

sum(10,20)

Sum of two numbers is: 30

Function without parameters

def sum():

       x=int(input("Enter value of x:"))

       y=int(input("Enter value of y:"))

       print("Sum of two numbers is:", x+y)

sum()

Enter value of x:12

Enter value of y:12

Sum of two numbers is: 24

 

a) Python return statement: Functions can return something to us. Whenever an interpreter runs a return statement, it terminates the function and returns a value to the call statement.

For Example,

def is_big(x,y):

     if x>y:

         return x

     else:

         return y

print(is_big(10,20))

Output:

20

b) Nesting of functions: A function can be declared inside another function

For Example,

def sum(x,y):

     print("Value of x is",x)

     print("Value of y is", y)

    def sum_three_numbers(z):

        print("Value of z is",z)

         print("Sum is",x+y+z)

     sum_three_numbers(30)

sum(10,20)

Output:

Value of x is 10

Value of y is 20

Value of z is 30

Sum is 60

 

c) Defining a function capable of taking an arbitrary number of arguments can be done by prefixing one of the arguments with a *.

For Example,

def sum(*args):

     s=0

     for n in args:

         s=s+n;

     print("sum of n numbers is:", s)

sum(10,20,30,40)

Output:

sum of n numbers is: 100

 

d) Recursion: Recursion is calling a function inside the same function.

For Example, The factorial of any number can be determined by using recursion.

def factorial(n):

     if n == 0:

         return 1

     else:

         return n * factorial(n - 1)

n=int(input("Enter a number to find factorial : "))

print(factorial(n))

Output:

Enter a number to find factorial : 5

120

 

e) Local and global variables: Local variables are those variables whose scope is limited within the function only. Global variables scope is not limited within a function, its scope is universal within the complete code.

For Example,

z=int(input("Enter the value of z:")) # z is a global variable

def sum():

     x=int(input("Enter the value of x:")) # here, x and y are local variables

     y=int(input("Enter the value of y:"))

     print("Sum of three numbers is",x+y+z)

sum()

Output:

Enter the value of z:12

Enter the value of x:12

Enter the value of y:12

Sum of three numbers is 36

 

f) map() function: Mapping consists of applying a transformation function to an iterable to produce a new iterable. Items in the new iterable are produced by calling the transformation function on each item in the original iterable.

Syntax:

map(function,iterable[i1,i2,i3…...in])

The first argument is the transformation function.

This function can be the substitute for a loop. The below Example can show it.

 

Using for loop

Using map() function

def square():

    numbers = [1, 2, 3, 4, 5]

    for i in range(len(numbers)):

        numbers[i]=numbers[i] ** 2

    print(numbers)

square()

def square(num):

    return num**2

numbers = [1,2,3,4,5]

result = map(square, numbers)

print(list(result))


 

Output: [1, 4, 9, 16, 25]


 

13) classes and objects: A class is a blueprint for creating objects. Objects are the instances of a class consisting of data members and methods that define their behavior. In python, a class is created by the keyword class.

For Example,

class Rectangle():

    def area(self,length,breadth):

        return length*breadth

r=Rectangle()

print("Area of Rectangle is",r.area(10,20))

Output:

Area of Rectangle is 200

 

Use of 'self' keyword: 

  • It is passed automatically when the function is declared inside the class as the first parameter when you call a method on an instance.

  • It is used if we want to access an instance variable from the instance method, from inside that method.

 

a) Instance attributes and the init method: constructor is a special method of a class that gets called automatically when an object of that class is created. In Python, the __init__() method is called the constructor. A constructor is used to initialize variables when an object of that class is created.

For Example,

class rectangle():

     def __init__(self,breadth,length):

         self.breadth=breadth

         self.length=length

     def area(self):

        return self.breadth*self.length

a=int(input("Enter length of rectangle: "))

b=int(input("Enter breadth of rectangle: "))

obj=rectangle(a,b)

print("Area of rectangle:",obj.area())

  print()

Output:

Enter length of rectangle: 12

Enter breadth of rectangle: 10

Area of rectangle: 120

 

b) Shallow Copy vs Deep Copy: When we use = to create a copy of an object, it creates a new variable but the new object. , in that case, if we make any changes in the original variable those changes reflect in the new variable also. Sometimes you may want to change the values of the original variable and don’t want those changes to reflect in the new variable or vice versa. In that case, the concept of shallow copy and a deep copy is used.

For Example,

class Car:

  def __init__(self, name, colors):

           self.name = name

      self.colors = colors

      honda = Car("Honda", ["Red", "Blue"])

  # Deep Copy of Honda

deepcopy_honda = deepcopy(honda)

deepcopy_honda.colors.append("Green")

print(deepcopy_honda.colors, \

       honda.colors)

 

# Shallow Copy of Honda

copy_honda = copy(honda)

 

copy_honda.colors.append("Green")

print(copy_honda.colors, \

      honda.colors)

Output: 

['Red', 'Blue', 'Green'] ['Red', 'Blue']

['Red', 'Blue', 'Green'] ['Red', 'Blue', 'Green']

 

c) Python Operator Overloading: 

 

Operator

Expression

FUNCTION

Math Operator Overloading

Addition(+)

p1 + p2

p1.__add__(p2)

Subtraction(-)

p1 - p2

p1.__sub__(p2)

Multiplication(*)

p1 * p2

p1.__mul__(p2)

Power(**)

p1 ** p2

p1.__pow__(p2)

Division(/)

p1 / p2

p1.__truediv__(p2)

Floor Division(//)

p1 // p2

p1.__floordiv__(p2)

Remainder (modulo)(%)

p1 % p2

p1.__mod__(p2)

Bitwise Operator Overloading

Bitwise Left Shift(<<)

p1 << p2

p1.__lshift__(p2)

Bitwise Right Shift(>>)

p1 >> p2

p1.__rshift__(p2)

Bitwise AND(&)

p1 & p2

p1.__and__(p2)

Bitwise OR(|)

p1 | p2

p1.__or__(p2)

Bitwise XOR(^)

p1 ^ p2

p1.__xor__(p2)(+)

Bitwise NOT(~)

~p1

p1.__invert__()

Comparison Operator Overloading

Less than

p1 < p2

p1.__lt__(p2)

Less than or equal to

p1 <= p2

p1.__le__(p2)

Equal to

p1 == p2

p1.__eq__(p2)

Not equal to

p1 != p2

p1.__ne__(p2)

Greater than

p1 > p2

p1.__gt__(p2)

Greater than or equal to

p1 >= p2

p1.__ge__(p2)

 

For Example,

class Complex:

    # defining init method for class

     def __init__(self, r, i):

         self.real = r

         self.img = i

   # overloading the add operator using special function

     def __add__(self, sec):

         r = self.real + sec.real

         i = self.img + sec.img

         return complex(r,i)

     # string function to print object of Complex class

     def __str__(self):

         return str(self.real)+' + '+str(self.img)+'i'

c1 = Complex(5,3)

c2 = Complex(2,4)

print("Sum of two complex numbers is = ",c1+c2)

 

Output:

Sum of two complex numbers is =  (7+7j)

 

14) Inheritance: Inheritance is defined as the capability to inherit one class from another class and use it whenever needed. Inheritance provides the following properties: 

  • It describes real-world relationships well. 

  • It provides the reusability of code. We don’t have to write the same code again and again. Also, it allows us to add more features to a class without modifying it. 

  • It is transitive in nature, which means that if class B inherits from another class A, then all the subclasses of B would automatically inherit from class A. 

 

a) Types of Inheritance: 

  • Single Inheritance

  • Multiple Inheritance

  • Multilevel Inheritance

  • Hierarchical Inheritance

  • Hybrid Inheritance


 

Single Inheritance

class Rectangle:

#Constructor

def __init__(self, length, breadth):

self.l = length

self.b = breadth

 

class Dimensions(Rectangle):

#method

def get_dimensions(self):

print("Length and Breadth of a Rectangle is:",self.l,self.b)

 

r1 = Dimensions(10, 20)

r1.get_dimensions()

Multiple Inheritance

class Dim_Length:

#Constructor

def __init__(self, length):

self.l = length

class Dim_Breadth:

#Constructor

def __init__(self, breadth):

self.b = breadth

class Dimensions(Dim_Length,Dim_Breadth):

    def __init__(self,length, breadth):

        Dim_Length.__init__(self,length)

        Dim_Breadth.__init__(self,breadth)

    def get_dimensions(self):

    print("Length and Breadth of a Rectangle is:",self.l,self.b)

 

r1 = Dimensions(10,20)

r1.get_dimensions()

Multilevel Inheritance

class Dim_Length:

#Constructor

def __init__(self, length):

self.l = length

class Dim_Breadth(Dim_Length):

#Constructor

def __init__(self, breadth,length):

self.b = breadth

Dim_Length.__init__(self,length)

class Dimensions(Dim_Breadth):

    def __init__(self,length, breadth):

        Dim_Breadth.__init__(self,breadth,length)

        

    def get_dimensions(self):

    print("Length and Breadth of a Rectangle is:",self.l,self.b)

 

r1 = Dimensions(10,20)

r1.get_dimensions()

Hierarchical Inheritance

class Parent:

def func1(self):

print("This is the base class")

 

class Child1(Parent):

def func2(self):

print("This is the child1 class")

 

class Child2(Parent):

def func3(self):

print("This is child2 class")

 

 

c1 = Child2()

c1.func3()

c1.func1()

 

print("---------")

c1 = Child1()

c1.func2()

c1.func1()

Hybrid Inheritance

 

class Parent:

def func1(self):

print("This is the base class")

 

class Child1(Parent):

def func2(self):

print("This is the child1 class")

 

class Child2(Parent):

def func3(self):

print("This is child2 class")

 

 

class Child3(Child1, Child2):

def func4(self):

print("This is child4 class")

 

 

class Child4(Child1):

def func5(self):

print("This is child5 class")

 

 

 

c1 = Child2()

c1.func3()

c1.func1()

 

print("---------")

c2 = Child1()

c2.func2()

c2.func1()

 

print("------")

 

c3 = Child3()

c3.func4()

c3.func1()

c3.func3()

 

print("------")

c4 = Child4()

c4.func5()

c4.func2()

 

 

15) Encapsulation: When you deal with sensitive data it is not a good choice to give access to all the variables used in a program. Encapsulation provides controlled access to data with security. If you want to make any kind of changes like updating, modification or deletion do it with the help of methods. Unlike the other languages, it does not support access specifiers (public, private, and protected). Python provides access to all the variables and methods globally.

The following Example will show how the variables can be accessed easily.

class Student:

     def __init__(self, name, roll=0):

         self.name = name

         self.roll = roll

      def display(self):

         print(self.name)

         print(self.roll)

  std = Student('Jack', 30)

#accessing using class method

std.display()

#accessing directly from outside

print(std.name)

print(std.roll)

Multiple methods are offered by Python to limit variable and method access across the program.

a) Using single underscore: It involves prefixing a variable or method with a single underscore. It does not make any sense really, you can access them as it is. One advantage is that you can tell other programmers to access variables or methods within the scope of the class only.

b) using double underscore: If you want to make class members i.e. methods and variables private, then you should prefix them with double underscores. But Python offers some sort of support to the private modifier. This mechanism is called Name mangling. With this, it is still possible to access the class members from outside it.

For Example,

 

Using Single Underscore

Using Double Underscore

class Student:

    def __init__(self, name, roll=0):

        self.name = name

        self._roll = roll

    def display(self):

        print(self.name)

        print(self._roll)

std = Student('Jack', 30)

#accessing using class method

std.display()

#accessing directly from outside

print(std.name)

print(std._roll)

Output:

Jack

30

Jack

30

class Student:

    def __init__(self, name, roll=0):

        self.name = name

        self.__roll = roll

    def display(self):

        print(self.name)

        print(self.__roll)

std = Student('Jack', 30)

#accessing using class method

std.display()

#accessing directly from outside

print(std.name)

print(std.__roll)

Output:

Jack

30

Jack

Traceback (most recent call last):

  File "<string>", line 13, in <module>

AttributeError: 'Student' object has no attribute '__roll'

 

c) Using getter and setter methods to access variables: If you want to access and change the private variables, accessor (getter) methods and mutators(setter methods) should be used, as they are part of Class.

For Example, 

class Student:

     def __init__(self, name, roll=0):

         self.name = name

         self.__roll = roll

      def display(self):

         print(self.name)

         print(self.__roll)

      def getRoll(self):

         print(self.__roll)

      def setRoll(self, roll):

        self.__roll = roll

  std = Student('Jack', 30)

#accessing using class method

std.display()

#changing Roll Number using setter

std.setRoll(35)

std.getRoll()

Output: 

Jack

30

35

 

16) Polymorphism: Polymorphism is taken from the Greek words Poly (many) and morphism (forms). It means that the same function name can be used for different types. Following are the examples of Polymorphism in Python:

  • The codes and classes written once can be reused and implemented multiple times.

  • It helps in reducing the coupling between different functionalities and the behavior of objects.

There are different methods to use polymorphism in Python. You can use different functions, class methods, or objects to define polymorphism.

a) Polymorphism with class methods: In this case, you have to use for loop that iterates through a tuple of objects. Next, you have to call the methods without being concerned about which class type each object is. We assume that these methods exist in each class.

For Example,

class Student_Girl:

     def __init__(self, name, roll):

         self.name = name

         self.roll = roll

def info(self):

         print(f"I am a girl. My name is {self.name}. My Roll Number is {self.roll}")

     def std(self):

         print("I study in 7th standard")

class Student_Boy:

     def __init__(self, name, roll):

         self.name = name

         self.roll = roll

     def info(self):

         print(f"I am a boy. My name is {self.name}. My Roll Number is {self.roll}")

     def std(self):

         print("I study in 9th standard")

girl1 = Student_Girl("Jack", 13)

boy1 = Student_Boy("Lily", 24)

for student in (girl1, boy1):

     student.info()

     student.std()

 

b) Polymorphism with functions and objects: In this case, you can create a function that can take any number of objects to perform polymorphism functionality.

For Example, 

class Student_Girl:

     def __init__(self, name, roll):

         self.name = name

         self.roll = roll

     def info(self):

         print(f"I am a girl. My name is {self.name}. My Roll Number is {self.roll}")

     def std(self):

         print("I study in 7th standard")

class Student_Boy:

     def __init__(self, name, roll):

         self.name = name

         self.roll = roll

     def info(self):

         print(f"I am a boy. My name is {self.name}. My Roll Number is {self.roll}")

     def std(self):

         print("I study in 9th standard")

def func(obj): 

        obj.info() 

       obj.std()

obj_girl = Student_Girl("Lily",10) 

obj_boy = Student_Boy("Jack", 14) 

func(obj_girl) 

func(obj_boy)

 

c) Polymorphism with Inheritance: In inheritance, the child class inherits the methods from the parent class. Also, it is possible to modify a method in a child class that it has inherited from the parent class.

For Example,

class Student:

     def __init__(self, name, roll):

         self.name = name

         self.roll = roll

class Student_Girl(Student):

     def info(self):

         print(f"I am a girl. My name is {self.name}. My Roll Number is {self.roll}")

     def std(self):

         print("I study in 7th standard")

class Student_Boy(Student):

     def info(self):

         print(f"I am a boy. My name is {self.name}. My Roll Number is {self.roll}")

     def std(self):

         print("I study in 9th standard")

def func(obj): 

     obj.info() 

     obj.std()

obj_girl = Student_Girl("Lily",10) 

obj_boy = Student_Boy("Jack", 14) 

func(obj_girl) 

func(obj_boy)

 

16) Files in Python: Python’s “with open(…) as …” Pattern

Reading and writing data to files using Python is pretty straightforward. To do this, you must first open files in the appropriate mode. Here’s an example of how to use Python’s “with open(…) as …” pattern to open a text file and read its contents:

with open('data.txt', 'r') as f:

    data = f.read()

open() takes a filename and a mode as its arguments. r opens the file in read-only mode. To write data to a file, pass in w as an argument instead:

 

with open('data.txt', 'w') as f:

    data = 'some data to be written to the file'

    f.write(data)

 

a) File Modes in Python: Following are the various File Modes in Python:

 

Mode

Description

'r'

This is the default mode. It opens a file for reading

'w'

This Mode Opens a file for writing.                     If a file does not exist, it creates a new file.

If a file exists it truncates the file

'x'

Creates a new file. If a file already exists, the operation fails.

'a'

Open file in append mode.

If a file does not exist, it creates a new file.

't'

This is the default mode. It opens in text mode.

'b'

This opens in binary mode.

'+'

This will open a file for reading and writing (updating)

 

This website uses cookies to improve user experience. By using our website you consent to all cookies in accordance with our Cookie Policy. More info. I Agree