Python Programming

History and Features

Python is developed by Guido Van Rossam in 1991.  The name python is taken by a fun show of Netherlands called “The Complete Monty Python’s Flying Circus” popularly broadcast from BBC around 1969 to 1974, which the favourite show of Guido Van Rossam.  Python programming language can be said All Rounder since it has the features of functional programming like C, object oriented programming like C++, scripting programming like Perl, modular programming like Modula.  But most of the features of python are taken from C and ABC language.  Python is actually developed prior to java but due lack of demand of big data like other issues it was not became popular. 

 

Features of Python Language:

  1. Simple and easy to learn
  2. Less lines of code
  3. Freeware and Open Source
  4. High level programming Language
  5. Platform Independent
  6. Dynamically Typed
  7. Both procedure and Object Oriented
  8. Interpreted Language
  9. Extensible (Other languages code can be embedded into python code)
  10. Embedded (Python program can be embedded in other languages)
  11. For machine learning and data science python is best choice

 

Limitations:

  1. Interpreters are always slower in performance when compared with compilers
  2. Cannot be used for Mobile applications
  3. Not suitable for enterprise applications

 

Application of Python: 

being a general purpose programming language python can be used to develop:

  • Desktop applications
  • Web applications
  • Network applications
  • Games
  • Data analysis applications
  • Machine learning
  • Artificial intelligence
  • IOT (internet of Things)

And many more….

 

Flavours of Python:

  1. CPython : standard version
  2. Jython or JPython
  3. IronPython: .NET Micrsoft technology
  4. Pypy: JIT (Python for Speed)
  5. RubyPython
  6. AncondaPython : to handle big data

 

Versions of Python:

3 basic versions

Python 1.0 introduced in Jan 1994

Python 2.0 introduced in October 2000

Python 3.0 introduced in Dec 2008

 

Python-3 not support Python-2

And Python -2 also not support Python -3

Since they are developed for different purposes

 

There will be no support for Python-2 after year 2020.  So, it is recommended to concentrate on Python-3.

DOWNLOAD & INSTALLATION

The latest version of Python can be freely downloaded from www.python.org which maintained by PSF (Python Software Foundation).

After installation, the default Shell version and Editor versions are available through Python IDLE (Integrated Development and Learning Environment) which is Free IDE.  But based on the developer’s purpose, convenient and taste there are different IDE’s available in the internet as we know IDE is a software that facilitates all the requirements of Program Development in a single environment.  An IDE enables autocompletion and Auto Suggestion of Code, program elements displaying in different colors for easy identification, using copy and paste we can easily insert the repeating code and using find & replace we can easily navigate through the code and many others.

Different IDEs

  1. PyCharm: PayCharm is a cross-platform IDE used for Python programming. This editor can be used on Windows, macOS, and Linux. This software contains API that can be used by the developers to write their own Python plugins so that they can extend the basic functionalities.
  2. Spyder: This software is designed for and by scientists who can integrate with Matplotlib, SciPy, NumPy, Pandas, Cython, IPython, SymPy, and other open-source software. Spyder is available through Anaconda (open-source distribution system) distribution on Windows, macOS, and Linux.
  3. Sublime Text3: Sublime Text 3 is a code editor which supports many languages including Python. It has basic built-in support for Python. Customization of Sublime Text 3 is available for creating create a full-fledged Python programming environment. The editor supports OS X, Windows, and Linux operating systems.
  4. Visual Studio Code: Visual Studio Code (VS Code) is an open-source environment developed by Microsoft. This IDE can be used for Python development. Visual Studio Code is based on Electron which is a framework to deploy Node JS applications for the computer running on the Blink browser engine.
  5. Atom: Atom is a useful code editor tool preferred by programmers due to its simple interface compared to the other editors.
  6. Jupyter: Jupyter is a tool for people who have just started with data science. It is easy to use, interactive data science IDE across many programming languages that just not work as an editor, but also as an educational tool or presentation.
  7. PyDev: PyDev is a third-party Python editor for Eclipse. This editor can be used in not only Python but IronPython and Jython development.
  8. Thonny: Thonny is an IDE for learning and teaching programming, specially designed with the beginner Pythonista scripting environment. It is developed at The University of Tartu, which you can download for free on the Bitbucket repository for Windows, Linux, and Mac.
  9. Wing: Wing is a lightweight Python environment which is designed to give you productive development experience.
  10. ActivePython: ActivePython is software consisting of the Python implementation CPython and a set of various extensions to facilitate installation.

Default IDE

Since python is interpreted language, the code lines can be directly entered in the shell environment of Python and check the output.  But the Shell environment cannot store instructions is not possible.  Hence, if you want to store the python code as a source code file and edit and re-execute it whenever you want you need a text editor environment. 

As we learnt, the default shell as well as text editor available in the form of IDLE with python installation which can be used for your program.  But developers usually select an IDE according to their project and many other factors.  Some of the IDEs are suitable for beginners while some are suitable for senior developers.

Keywords or Reserved Words

Keywords are pre-meaningful words for any programming language that cannot be used for any other purpose but only for which they were reserved.  There are 30 keywords in Python language that are to be entered in lower case only in your code.

 

and

exec

not

assert

finally

or

break

for

pass

class

from

print

continue

global

raise

def

if

return

del

import

try

elif

in

while

else

is

with

except

lambda

yield

Identifiers

Identifier is a name of a program element assigned by the developer.  In other words, we can say identifiers are the keywords defined user while keywords are the identifiers defined by the language.  Program element can be a variable, array, function, module or object etc.  The developer should keep in mind the following conditions while assigning an identifier to his program elements.  

  • Keywords should not be used as identifiers.
  • The first letter of identifier must start with a letter (A-Z or a-z) or Underscore(_) but second letter onwards there can be letters and numbers.
  • Any symbols(*,&,% etc) and punctuation marks(space, comma etc) are not allowed in identifier.
  • Python is a case sensitive programming language. The identifier ‘A’ is different than ‘a’
  • Class names must start with an uppercase letter.
  • Starting an identifier with a single leading underscore indicates that the identifier is private.
  • Starting an identifier with two leading underscores indicates a strongly private identifier.
  • If the identifier also ends with two trailing underscores, the identifier is a language-defined special name.

Block or Compound Statement is now ‘Suite’

There are no curly braces({ }) usage in python like in C, C++ and java.  The opening and closing curly braces are used to group a logically connected group of statements in those languages.  The group of statements enclosed between two curly braces are known as block, code block or compound statement which are specifying the body of a loop statement or a function.

Python calls the code block as a suite that can be understood by a colon (:) which indicating the beginning of a suite.  After that we have to use indentation to specify all the statements of the suit.  The indentation is a space maintained from left hand side.  The code lines with same amount of indent would be treated as a single block.

Example:

if (a>b) :

               print “a is big”   #indentation from left hand side

else :

               print “b is big”

Splitting a code line

It is possible to enter a single code line into multiple lines but adding \ at the end of the line.  The popular termination character of C/C++/java that is semicolon (;) is not mandatory in python.  But semicolon must be presented when you want to enter more than one executable statement in a  single line.

 

Example:

print (“The statement that \

can be entered in \

multiple lines”)

print (“I am”); print(“looking”); print (“as single statement”)

String literals

Python accepts single (‘), double (“) and triple (”’ or “””) quotes to denote string literals, as long as the same type of quote starts and ends the string.  The triple quotes also allow you to span the string across multiple lines.

 

Example:

FirstName=’Abc’

LastName=”Def”

Address=”””D.No.123,Unknown Street, Unknown City,

Planet Earth”””

print (FirstName,LastName)

print (Address)

Comments

Comments are useful for the developer to provide description for the coding so that it can be easily understood in future.  Comments are only useful or visible for the developer only.  In Python, there are two types of comment styles.

#(hash) for single line comment line style

‘’’(triple single quotes) or “”” (triple double quotes) for multi-line comment line style

DATA TYPES

Data type is a keyword that is used to specify the kind of data that a data element is holding.  The datatype is also useful in many other places like functions, Class declarations etc.

Python has the following data types built-in by default:

str, int, float, complex, list, tuple, dict, set

You can get the data type of any object by using the type() function

 

Example:

x = 5

print(type(x))

Variables

A variable is a data element that is referring a memory location with an identifier.  Since the value at the memory location referring by that data element, can be changed during program execution it is called as variable.  Unlike other programming languages, Python has no command for declaring a variable.  A variable is created the moment you first assign a value to it.

Example:

x = 5

y = “John”

print(x)

print(y)

No Declaration

Variables do not need to be declared with any particular type and can even change type after they have been set.

Example:

x = 4 # x is of type int

x = “Sally” # x is now of type str

print(x)

String Variables

String variables can be declared either by using single or double quotes.

Example:

x = “John”

# is the same as

x = ‘John’

Assigning Values to multiple variables

you can assign the same value to multiple variables in one line

Example:

x = y = z = “Orange”

print(x)

print(y)

print(z)

Assign different values to different variables

x, y, z = “Orange”, “Banana”, “Cherry”

print(x)

print(y)

print(z)

The print statement

The print statement is used to print some string or value of a variable or a result of the expression to the console. 

Example:

print (“hello, World”)

 

you can print more than one value using single print statement by separating its arguments with a comma or ‘+’

print(“Python is ” + x)

 

Eg2:

x = “Python is “

y = “awesome”

z =  x + y

print(z)

 

Eg3:

x = 5

y = 10

print(x + y)

 

Eg4:

x = 5

y = “John”

print(x + y)          #it will gives you error.

OPERATORS

Operators are the constructs which can manipulate the value of operands.  Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands and + is called operator.

 

Python language supports the following types of operators.

  • Arithmetic Operators
  • Comparison (Relational) Operators
  • Assignment Operators
  • Logical Operators
  • Bitwise Operators

Python Arithmetic Operators

Assume variable a holds 10 and variable b holds 20, then –

 

Operator

Description

Example

+ Addition

Adds values on either side of the operator.

a + b = 30

– Subtraction

Subtracts right hand operand from left hand operand.

a – b = -10

* Multiplication

Multiplies values on either side of the operator

a * b = 200

/ Division

Divides left hand operand by right hand operand

b / a = 2

% Modulus

Divides left hand operand by right hand operand and returns remainder

b % a = 0

** Exponent

Performs exponential (power) calculation on operators

a**b =10 to the power 20

//

Floor Division – The division of operands where the result is the quotient in which the digits after the decimal point are removed. But if one of the operands is negative, the result is floored, i.e., rounded away from zero (towards negative infinity) −

9//2 = 4 and 9.0//2.0 = 4.0, -11//3 = -4, -1

Python Comparison Operators

These operators compare the values on either side of them and decide the relation among them. They are also called Relational operators.

 

Assume variable a holds 10 and variable b holds 20, then –

 

Operator

Description

Example

==

If the values of two operands are equal, then the condition becomes true.

(a == b) is not true.

!=

If values of two operands are not equal, then condition becomes true.

(a != b) is true.

<> 

If values of two operands are not equal, then condition becomes true.

(a <> b) is true. This is similar to != operator.

If the value of left operand is greater than the value of right operand, then condition becomes true.

(a > b) is not true.

If the value of left operand is less than the value of right operand, then condition becomes true.

(a < b) is true.

>=

If the value of left operand is greater than or equal to the value of right operand, then condition becomes true.

(a >= b) is not true.

<=

If the value of left operand is less than or equal to the value of right operand, then condition becomes true.

(a <= b) is true.

Python Assignment Operators

Assume variable a holds 10 and variable b holds 20, then –

Operator

Description

Example

=

Assigns values from right side operands to left side operand

c = a + b assigns value of a + b into c

+= Add AND

It adds right operand to the left operand and assign the result to left operand

c += a is equivalent to c = c + a

-= Subtract AND

It subtracts right operand from the left operand and assign the result to left operand

c -= a is equivalent to c = c – a

*= Multiply AND

It multiplies right operand with the left operand and assign the result to left operand

c *= a is equivalent to c = c * a

/= Divide AND

It divides left operand with the right operand and assign the result to left operand

c /= a is equivalent to c = c / a

%= Modulus AND

It takes modulus using two operands and assign the result to left operand

c %= a is equivalent to c = c % a

**= Exponent AND

Performs exponential (power) calculation on operators and assign value to the left operand

c **= a is equivalent to c = c ** a

//= Floor Division

It performs floor division on operators and assign value to the left operand

c //= a is equivalent to c = c // a

Python Logical Operators

There are following logical operators supported by Python language. Assume variable a holds 10 and variable b holds 20 then

 

Operator

Description

Example

and Logical AND

If both the operands are true then condition becomes true.

(a and b) is true.

or Logical OR

If any of the two operands are non-zero then condition becomes true.

(a or b) is true.

not Logical NOT

Used to reverse the logical state of its operand.

Not(a and b) is false.

Python Bitwise Operators

Bitwise operator works on bits and performs bit by bit operation. Assume if a = 60; and b = 13; Now in the binary format their values will be 0011 1100 and 0000 1101 respectively.

 

Following table lists out the bitwise operators supported by Python language with an example each in those, we use the above two variables (a and b) as operands −

 

a = 0011 1100

 

b = 0000 1101

 

—————–

 

a&b = 0000 1100

 

a|b = 0011 1101

 

a^b = 0011 0001

 

~a  = 1100 0011

 

There are following Bitwise operators supported by Python language

 

Operator

Description

Example

& Binary AND

Operator copies a bit to the result if it exists in both operands

(a & b) (means 0000 1100)

| Binary OR

It copies a bit if it exists in either operand.

(a | b) = 61 (means 0011 1101)

^ Binary XOR

It copies the bit if it is set in one operand but not both.

(a ^ b) = 49 (means 0011 0001)

~ Binary Ones Complement

It is unary and has the effect of ‘flipping’ bits.

(~a ) = -61 (means 1100 0011 in 2’s complement form due to a signed binary number.

<< Binary Left Shift

The left operands value is moved left by the number of bits specified by the right operand.

a << 2 = 240 (means 1111 0000)

>> Binary Right Shift

The left operands value is moved right by the number of bits specified by the right operand.

a >> 2 = 15 (means 0000 1111)

Strings

String in python is a literal formed with the groups of letters or meaningful words or phrases stored as values in a variable.  We can either use single or double quotes to denote a String literal.

#Example

name=”sai”

name=’sai’

We can also directly display a string literal using print() function:

#Example

print(“Welcome to”)

print(‘Python’)

Multiline Strings

Multiline string is a string that spans into multiple lines.  We can store a multiline string into a variable by using three quotes (either single or double)

#Example1

str = “””Python is

a versatile programming language

used for many purposes.”””

print(str)

#Example2

str = ”’ Python is

a versatile programming language

used for many purposes.”’

print(str)

Indexing

Python treats String as a character array and identifies each letter in the String with index values.  There are two types of indexing, they are positive and negative.

Positive indexing starts with 0 and increments by 1, assigned from left most letter towards right end.

Negative indexing starts with -1 and decrements by 1, assigned from right most letter towards left end.

 

 

Accessing String Characters

String characters can be accessed with the help of their indices.

 

#Example

str=”best”

 

#accessing with positive index

print(str[1])

 

#accessing with negative index

print(str[-2])

Slicing

You can return a range of characters by using the slice syntax.  Specify the start index and the end index, separated by a colon, to return a part of the string.

 

Example

Get the characters from position 2 to position 5 (not included):

b = “Hello, World!”

print(b[2:5])

 

Negative Indexing

Use negative indexes to start the slice from the end of the string.

 

Example

Get the characters from position 5 to position 1, starting the count from the end of the string:

b = “Hello, World!”

print(b[-5:-2])

 

String Length

To get the length of a string, use the len() function.

 

Example

str = “Welcome to Python.”

print(len(str))

 

String Methods

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

 

The strip() method removes any whitespace from the beginning or the end

 

Example

str = ”    Welcome to Python.    “

print(str.strip())

 

The lower() method returns the string in lower case:

str = “Welcome to Python.”

print(str.lower())

 

The upper() method returns the string in upper case:

str = “Welcome to Python.”

print(str.upper())

 

The replace() method replaces a string with another string:

str = “Welcome to Python. “

print(str.replace(“P”, “J”))

 

The split() method splits the string into substrings if it finds instances of the separator:

str = “Welcome to Python.”

print(str.split(” “))

 

Check String

To check if a certain phrase or character is present in a string, we can use the keywords ‘in’ or ‘not in’.  This checking would return a True or False 

 

#Example

str = “Welcome to Python.”

chk=”Py” in str

print(chk)

 

Check if the phrase “ain” is NOT present in the following text:

str = “Welcome to Python.”

chk=”Hai” not in str

print(chk)

 

String Concatenation

To concatenate, or combine, two strings you can use the + operator.

 

Example

Merge variable a with variable b into variable c:

x = “Welcome”

y = “Python”

z =x+y

print(z)

 

To add a space between them, add a ” “:

x = “Welcome”

y = “Python”

z =x+” “+y

print(z)

 

#Example

x = “Welcome”

y =x+” Python”

print(y)

 

String Format

We cannot combine strings and numbers like this:

 

Example

age = 20

x =”My age is:”+age

print(x)

 

 

But we can combine strings and numbers by using the format() method.  The format() method takes the passed arguments, formats them, and places them in the string where the placeholders {} are:

 

Example

 

Use the format() method to insert numbers into strings:

age = 20

x =”I am {} years old”

print(x.format(age))

 

The format() method takes unlimited number of arguments, and are placed into the respective placeholders:

 

Example

name=”sai”

age = 20

qual=”BSc”

str=”My name is {} of age {}, completed {}”

print(str.format(name,age,qual))

 

You can use index numbers {0} to be sure the arguments are placed in the correct placeholders:

 

Example

name=”sai”

age = 20

qual=”BSc”

str=”My name is {2} of age {1}, completed {0}”

print(str.format(qual,age,name))

 

 

Escape Character

To insert characters that are illegal to use in a string we can use an escape character.  An escape character is a backslash \ followed by the character you want to insert.

 

An example of an illegal character is a double quote inside a string that is surrounded by double quotes:

Example

 

You will get an error if you use double quotes inside a string that is surrounded by double quotes:

txt = “We are the so-called “Vikings” from the north.”

 

To fix this problem, use the escape character \”:

Example

 

The escape character allows you to use double quotes when you normally would not be allowed:

txt = “We are the so-called \”Vikings\” from the north.”

 

Other escape characters used in Python:

Code    Result Try it

\’          Single Quote  

\\          Backslash       

\n         New Line       

\r          Carriage Return         

\t          Tab     

List

List is one of the internal data structures of Python that is created with a list of values within square brackets.  The data items of list need not to be of same data type.

 

Example:

L1 = [‘Maths’, ‘Science’, 1993, 2000];

numList = [1, 2, 3, 4, 5 ];

alphList = [“a”, “b”, “c”, “d”]

 

List items are identified with positive and negative indices where positive index starts from 0 from left to right while negative index starts from -1 from right to left.

 

Example

fruitList = [“watermelon”, “banana”, “papaya”]

print(fruitList)

 

Accessing Values in Lists

The items of the list can be accessible with the help of their positive or negative indices.

 

#Example

fruitList = [“watermelon”, “banana”, “papaya”]

print(fruitList[2])

 

 

#Example

L1 = [‘Maths’, ‘Science’, 1993, 2000];

numList = [1, 2, 3, 4, 5 ];

print (“L1[0]: “, L1[0])

print (“numList[1:3]: “, numList[1:3])

print(thislist[-1])

Slicing with Range of Indexes

Slicing or accessing a group of list elements can be done by specifying the range of indexes.  In this method, we will specify a start index and stop index.  In the result, the value at start index will be included and value at the stop index will be excluded.

 

#Example

fruits = [“apple”, “banana”, “cherry”, “orange”, “kiwi”, “melon”, “mango”]

print(fruits[2:5])

 

 

#Example code to access all the values from starting index to specified index

fruits = [“apple”, “banana”, “cherry”, “orange”, “kiwi”, “melon”, “mango”]

print(fruits[:5])

 

#Example code to access all the values from specified index to the last element

fruits = [“apple”, “banana”, “cherry”, “orange”, “kiwi”, “melon”, “mango”]

print(fruits[3:])

 

Length of List

The in-built len() function can be used to get the number of items in the list.

 

#Example

fruits = [“apple”, “banana”, “cherry”]

print(len(fruits))

 

Change the value of an Item Value

Using positive or negative indices, we can modify the list data items.

 

#Example

fruits = [“apple”, “banana”, “cherry”]

fruits[1] = “watermelon”

print(fruits)

 

#Example

sub = [‘Maths’,’physics’, ‘chemistry’];

print (“Initial value at index 2 is: “)

print (sub[2])

sub[2] = ‘Oganic Chemistry’;

print (“Updated value at index 2 is: “)

print (sub[2])

 

Add new Items

New data items can be added to the existing list with the following methods.

  1. At the end of the list using append() function
  2. At the specified index using insert() function

 

#Example

fruits = [“apple”, “banana”, “cherry”]

fruits.append(“orange”)

print(fruits)

 

#Example

fruits = [“apple”, “banana”, “cherry”]

fruits.insert(1, “orange”)

print(fruits)

 

Remove Item List Elements

The existing data elements of list can be removed by the following ways:

  1. Using del command: remove value at a specified index or entire list
  2. Using remove() function: remove specified value
  3. Using pop() function: remove last element or value at specified index
  4. Using clear() function: empty list

 

#Example to remove the value at specified index

sub = [‘maths’, ‘physics’, ‘chemistry’]

print (sub)

del sub[2];

print (“After deletion value at index 2 : “)

print (list1)

 

#Example to remove a specified value

fruits = [“apple”, “banana”, “cherry”]

fruits.remove(“banana”)

print(fruits)

 

#Example to remove the list completely

fruits = [“apple”, “banana”, “cherry”]

del fruits

 

#example code to remove last element

fruits = [“apple”, “banana”, “cherry”]

fruits.pop()

print(fruits)

 

#example code to remove last element

fruits = [“apple”, “banana”, “cherry”]

fruits.pop(2)

print(fruits)

 

 

#example code to empty the list

fruits = [“apple”, “banana”, “cherry”]

fruits.clear()

print(fruits)

Copy a List

A list cannot be copied directly into another list.  If you do so, the new name will act as a reference to the existing list.

 

fruits1 = [“apple”, “banana”, “cherry”]

fruits2=fruits1

fruits2[2]= “apple”

print(fruits1)

 

Following are the in-built methods to copy a list:

  1. Using copy() method
  2. Using list() method

 

# Example code create a copy of the existing list using copy() method

fruits1 = [“apple”, “banana”, “cherry”]

fruits2 = fruits1.copy()

print(fruits1)

print(fruits2)

fruits2[2]= “apple”

print(fruits1)

print(fruits2)

 

 

 

#Example code make copy of the list using list() method

fruits1 = [“apple”, “banana”, “cherry”]

fruits2 = list(fruits1)

print(fruits1)

print(fruits2)

fruits2[2]= “apple”

print(fruits1)

print(fruits2)

 

Joining Two Lists

Two or more lists can be concatenated or joined into a single list.  The following ways can be used to join lists:

  1. Using + operator
  2. Using extend() method

 

#Example code to join two lists using + operator by creating a new list

AlphList = [“a”, “b” , “c”]

NumList = [1, 2, 3]

NewList = AlphList + NumList

print(NewList)

 

#Example code to add one list elements into another existing elements

AlphList = [“a”, “b” , “c”]

NumList = [1, 2, 3]

AlphList.extend(NumList)

print(AlphList)

print(NumList)

 

#Example code to create new list by repetitively adding the elements of existing list

AlphList = [“a”, “b” , “c”]

NewList = AlphList * 2

NumList=[1,2,3] * 3

print(NewList)

print(NumList)

Tuple

Tuple is also one of the python’s internal data structures.  The differences between lists and tuple are:

  1. Lists are created using square brackets while tuples are created with parenthesis.
  2. Lists are mutable while Tuples are immutable

 

#Exampe

tup1 = (‘physics’, ‘chemistry’, 1997, 2000);

tup2 = (1, 2, 3, 4, 5 );

tup3 = “a”, “b”, “c”, “d”

tup1 = (); #Empty tuple

tup1 = (50,); #list with single element must be created with additional comma

 

#NOT a tuple

thistuple = (“apple”)

print(type(thistuple))

 

Tuples are also having positive and negative indices to access and modify their values.

 

#Example code access tuple elements using indices

tup1 = (‘physics’, ‘chemistry’, 1997, 2000);

tup2 = (1, 2, 3, 4, 5, 6, 7 );

print (“tup1[0]: “, tup1[0]);

print (“tup2[1:5]: “, tup2[1:5]);

 

Negative indexing means beginning from the end, -1 refers to the last item, -2 refers to the second last item etc.

 

Example

#Print the last item of the tuple

thistuple = (“apple”, “banana”, “cherry”)

print(thistuple[-1])

 

Length of the tuple can get using len() function.

Tuple is immutable

Once a tuple is created, you cannot change its values. Tuples are unchangeable or immutable.

 

Example:

tup1 = (12, 34.56);

tup2 = (‘abc’, ‘xyz’);

 

# Following action is not valid for tuples

# tup1[0] = 100;

 

# So let’s create a new tuple as follows

tup3 = tup1 + tup2;

print (tup3);

 

Convert Tuple as List

You can convert the tuple into a list, change the list, and convert the list back into a tuple. 

 

Example:

x = (“apple”, “banana”, “cherry”)

#x[1]=”kiwi” this is not possible

y = list(x) #converting tuple into a list

y[1] = “kiwi”

x = tuple(y) #converting a list into a tuple

print(x)

 

Delete Tuple Elements

Removing individual tuple elements is not possible.  But we can delete entire tuple with ‘del’ command.

 

Example:

tup = (‘physics’, ‘chemistry’, 1997, 2000);

print (tup);

del tup; #but del tup[0] is not possible

print (“After deleting tup : “);

print (tup);

 

 

Concatenation and extending tuples

tup1=(1, 2, 3) + (4, 5, 6) #returns (1, 2, 3, 4, 5, 6)

tup2=(‘Hi!’,) * 4 #returns (‘Hi!’, ‘Hi!’, ‘Hi!’, ‘Hi!’)

print(tup1)

print(tup2)

Sets

The set data structure of Python is a list of data elements stored in unordered or no index manner.  Set is created using pair of curly braces. 

 

#Example code to create a Set

fruits = {“apple”, “banana”, “cherry”}

print(fruits)

 

Access Items

Since set is not maintain any index, we cannot access elements of set using index values.  But we can search for the presence of a data element by its value.

 

#Check if “banana” is present in the set:

fruits = {“apple”, “banana”, “cherry”}

print(“banana” in fruits)

Add Items

We cannot update or change the existing values of a set but can add new data elements.  The place of the newly inserted data element cannot be determined since set is unordered.

The following ways can be used to add new data items to Set:

  1. Using add() function: to add a single data element
  2. Using update() function: to add more than one data items

 

#Example to add an item to a set, using the add() method

fruits = {“apple”, “banana”, “cherry”}

fruits.add(“orange”)

print(fruits)

 

#Example to add multiple items to a set, using the update() method

fruits = {“apple”, “banana”, “cherry”}

fruits.update([“orange”, “mango”, “grapes”])

print(fruits)

 

The len() method can be used with Set to know the number of set elements.

 

#Example to get the number of items in a set

fruits = {“apple”, “banana”, “cherry”}

print(len(fruits))

 

Remove Item

The existing data items of Set can be removed by the following methods:

  1. Using remove() method: raises an error if the items removable is not exists
  2. Using discard() method: don’t raise any error if the removable item is not present
  3. Using pop() method: always remove the last element but cannot say which item will get removed since set is unordered. This method also returns the removed item.
  4. Using clear() method: empty the set
  5. Using del keyword: removes set from memory

 

#Example code to remove “banana” by using the remove() method

fruits = {“apple”, “banana”, “cherry”}

fruits.remove(“banana”)

print(fruits)

 

#Example code to remove “banana” by using the discard() method

fruits = {“apple”, “banana”, “cherry”}

fruits.discard(“banana”)

print(fruits)

 

#Example code to remove the last item by using the pop() method

fruits = {“apple”, “banana”, “cherry”}

x = fruits.pop()

print(x)

print(fruits)

 

#Example code to use clear() method to empty the set

fruits = {“apple”, “banana”, “cherry”}

fruits.clear()

print(fruits)

 

#Example code to use del keyword will delete the set completely

fruits = {“apple”, “banana”, “cherry”}

del fruits

print(fruits)

Join Two Sets

Joining of sets means creating a new set containing all the elements of given sets or add elements of one set to another.  In any case, the resultant set won’t have any duplicate values.  Two or more sets can be joined using the following way:

  1. Using union() method: creates a new set by containing all items from joining sets
  2. Using update() method: adds elements of one set to another.

 

#Example code to use union() method returns a new set with all items from both sets

set1 = {“a”, “b” , “c”}

set2 = {1, 2, 3}

set3 = set1.union(set2)

print(set3)

 

#Example code to use update() method inserts the items in set2 into set1

set1 = {“a”, “b” , “c”}

set2 = {1, 2, 3}

set1.update(set2)

print(set1)

Dictionary

Dictionary is also a collection of unordered data structure.  Dictionary can be created using key and value pairs inside pair of curly braces.  Each key and value pair is separated by colon(:) and each item of dictionary is separated with comma (,). 

 

Keys of dictionary must be unique but values may not be.  Dictionary can contain any type of values but keys must be immutable type like strings, numbers or tuples.

 

#Example code to create and print a dictionary

mydict ={

  “brand”: “Renault”,

  “model”: “Climber”,

  “year”: 2019

}

print(mydict)

 

Accessing Values in Dictionary

Elements of the dictionary can be accessed using their keys inside square brackets.  The in-built get() method can also be used for this.

 

#Example code

dict1 = {‘Name’: ‘Shiva’, ‘Age’: 18, ‘Class’: ‘First’}

print (“dict1[‘Name’]: “, dict1[‘Name’])

print (“dict1[‘Age’]: “, dict1[‘Age’])

print(dict1.get(‘Name’))

Updating Dictionary

Updating of dictionary involves adding a new key-value pair or modifying an existing item or deleting an item.

 

#Example code

Dict1 = {‘Name’: ‘Ram’, ‘Age’: 22, ‘Class’: ‘First’}

Dict1[‘Age’] = 28; # update existing entry

Dict1[‘College’] = “Govt Degree College”; # Add new entry

print (“Dict1[‘Age’]: “, Dict1[‘Age’])

print (“Dict1[‘College’]: “, Dict1[‘College’])

 

Delete Dictionary Elements

Removal of elements of dictionary can be done by the following ways:

  1. Using del keyword
  2. Using clear() method

 

#Example code

dct = {‘Name’: ‘Krishna’, ‘Age’: 7, ‘Class’: ‘First’}

del dct[‘Name’]; # remove entry with key ‘Name’

print(dct)

dct.clear();     # remove all entries in dict

print (“dct[‘Age’]: “, dct[‘Age’])

del dct ;        # delete entire dictionary

print (“dct[‘Class’]: “, dct[‘Class’])

CONTROL STATEMENTS

Control statements of any programming language are used to change the normal flow of program execution.

 

In general three types of control statements:

  1. Decision/Selection/Branching
  2. Loop/Iteration/Repetition
  3. Jump Statements

 

Python control statements

  1. Decision
    1. Simple if
    2. Multiple if
    3. .else
    4. If…elif
  2. Loop
    1. While
    2. For
  3. Jump
    1. Break
    2. continue

Decision/Selection/Branching Statements

Simple if statement

The if statement allows execution of its suit of statements under its control if the specified condition is true.

 

Example:

a=10

if (a>0):

    print(“a is positive”)

 

multiple if statement

When a set of independent conditions to be checked we can use multiple if statements

 

Example:

a=int(input(“Enter a number:”))

if (a>0):

    print(“\na is positive”)

if(a==0):

    print(“\na is zero”)

 

if(a<0):

    print(“\na is negative”)

 

if…else statement

when a pair of dependent conditions to be checked we can use if…else statement.  The dependent conditions are those if one of them is true then the other is compulsory false.

 

Example:

#example code showing two dependent conditions

a=int(input(“Enter your first number:”))

b=int(input(“Enter your second number:”))

if (a>b):

    print(“\n”,a,” is big”)

if(b>a):

    print(“\n”,b,” is big”)

 

Example:

#example code showing use of if…else for dependent conditions

a=int(input(“Enter your first number:”))

b=int(input(“Enter your second number:”))

if (a>b):

    print(“\n”,a,” is big”)

else :

    print(“\n”,b,” is big”)

LOOP STATEMENT

A loop statement allows us to execute a statement or group of statements multiple times. 

 

While Loop

A while loop statement in Python programming language repeatedly executes a target statement as long as a given condition is true.

 

Example:

count = 0

while (count < 9):

   print (‘The count is:’, count)

   count = count + 1

 

print (“Good bye!”)

 

The Infinite Loop

A loop becomes infinite loop if a condition never becomes FALSE. You must use caution when using while loops because of the possibility that this condition never resolves to a FALSE value. This results in a loop that never ends. Such a loop is called an infinite loop.

 

An infinite loop might be useful in client/server programming where the server needs to run continuously so that client programs can communicate with it as and when required.

 

Example:

var = 1

while var == 1 :  # This constructs an infinite loop

   num = input(“Enter a number  :”)

   print (“You entered: “, num)

 

print (“Good bye!”)

 

Using else Statement with While Loop

Python supports to have an else statement associated with a loop statement.  If the else statement is used with a while loop, the else statement is executed when the condition becomes false.

 

Example:

count = 0

while (count < 5):

   print (count, ” is  less than 5″)

   count = count + 1

else:

   print (count, ” is not less than 5″)

 

 

 

Single Statement Suites

Similar to the if statement syntax, if your while clause consists only of a single statement, it may be placed on the same line as the while header.

 

Example:

flag = 1

while (flag): print (‘Given flag is really true!’)

print (“Good bye!”)

 

FOR Loop

It has the ability to iterate over the items of any sequence, such as a list or a string. 

 

Syntax

for iterating_var in sequence:

   statements(s)

 

If a sequence contains an expression list, it is evaluated first. Then, the first item in the sequence is assigned to the iterating variable iterating_var. Next, the statements block is executed. Each item in the list is assigned to iterating_var, and the statement(s) block is executed until the entire sequence is exhausted.

 

Example:

for letter in ‘Python’ :     # First Example

   print (“Current Letter :”, letter)

 

fruits = [‘banana’, ‘apple’,  ‘mango’]

for fruit in fruits:        # Second Example

   print (‘Current fruit :’, fruit)

 

print (“Good bye!”)

 

Iterating by Sequence Index

An alternative way of iterating through each item is by index offset into the sequence itself.

 

Example:

fruits = [‘banana’, ‘apple’,  ‘mango’]

for index in range(len(fruits)):

   print (‘Current fruit :’, fruits[index])

 

print (“Good bye!”)

 

Using else Statement with For Loop

Python supports to have an else statement associated with a loop statement.  If the else statement is used with a for loop, the else statement is executed when the loop has exhausted iterating the list.

 

 

 

 

 

 

Nested Loop

Python programming language allows to use one loop inside another loop. Following section shows few examples to illustrate the concept

 

Syntax

for iterating_var in sequence:

   for iterating_var in sequence:

      statements(s)

   statements(s)

 

The syntax for a nested while loop statement in Python programming language is as follows

 

while expression:

   while expression:

      statement(s)

   statement(s)

 

A final note on loop nesting is that you can put any type of loop inside of any other type of loop.

 

Example:

i = 2

while(i < 100):

   j = 2

   while(j <= (i/j)):

      if not(i%j): break

      j = j + 1

   if (j > i/j) : print (i, ” is prime”)

   i = i + 1

 

print (“Good bye!”)

 

Break Statement

It terminates the current loop and resumes execution at the next statement, just like the traditional break statement in C.

 

The most common use for break is when some external condition is triggered requiring a hasty exit from a loop. The break statement can be used in both while and for loops.

 

If you are using nested loops, the break statement stops the execution of the innermost loop and start executing the next line of code after the block.

 

Example:

for letter in ‘Python’:     # First Example

   if letter == ‘h’:

      break

   print (‘Current Letter :’, letter)

 

var = 10                    # Second Example

while var > 0:             

   print (‘Current variable value :’, var)

   var = var -1

   if var == 5:

      break

 

print (“Good bye!”)

 

Continue Statement:

It returns the control to the beginning of the while loop.. The continue statement rejects all the remaining statements in the current iteration of the loop and moves the control back to the top of the loop.  The continue statement can be used in both while and for loops.

 

Example:

for letter in ‘Python’:     # First Example

   if letter == ‘h’:

      continue

   print (‘Current Letter :’, letter)

 

var = 10                    # Second Example

while var > 0:             

   var = var -1

   if var == 5:

      continue

   print (‘Current variable value :’, var)

print (“Good bye!”)

 

Pass Statement

It is used when a statement is required syntactically but you do not want any command or code to execute.

 

The pass statement is a null operation; nothing happens when it executes. The pass is also useful in places where your code will eventually go, but has not been written yet

 

Example:

for letter in ‘Python’:

   if letter == ‘h’:

      pass

      print (‘This is pass block’)

   print (‘Current Letter :’, letter)

 

print (“Good bye!”)

Functions

What is a function?

Function is a piece of code or small sub program that generally defined separately to perform a specific task.  The very first use of defining a function is reusability.  Once a function is defined, it can be invoked or called where and when necessary.  Functions also divide the program into small chunks or modules and improves readability.

 

Two forms of any function

In general, a function can be seen in two forms in the program.  One is the function definition and the other is the function invocation.  The definition of a function is the specification of what is to be performed when the function has been invoked.  The innovation of function is asking the function to perform what is specified in its definition.  A well and prior defined function can only be called or invoked.  The following are the examples of function definition and invocation.

 

#Example of function invocation

funcName()

funcName(x,y)

 

#Example of function definition

def funcName(Self):

       executable code

       executable code

 

Built-in vs User-defined Functions

Python language already providing many built-in or library functions like print(), input() which we already using in our previous programs.  Remember the definitions of those functions are available with Python language libraries.  Python is also allowing us to defined our own functions which are called as user-defined functions.

Recursive Function

When a function calls itself in its definition then it is called as recursive function.  Imagine a situation where two mirrors are arranged opposite to each other.  Infinite reflections will be generated between them.  Similarly, a recursive function creates a loop hence the developer should take care in his logic so that it should be terminated at some point.  But Python doesn’t allow a recursive function to the depth of more than 1000 times.  Python automatically displays a recursionError when the maximum depth of recursion is crossed.

 

#Example of recursive function

def func1(x):

    print(x)

    func1(x+1)

 

func1(1)

 

#Example program showing how recursion works

def fact(x):

    if x == 1:

        return 1

    else:

        return (x * fact(x-1))

 

x=int(input(“Enter your number:”))

print(“The factorial of”, x, “is”, fact(x))

 

Lambda Functions

A function with no name is known as anonymous function.  The keyword ‘lambda’ instead of ‘def’ to be used to create an anonymous function.  A lambda function usually has a single line of body but can take many arguments.

 

#Example showing how lambda function works

sqr = lambda x: x * x

 

n=int(input(“Enter any number:”))

print(“Square of your number: “,sqr(n))

 

Pass by reference vs value

We already learn how the

 

#Example of pass by value

def changeme(seq):

   seq=[1,2,3,4];

   print (“Values inside the function: “, seq)

   return

 

myseq = [10,20,30];

changeme(myseq);

print (“Values outside the function: “, myseq)

 

#Example of pass by reference

def changeme(seq):

   seq.append([1,2,3,4]);

   print (“Values inside the function: “, seq)

   return

 

myseq = [10,20,30];

changeme(myseq);

print (“Values outside the function: “, myseq)

Modules

Module in Python is simply a file contains definitions of functions and classes and saved with .py extension so that it can be reused in another python program.  Hence there no separate process exists to create a module.  We can split our code into number of modules so that it can be managed easily.  Splitting code into modules is useful in big projects.

 

The import keyword

Once a module is created and saved the variables, functions, classes defined in that module can be reused in another module.  In order to do that, the respective module must be imported to our current module using ‘import’ statement.

 

#Example program to be saved as two separate files

#save this module as mod1.py

def func():

    print(“this is separate module”)

 

#save this module as mod2.py

import mod1

 

mod1.func()                  #since func() is defined in mod1

 

Alias for Module

When you feel the name of module is lengthier you can put an alternate name in the module into which it is importing using import…as… statement.

 

#Example code providing alias for mod1

import mod1 as m

 

m.func()                        #since func() is defined in mod1

from…import *

When you feel discomfort to use module name prefixed each time some member of it is called you can change the syntax of import statement as from…import *

 

#Example code showing how to import all members from a module

from mod1 import *

 

func()                           

 

importing specific functions only

When you really need a specific function only instead of all the members from a module you can specify names of those members only instead of ‘*’

 

#save this file mod3.py

def func1():

    print(“func1 code”)

 

def func2():

    print(“func2 code”)

   

x=10

 

#code showing how to import specific members from a module

from mod3 import x,func1

 

func1()

print(x)

Built-in Modules

Python provides several built-in modules which can be imported whenever you need.  Built-in modules are written C and interpreted through python interpreter.  You have to use import sys statement in your program to use built-in modules. 

 

Type help(‘modules’) at python shell or prompt to view the list of all built-in modules of python.  You can also use same help() function to show all the content of individual module.

For example: help(math) 

 

#code showing how built-in module ‘math’ can be used

import math

 

x=int(input(“Enter your number:”))

print(math.factorial(x))

print(math.sqrt(x))

 

The dir() function

This function returns a short list of all the functions, variables and other members of given module.

 

#code showing how dir() function works

import mod3

 

a=dir(mod3)

print(a)

 

Modules Search Path

When you imported a module, Python first searches for that module in current working directory, if not found it search in path of Python installation and even it couldn’t find it will search through all the paths stored in sys.path

 

#code showing all paths stored in sys.path

import sys

 

print(sys.path)

 

 

 

__name__ variable

The name of the first module

Package

A package in Python is like a folder in Windows which is usually stores the files and other folders.  Similar to that, a python package may contain another packages (sub packages) or modules in it. In order to use a package in our working program the package must be residing in the path that is known to our Python IDE.  We already know all the known paths are stored in sys.path variable.  We have to add the new unknown path of your package to the sys.path variable.

 

import sys

sys.path.append(“path of package”)

 

#This program needs to create two packages and respective modules

#create a package newPkg in current working folder

#create module ModA under newPkg and save the following code

def disp():

    print(“Hi from ModA”)

 

#create module ModB under newPkg and save the following code

def show():

    print(“Hi from ModB”)

 

#create a package PythonProject on your desktop

#create module mod1and save the following code

x=10

def func1():

    print(“func1 code”)

 

def func2():

    print(“func2 code”)

   

#create new python file in your current working folder and save the following code

import sys

sys.path.append(“C:\\Users\\SatyamITGURU\\Desktop”) #adding the unknown path

 

from newPkg.ModA import *            #newPkg is created inside current working folder

from PythonProject.mod1 import *

 

disp() #disp() is the module defined in ModA

func2() #func2() is the module defined in mod1

Exception Handling

Types of Errors occur during program development

It is common to occur any error during program development due to the ignorance of developer, program or some external resource.  Basically, there are two types of errors occur during any program development.  They are Compile time errors and Run-time errors.  As their name saying, compile time errors occur at the time of compiling the source code while run-time errors occur at the time of executing the program. 

 

Compile-time errors are two types, they are

Syntax Errors: occur when sentence construction rules are avoided.

Semantic Errors: occur when some useless code is founded.

 

Run-time Errors are also two types, they are

Logical Errors: occur due to ignorance or negligence of developer.

unExpected Errors: occur due to lack of or failure of some external resource.

 

Exception Handling of Python is a mechanism to handle unexpected runtime errors only (the last one), but not any other types of errors discussed above.  Exception can be defined as an unwanted situation during the execution of the program.  Exception causes the abnormal termination of the program.  This situation is not suitable for the following examples real-time scenarios

  1. ATM program is closed due to wrong password entry by a user.
  2. A network application is closed due to some mistake done by the user on a particular node.

 

Handling of exception is the concept of avoiding abnormal termination of the program due to exception so that the program would continue its execution by taking necessary steps regarding exception.  The handling of exception is not providing solution for the exception but it is providing an alternative way to run the rest of the program which is not dependent on the code in which exception occurred. 

 

#Example code with run-time error

x=10

y=0

print(“Division Operation”)

print(x/y)

print(“rest of the code”) 

 

The output of the above code would be like below:

Division Operation

Traceback (most recent call last):

  File “D:\Python Programs\practice.py”, line 4, in <module>

    print(x/y)

ZeroDivisionError: division by zero

 

The exception raised in the above code is divisible by zero in the line “print(x/y)”.  You can observe there is an output statement that is displaying a string “print(“rest of the code”) is not executing even though it is not at all dependent on the code line in which exception occurred.

This is also known as abnormal termination or automatic exception handling handed over to PVM.

 

#same program with exception handling

x=10

y=0

print(“Division Operation”)

try:

    print(x/y)

except:

    print(“Division by zero Error”)

print(“rest of the code”)

 

The output of the above program is :

Division Operation

Division by zero Error

rest of the code

 

The difference you can get from the second example is, it continues with the printing of the string “rest of the code…” by showing respecting exception message.  This is known as manual exception handling due to which the program would be terminated normally.

Manual Exception Handling in Python is done by try…except pair.  The risky code (i.e. the code where there may be chance of exception raising) is kept under the control of try block.  The try block informs its following except block about the exception raised inside try block.  The except block is responsible to handle the exception raised inside try block.

 

#Example

try:

  print(x)

except:

  print(“Exception raised”)

print(“rest of the code”)

 

Mutiple except blocks

One try block may be followed by multiple except blocks.  For each different exception raised inside try block there must be a specific except block can be defined with the name of corresponding errorname.  The except blocks must be in the order of most specific to most general.

 

y=0

try:

    print(x)  #NameError

    x=10

    print(x/y) #ZeroDivisionError

except NameError:

    print(“variable x is not defined”)

except ZeroDivsionError:

    print(“Division by zero is not possible”)

except:

    print(“exception raised is not known”)

   

print(“rest of the code”)

 

Points regarding Multiple except blocks:

  • Only one out of all except blocks will be executed
  • Once an exception raised inside the try block, there will be no chance of execution for the rest of the code inside try block, following exception caused statement.

 

The else block followed by try…except

The else block can be used with try…except blocks to specify the special code that is to be executed when no exception raised inside try block.

 

#Example showing using else with try…block

try:

  print(“Python”)

except:

  print(“Exception raised”)

else:

  print(“Everything is fine”)

Finally

The finally is the block which is also used with try…except pair.  The finally will always be executed regardless of exception.  In general, the cleanup code will be put inside finally block.  A try block may have many except but only one finally block.  Try without except or finally is invalid.

 

#example showing use of finally block

try:

    print(“hi”)

except:

  print(“Exception raised”)

finally:

  print(“finally block always executed”)

   

print(“rest of the code”)

Object Oriented Programing

Introduction to OOP

Object Oriented Programming is one of the different programming paradigms like procedure oriented, function oriented etc.  In this programming approach the program logic is think in terms of objects.  Every object has some attributes and abilities.  Objects can work and communicate with the world and even with each with the help of methods.  Object can be representative of any real-world entity.  For example, car is an object, Table is an object, man is an object and so on.  A group of objects can have common behaviour and similar attributes.  So we can create a model or blueprint that represent those objects.  Like Alto, Dezire, Baleno are car objects and ‘four-wheeler’ or ‘Maruti-car’ can be considered as a blue print or model.  In Object oriented programming, the blue print or model which is used to create number of objects is known as class.

 

Class and Objects

In another way, class a can be considered as a user-defined data type.  Consider integer data type of C language, we use int data type to declare variables.  What is a variable?  It is a data element that is used to hold some kind of data.  But before that, the system must know how to allocate memory for that data element.  The attributes or characteristics of variables are defined by its data type.  We can say data type specifies the characteristics and operations possible on each data element that is declared out of that data type.  Similar to that, class can be defined as a user-defined data type out of variables can be declared.  The variables of class are known as objects. 

Creating class

In python, a class can be defined using ‘class’ keyword.  A class can contains variables and methods.  The content variables and methods of a class are known as its members.

 

Creation of Object or Class instantiation

As we understood object is a variable or instance declared out of the class, each object can hold all the members of its class definition.  The memory for the class members will be allocated at the time of instantiation.  The object can access its members by using dot(.) operator.

 

 

#Example code showing relationship between class and object

class human:

    Eyes=2

    Nose=1

    def walk(Self):         //Self is reference parameter

        print(“I can walk”)

 

m1=human()                 //human() the constructor

print(“I have “,m1.Eyes, “eyes”)

print(“I have “,m1.Nose, “Nose”)

m1.walk()

 

The ‘self’ parameter

The ‘self’ parameter acts as a reference to the current instance of the class.  The name ‘self’ is not mandatory but it must be the first parameter of any function in the class.

 

#Example code how constructor can call ___init__ method

class mobile:

    def __init__(self,Make,Model):

        self.Make=Make

        self.Model=Model

    def show(S):

        print(“My Manufacturer :”,S.Make)

        print(“My Model :”,S.Model)

 

m1=mobile(“Vivo”,”X50″)

m1.show()

Constructor

A constructor is a special method of class.  It is special because it has the same name as its class and by default available in the class definition.  The constructor invokes the ‘__init__’ method automatically each time you create an object.  The __init__() method is a method by default available to any class definition that is used to initialise the instance variables of class.

 

Class Variables and Instance Variables

There are two types of variables we can see inside a class definition.  Class variables and instance variables.  Class variables are those variables that are initialised inside class definition.  Those will have a fixed value for all the instances of the class

 

#class variable example

class human:

            eyes=2

 

m1=human()

m2=human()

print(m1.eyes)

print(m2.eyes)

 

An instance variable is the one that will have different values for each instance declared out of that class.  The instance variable usually get initialised by the constructor.

 

#instance variable example

class human:

    eyes=2

    def __init__(self,name,skincolor):

        self.name=name

        self.skincolor=skincolor

       

m1=human(“ram”,”blue”)

m2=human(“sita”,”fair”)

print(m1.eyes,” “,m1.name,” “,m1.skincolor)

print(m2.eyes,” “,m2.name,” “,m2.skincolor)

Inheritance

Inheritance is one of the features of OOP language.  Through this feature, an OOP language can allow code reusability.  A class can be inherited into another class or derived from another class.  The class that is being inherited is known as base or parent class and the derived class is known as child class. 

Instantiation can be done for both parent and child classes but it is conventional to declare objects from child class only since it is the most specialised version.

 

#Example code showing how a base class can be inherited

class person:

   

    def getperson(self):

        self.name=input(“Enter your name:”)

        self.age=input(“Enter your age:”)

        self.qual=input(“Enter your qualification :”)

 

class employee(person):

   

    def getemp(self):

        self.desg=input(“Enter your designation:”)

    def showdata(self):

        print(“Employee Details”)

        print(“Name :”,self.name)

        print(“age :”,self.age)

        print(“qual :”,self.qual)

        print(“desg :”,self.desg)

 

ramu=employee()

ramu.getperson()

ramu.getemp()

ramu.showdata()

 

Types of Inheritances

The following four types of inheritances are possible in python.  They are:

  1. Single
  2. Multi level
  3. Multiple
  4. Hierarchical

Single or Single Level Inheritance

If one class is extended into another sub class, it is known as single inheritance.  In other words, if the class from which object is declared is derived from one base class, it is known as single level inheritance

 

#Example

class person:

    def getperson(self):

        self.name=input(“Enter your name:”)

        self.age=input(“Enter your age:”)

        self.qual=input(“Enter your qualification :”)

 

class husband(person):

   

    def gethus(self):

        self.getperson()

        self.wife=input(“Enter your spouse name:”)

   

    def showdata(self):

        print(“person Details”)

        print(“Name :”,self.name)

        print(“age :”,self.age)

        print(“qual :”,self.qual)

        print(“spouse :”,self.wife)

 

ramu=husband()

ramu.gethus()

ramu.showdata()

 

 

Multi Level Inheritance

If the class from which object is created is derived from a base class which is already derived from another base class, it is known as multi-level inheritance.

 

#Example

class person:

    def getperson(self):

        self.name=input(“Enter your name:”)

        self.age=input(“Enter your age:”)

        self.qual=input(“Enter your qualification :”)

 

class husband(person):

   

    def gethus(self):

        self.getperson()

        self.wife=input(“Enter your spouse name:”)

   

class father(husband):

    def getchild(self):

        self.gethus()

        self.child=input(“Enter your child name:”)

   

    def showdata(self):

        print(“person Details”)

        print(“Name :”,self.name)

        print(“age :”,self.age)

        print(“qual :”,self.qual)

        print(“spouse :”,self.wife)

        print(“Child :”,self.child)

       

ramu=father()

ramu.getchild()

ramu.showdata()

Hierarchical Inheritance

If one base class is inherited into two or more child classes it is known as hierarchical Inheritance. 

 

#Example

class person:

    def getperson(self):

        self.name=input(“Enter your name:”)

        self.age=input(“Enter your age:”)

        self.qual=input(“Enter your qualification :”)

 

class husband(person):

   

    def gethus(self):

        print(“Enter personal Details”)

        self.getperson()

        self.wife=input(“Enter your spouse name:”)

   

    def showdata(self):

        print(“person Details”)

        print(“Name :”,self.name)

        print(“age :”,self.age)

        print(“qual :”,self.qual)

        print(“spouse :”,self.wife)

   

   

class employee(person):

    def getdesg(self):

        print(“Enter Employee Details”)

        self.getperson()

        self.desg=input(“Enter your desgination:”)

   

    def showdata(self):

        print(“Employee Details”)

        print(“Name :”,self.name)

        print(“age :”,self.age)

        print(“qual :”,self.qual)

        print(“desg :”,self.desg)

       

ram=husband()

lakshman=employee()

ram.gethus()

lakshman.getdesg()

ram.showdata()

lakshman.showdata()

 

Multiple Inheritance

If a class is derived from more than one base class, it is known as multiple inheritance.

 

 

#Example

class person:

    def getperson(self):

        self.name=input(“Enter your name:”)

        self.age=input(“Enter your age:”)

        self.qual=input(“Enter your qualification :”)

 

class student:

   

    def getstd(self):

        print(“Enter student Details”)

        self.course=input(“Enter your course name:”)

   

class employee(person,student):

    def getdesg(self):

        print(“Enter Employee Details”)

        self.getperson()

        self.getstd()

        self.desg=input(“Enter your designation:”)

   

    def showdata(self):

        print(“Employee Details”)

        print(“Name :”,self.name)

        print(“age :”,self.age)

        print(“qual :”,self.qual)

        print(“course :”,self.course)

        print(“desg :”,self.desg)

       

ram=employee()

ram.getdesg()

ram.showdata()

Polymorphism

Polymorphism allows the ability to take different forms.  It refers to the use of a single program element like method, operator or object to represent different types in different scenarios.

 

In Python, Polymorphism can be exhibited in the following four ways:

  1. Duck Typing
  2. Method Overloading
  3. Operator Overloading
  4. Method Overriding

Duck Typing

This term comes from the saying “If it walks like a duck, and it quacks like a duck, then it must be a duck.”  Python follows the EAFP (Easier to Ask Forgiveness than Permission) rather than the LBYL (Look Before You Leap) philosophy.

Unlike other programming languages that demand the declaration of a variable before its use, python is allowing the developer to create variable just by assigning a value.  Then how python can understand the type of variable or object?  It understands the type of variable by its methods.

 

#Example code

class programming:

    def code (self, ide):

        ide.execute()

   

class best:

    def execute (self):

        print(“I am learning Python from Best Computer Institute”)

   

ide = best()

 

obj1 = programming()

 

obj1.code(ide)

 

 

Method Overloading

Method overloading is the concept of a method with different signatures or implementations or definitions.  The name of the method should be same but the number of arguments or type of arguments must be different.  Based on the number of parameters passed at the time of invocation, the corresponding definition should be linked.

But, unlike other Object Oriented programming languages like C++ and Java,  Python does not support method overloading directly, but we can achieve it by modifying out methods.

 

 

#Example code

class best:

    def sum(self, a = None, b = None, c = None):        

        s = 0

        if a != None and b != None and c != None:

            s = a + b + c

        elif a != None and b != None:

            s = a + b

        else:

            s = a

        return s

       

s = best()

 

print(s.sum(1))

 

print(s.sum(3, 5))

 

print(s.sum(1, 2, 3))

 

 

Operator Overloading

Operator overloading is the ability of a single operator to perform more than one operation based on the class (type) of operands. For this we will define a separate method inside the class whose objects are interested to use the operator.

 

We know the arithmetic operator ‘+’ works with numbers as well as strings.  But it cannot be used with user-defined types like objects.  We can make it possible by overloading.

 

#Example code

class sum:

   

    def __init__(self, m1, m2):

        self.m1 = m1

        self.m2 = m2

 

    def __add__(self, other):

        m1 = self.m1 + other.m1

        m2 = self.m2 + other.m2

        s3 = sum(m1, m2)

        return s3

 

s1 = sum(58, 59)

s2 = sum(60, 65)

s3 = s1 + s2

print(s3.m1)

print(s3.m2)

 

 

 

Method Overriding

By this concept, a sub class re-defines the existing method of its parent class to customize its implementation for its purpose.

 

#Example code

class father:

    def doEducation(self):

        print(“You must do Engineering”)

 

       

class son(father):

    def doEducation(self):

        print(“No, I will do Chartered Accountancy”)

 

raj = son()

raj.doEducation()

File Handling

File handling in Python is performed with the help of some pre-defined functions.  We will learn about those functions one by one.

 

The open() function:

This function is used to open an existing or saved file.  The same function can also creates or overwrites a file based on the mode.

 

Syntax: open(filename,mode)

Where:

Filename – the name of the file that we want to work with.

Mode – as the value for this working mode, we can supply any one of the these letters:

r  – read only – tries to open an existing file, returns error if file not found

a – Append – opens file to add some additional text to the existing content.

w – Write – opens a file for over writing, if the file does not exists it will create it

x – Create – creates a file, returns error if file already exists.

 

In addition to the above modes

t  – indicate working with text file (default value)

b – indicate working with binary file

 

“””Create a text file with Notepad app

This is the first file to be

read from

Python Program

and save it in your python working folder with name file1.txt”””

#Enter this code in your IDE to open the content of your file

f=open(“file1.txt”,”r”)

print(f.read())

 

The readline() function to read content of the file line by line

#reading content of the file line by line

f=open(“file1.txt”,”r”)

print(f.readline())

print(f.readline())

print(f.readline())

 

The write() function is used to over write the content of the existing file.  If the file does not exist then it creates a new file.

 

#write() function to create or overwrite a file

f=open(“file2.txt”,”w”)

f.write(“Second File”)

 

f=open(“file2.txt”,”r”)

print(f.read())

 

 

#Example code to copy content of one file into another

f=open(“file1.txt”,”r”)

f1=open(“file3.txt”,”w”)

 

for data in f:

    f1.write(data)

 

f1=open(“file3.txt”,”r”)

print(f1.read())

 

#Example code to add additional content to existing file

f=open(“file1.txt”,”r”)

f1=open(“file3.txt”,”a”)

 

for data in f:

    f1.write(data)

 

f1=open(“file3.txt”,”r”)

print(f1.read())

 

#Example code to duplicate an image

f=open(“flowers.jpg”,”rb”)

f1=open(“flowerscopy.jpg”,”wb”)

 

for data in f:

    f1.write(data)

Multi Threading

Multi Tasking

The activity of doing more than one task at a time is known as multi-tasking.  In computer science, two types of multi-tasking

  1. Process based (or) o/s level
  2. Thread based (or) program level

 

Multi-threading is a concept of running different parts of a program simultaneously which are independent of each other.

 

Multi-threading can be witnessed in our games where some characters has to move independently while we are playing one character.

Thread is basically a lightweight sub-process, a smallest unit of processing. Multiprocessing and multithreading, both are used to achieve multitasking.

Multithreading is most preferable than multiprocessing for the following advantages:

  1. threads share a common memory area. They don’t allocate separate memory area so saves memory.
  2. context-switching between the threads takes less time than process.

Advantage of Multithreading

It doesn’t block the user because threads are independent and you can perform multiple operations at same time.

You can perform many operations together so it saves time.

Improves CPU utilisation.

Threads are independent so it doesn’t affect other threads if exception occur in a single thread.

What is Thread in Python

A thread is a lightweight sub process, a smallest unit of processing. It is a separate path of execution.

Threads are independent, if there occurs exception in one thread, it doesn’t affect other threads. It shares a common memory area.

#Example code showing how two processes run without threading

class First:

    def run(Self):

        for i in range(5):

            print(“Hello”)

 

class Second:

    def run(Self):

        for i in range(5):

            print(“Hi”)

 

t1=First()

t2=Second()

 

t1.run()

t2.run()

#Example code showing how two processes run with threading

from threading import *

 

class First(Thread):

    def run(Self):

        for i in range(5):

            print(“Hello”)

 

class Second(Thread):

    def run(Self):

        for i in range(5):

            print(“Hi”)

 

t1=First()

t2=Second()

 

t1.start()

t2.start()

You cannot copy content of this page