0% found this document useful (0 votes)
6 views191 pages

PythonNotesFinal (3)

The document explains the concept of programming and scripting languages, highlighting Python as a fast, open-source scripting language developed by Guido van Rossum. It details the advantages and disadvantages of Python, its features, and various applications, as well as how to set up and execute Python code. Additionally, it covers fundamental programming concepts such as variables, data types, comments, and boolean functions.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views191 pages

PythonNotesFinal (3)

The document explains the concept of programming and scripting languages, highlighting Python as a fast, open-source scripting language developed by Guido van Rossum. It details the advantages and disadvantages of Python, its features, and various applications, as well as how to set up and execute Python code. Additionally, it covers fundamental programming concepts such as variables, data types, comments, and boolean functions.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 191

Program:

Sequence of instructions that are needed to be executed in order to


get the output/result.

Purpose:
1)To get the results in a faster manner.
2)To get the results in an accurate manner.

Example: To add two numbers.

So,to accomplish our tasks,we are writing the code.


This code can be written by using programming languages and also by using the
scripting languages.

Basic differences between a programming and scripting oops

Programming Language: C,CPP,Java

1)It takes many lines of code for even a smaller requirement(task)


2)It increases cost of maintenance
3)It is heavy weight language

Scripting Language: Python,Ruby,Perl

1)It takes less lines of code even for a larger requirement(task)


2)It reduces cost of maintenance
3)It is light weight Language

What is python:
Python is a fastest scripting language.

It was created by Guido van Rossum in 1989 and was released in 1991.

Why is it called Python? When Guido van Rossum began implementing Python,he used to
read the published scripts from
Monty Python's Flying Circus , a BBC comedy series from the 1970s. Van Rossum
thought he need a name that has to be short, unique, and slightly mysterious, so he
decided to put the name of the as language Python.

The code written in python will be executed very fastly while compared with
the code written in any other languages.Hence they named the language as "python".

Example:
If i just want to print the value "19" on to the monitor using java,the following
code must be written.....

class Sample
{

public static void main(String args[])


{

int value;
value=19;
System.out.println(value);//19

If we want to do the same in python,just the following code is sufficient.....

print(19)

Thats it....................!!!!!!!!!!!!!!!!!!!

As the number of instructions are less,the code will be executed very fastly...

Features:

1)It is a scripting Language, developed by Guido Van Rossum in 1989 and was
released in 1991.

2)It is an open source i.e. it can be downloaded for free from the below link.
www.python.org/downloads

3)Python is language with a huge following of volunteers that are constantly trying
to improve it.

4)It is an Object oriented language ie., in python,every thing will be treated as


an object.
Example :
x= Python is simple and easy to learn #x is treated as an object.
print x.count( e ) # 3

5)It is Portable/flexible language that means,it runs on many Unix variants, on the
Mac, and Windows 2000 and later.

6)It has very rich set of Libraries/Modules(Predefined things).

7)It is simple and easy to learn.

===========Applications============
Desktop applications
Web development --> django
Game development
Automation testing
Networking
Hadoop(Pydoop) and Bigdata ---->To place data in cloud and also to retrieve data
from cloud
Puppet scripts
We can integrate python scripts in java using jython tool,in dotnet using
ironPython tool.
=================Disadvantages=====================
1)Python has a smaller pool of experienced developers compared to other languages
like Java.

2)It has database access limitations.

3)The language isn t a good choice for mobile applications as it is very weak in
mobile computing.

4)Slower than C,CPP(platform dependent languages) but faster than platform


independent languages.

5)Runtime errors:
More errors(Exceptions) will be shown at Runtime.(At the time of execution)

6)It's near impossible to build a high-graphic 3D game using Python.

===========================
1)Compilation:Compiler
Converts the high level code to low level code/machine understandable code/binary
code.

2)Execution:
Resolving the binary code step by step is called as execution.

c+e
hello.c ------------>hello.exe

compiler PVM(interpreter)
hello.py---------->hello.pyc--------------------->hello.exe

pythonclass file

Compiler
PVM

System---->OS--->
JVM--->Java appli
JIT-COm--->.net appli
PVM-->Python appli

.pyc ====>Python class file

PVM =====>Python Virtual Machine(Interpreter)


So, python is both compiler based and interpreter based language.

Compiler ====> Translates the whole program into machine code.


Interpreter ====>Translates/Resolve program(low level code) one statement at a
time.

Python is both compiler and interpreter based language....


PVM(In)
HL---->Output

=================Working with python===================


To write and execute a python program:

Download and install python software:


google--->www.python.org--->downloads--->download python3.8(any version).
Open the downloaded file and install it.

After the installation,you can see python3.7 folder in "All programs" column of
your computer.

Ways to execute python code:


1)Using python line(Command mode)
2)Using IDLE(Script mode)
3)Using PyCharm(better way)
4)Using normal command prompt

1)Using python command line(Command mode)

To open python in the command mode:

All programs----->python 3.7----->python(black icon with snakes)-->click on it.

Type the code/script in the command prompt

(or)
In the search space of your computer,type "python".Then,we can observe "python
comandline".Click on it.
Then a python cmd prompt will be opened.

2)Using IDLE(Script mode):

To open python in the script mode:

All programs----->python 3.7----->IDLE----->Click on it.

Now IDLE will be opened.

To write some code,then go to File--->New File---->save the file like hello.py-----


>Write the code.
You can execute that code in the following manner...
Run---->Run module.Output will be shown in a separate window(shell).

All your files saved in the IDLE will be going to the below path by default:
C:\Users\user\AppData\Local\Programs\Python\Python36-32

3)Using PyCharm(better way):

Working with pycharm:

Link to download pycharm:


https://www.jetbrains.com/pycharm/download/#section=windows

There you will get two options----"Professional" and "Community"

Download "Community" .It is an open source.So, download this.


Professional is not an open source....Its just a trial version..Later we have to
buy it.

To open pycharm:

All programs----->Jetbrains Pycharm------>double click on it.

By default the projects done in pycharm will go to c--->users--->user---


>PycharmProjects.

4)Using normal command prompt:

To execute a .py program using a normal command prompt,we should


set the path first.data

Process to set the path:

Path:Indicating the location of .exe files to the OS.


We are telling the location of those files that makes our program
to execute.

Process of setting up the path:

right click
My Computer------------------->properties----->Advanced--->
Environmental variables------>User variables--->new--->

variable name:PATH
variable value:paste

ok----->ok----->ok.

C:\Users\user\AppData\Local\Programs\Python\Python36-32 -------->copy

To check wether the path was properly set or not


C:>python
It will show some information if the path was set properly.
Else,it will show cmd not found.
After setting the path,you can take a notepad and you can write the program.After
that save the file with the extension .py (hello.py say).
Let us say your file is there in the desktop.
Now, open the command prompt and give the compilation and execution commands.

Command for compilation:

>>python -m py_compile hello.py

In the current working directory," __pycache__ " folder will be created


and inside that you can see hello.pyc file.

Command for execution:

>>python hello.py

Note:
Directly you can give the execution command without giving the compilation command.
If you want to have .pyc file to make it portable,in that case only you should give
the compilation command.

C:\Users\QSHORE>cd desktop

C:\Users\QSHORE\Desktop>python test.py
Hello all

================Variables=====================

It is the name of a memory cell.


This is used to store a value.

Example:
a=10
print(a)

o/p:10

==================

a=100

a=20

a=90

print(a) #90

A variable can store only one value at a time.(The latest value)

===========================
a=10
b=20

print("The value of a is",a)


print('The value of b is',b)

output:
The value of a is 10
The value of b is 20

====================================
no1=10
no2=20

sum=no1+no2
print('The sum is',sum)

sub=no1-no2
print("The sub is",sub)

mul=no1*no2
print("The mul is",mul)

div=no1/no2
print("The div is",div)

================================
In the instruction a=10, = is called as an "Assignment operator".

This assignment can be done in two ways:


1)Assigning single value to multiple variables:

Syntax:
var1=var2=var3=value

Ex:
x=y=z=90
print(x)
print(y)
print(z)
print(x,y,z)

Output:
90
90
90
90 90 90

2)Assigning multiple values to multiple variables:

Syntax:

var1,var2,var3=val1,val2,val3

a,b,c=5,10,15
print(a)
print(b)
print(c)

op:
5
10
15

Assigning multiple values to multiple variables.

name,gender="Harika","F"
print(name,gender)

Output:
Harika F

================id()==================

id() is used to get the address of a variable.

Syntax:
id(VariableName)

=======================
a=10
print(a)
print(id(a)) #1001

b=20
print(id(b)) #1002

c=90
d=90
print(id(c)) #1003
print(id(d)) #1003

Both c and d will be pointed to the same address 1003

If the values inside the variables are same,then the addresses of the variables
will also be same.

If the values inside the variables are different,then the addresses of the
variables will also be different.

========================
Rules to be followed to declare variables:

1)Should start with [a-z][A-Z] _


2)Variable names should not contain any special character(except _)
3)Variable names are case sensitive.
4)Variable names should not be any keyword.

===========================
To check the keywords available in python:
Open python in the command mode

>>>help()

Welcome to Python 3.7! This is the online help utility.

If this is your first time using Python, you should definitely check out
the tutorial on the Internet at http://docs.python.org/2.7/tutorial/.

Enter the name of any module, keyword, or topic to get help on writing
Python programs and using Python modules. To quit this help utility and
return to the interpreter, just type "quit".

To get a list of available modules, keywords, or topics, type "modules",


"keywords", or "topics". Each module also comes with a one-line summary
of what it does; to list the modules whose summaries contain a given word
such as "spam", type "modules spam".

help> keywords

Here is a list of the Python keywords. Enter any keyword to get more help.

and elif if print


as else import raise
assert except in return
break exec is try
class finally lambda while
continue for not with
def from or yield
del global pass
help>crtl+z and enter
#To come out and get a python prompt
>>>
================================
Try to take the variable names as small because it will become easy to access them
furthur.
Ex:
rollnumber -->Not prefered
roll_no --->Prefered

============Comments==========================
Comments:
What ever we do write under comments,that will not be considered for execution.

Python supports two types of comments:

1)Single line comment:


Used to comment only one line.It is done by using # .

Eg:
#single line comment
print("Hello Python")

output:
Hello Python

2)Multi lined Comment:


This is used to comment multiple lines at a time.
Multi line comment can be given inside triple quotes or double triple
quotes.

eg:

''' This
Is
Multipline comment
'''
eg:

"""
This is also a
perfect example of
multi-line comments
"""

======================================

'''
====>triple quotes

'''

"""

=====>double triple quotes

"""

===General data types===

Data Types:
Type of value stored in a variable.
A variable can store 4 types of values

int----->Integers(+ve,-ve,0)
float--->Decimal values(2.6,9.99)
str(String)--->Collection of characters('a' '1' '@' --->
'Pinky',"Helloall@123",'''Hai''')
bool----->True or False

type():Used to know the type of value stored in a variable.

Syntax:

type(VariableName)

Important note:

How the datatype of a variable is decided??

Basing on the type of value stored in the variable,we can determine the data type
of that variable.
============================================
Note:
String:
Group of characters or collection of characters is called as a string.
Every String must me embedded in single,double or in triple quote.

Character:
Any individual entity

'a' '1' '@'

Ex:
"pinky"
"1001AbC100@"

a=10 #(int---->Integers(+ve,-ve,0))
print(type(a)) #<type 'int'>

b=2.3 #(float---->Decimal values)


print(type(b)) #<type 'float'>

String:
Group of characters is called as a string.
Character means any individula entity like '1' 'a' '@'

name="John" #(strings----Group of characters)


print(type(name)) #<type 'str'>

name1='Peter'
print(type(name1)) #<type 'str'>

a=True #(bool----->To store true or false(T and F must be capital))


print(type(a)) #<type 'bool'>

type():
Used to see the type of value stored in a variable.

Ex:

a=10
print(type(a))#int

======Program to add two numbers=====(Execute in cmd prompt)


a=10
b=20
c=a+b
print(c)
print('The sum is',c) #The sum is 30

# >>c this will also print 30 as output in command prompt

#exit() to exit the cmd prompt


=====using place holders "{}" in printing the output=======

Something is going to be substituted in the place of a place holder.


A a place holder is indicated by " {} " .

() ----->function/method/
format() is a function

print('I love {0} and {1}'.format('bread','butter'))


# Output: I love bread and butter

print('I love {1} and {0}'.format('bread','butter'))


# Output: I love butter and bread

'''

a=10
b=20
c=a+b ===>The sum of 10 and 20 is 30
print("The sum of",a,"and",b,"is",c)
print("The sum of {0} and {1} is {2}".format(a,b,c))

'''

Another way of using place holders:


print('Hello {name}, {greeting}'.format(greeting = 'Goodmorning', name = 'John'))
Hello John, Goodmorning

print('Hello {name}, {greeting}.I am fine {name}'


.format(greeting = 'Goodmorning', name = 'John'))

print('Hello {} ,wishing you {}'.format("John","Happy bday"))

a=23
b="Rosy"
f="hello"
print(f"The name is {b} {f} and the age is {a}")

==============Boolean functions=========

Boolean functions will produce the result as either true or false.


We can apply boolean functions only on strings.

String is a collection of characters


character: '1' 'a' '@'
These boolean functions are used to validate the inputed data.

String===>number,alphabet,special symbol
a,n,s

================isalpha()==================
isalpha() returns true if all the characters in the string are alphabets.
my_string="Hello world"

print(my_string.isalpha())

OP:false (because space is a character)

str1="HelloWorld"
print(str1.isalpha())

OP:true

Purpose:
Say,to check wether the name entered by the user is valid or not..
A valid name should have only alphabets but not numbers and special symbols.

==============isdigit()================
isdigit() returns true if all the characters of a string are digits.

str="hfdgkjfdhg"
print(str.isdigit())
False
str="hfdgkjfdhg123"
print(str.isdigit())
False
str="45435435435h"
print(str.isdigit())
False
str="45435435435"
print(str.isdigit())
True

Purpose:
Say,to validate a mobile number.It should have only digits.
==============isalnum()===========

isalnum() returns true if all the characters of a string are 1)numbers or


2)alphabets or
3)Combination of both

But the string should not contain any special symbols like @, space, etc.

a="Hello world"

print(a.isalnum())

OP:False #because space is there

>>> str1="3flgkld"
>>> print(str1.isalnum())
True

str2="356546"
>>> print(str2.isalnum())
True
Purpose:
Say,to validate the employee Ids ...If an employee id is having special symbol,i
will not
treat that as a valid one.

=========isupper()=====================
isupper() returns true if all the alphabets of a string are in upper case.

str1="HELLO"
print(str1.isupper())
OP:
True

str5="H78"
print(str5.isupper())
True

str="Hello"
print(str.isupper()) #False

Purpose:
Say, i have stored all the names of the files available in my computer in a
notepad.
I want to get the files(file names) which have all the characters as capital.
=========islower()=====================
islower() returns true if all the alphabets of a string are in lower case.

a='hello'
print(a.islower())
OP:True

a='Hello'
print(a.islower())
OP:false

a="hkh6767"
print(a.islower())
OP:
True

a="6767"
print(a.islower())

Op:
False

Purpose:
Say, i have stored all the names of the files available in my computer in a
notepad.
I want to get the files(file names) which have all the characters as small.

===================endswith()============
endswith() will return true if the string is ended with the specified character.
Characters are case sensitive.
b='Hello World'
print(b.endswith('d'))
OP:
True

Purpose:
Say, i want to get all the employee names in a file that are going to end with "d".

=====================startswith()=================
startswith() will return true if the string is started with the specified
character.

b='Hello World'
print(b.startswith('H'))

OP:
True

Purpose:
Say, i want to get all the employee names from a file that are going to start with
"H".

So,
These boolean functions are used to validate the inputed data.
Let us say,the user entered a mobile no.We can validate it using
isdigit().

Enter your mobile number


mNo=989898989s

mNo.isdigit() #false

If the user enters a valid no. then only i will perform the required
logic/operations.

Purpose:

To get the required data from the existing data.

Also, these boolean functions are used to validate the user input.

=============Type casting===================

Type Casting:

Type : Data type


Casting : Conversion

Type Casting:
Converting the value of one datatype into the value of another datatype is called
as type casting.
If we want to convert a value to an integer,then we will use int().
If we want to convert a value to float,then we will use float().
If we want to convert a value to a string,then we will use str().

Into what type we want to convert that function we will use.

We can convert between different data types by using different type conversion
functions like int(), float(),str() etc.
=============
a=10
print(type(a)) #int
b=float(a)
print(b)#10.0
print(type(b)) #float

=============
a=float(10) #int---->float
print(a) #10.0
print(type(a)) #float

=============
print(float(5)) #int -- float 5.0

==============
print(int(10.6)) #float ---int 10

print(int(-10.6)) #-10
=================
Conversion to and from string must contain compatible values.

print(float('2.5'))#String---->float #2.5

====================
a= float('2.5')
print(a) #2.5
print(type(a)) #float

==============
print(str(25)) #int --- string '25'
===============

int('John') #str--->int

Traceback most recent call last):


File "<string>", line 301, in runcode
File "<interactive input>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '1p'
We cannot convert one sequence to another.

Purpose:

Let us say we want to validate an integer data say mobile no.


In a mobile number all the characters must be digits.
So,we will apply isdigit().But,isdigit() can be applied only to string
data.So, in that case, i need to convert that number from int type top string type
in order to apply isdigit() on it.

a=98909890
#print(a.isdigit()) #error.....You cannot apply this method to an integer type
value
b=str(a)
print(b.isdigit())

Like that in many contexts we will use this casting.

=============Accepting input from the user==================

Accept two values from the user and add them.

input() is a function that is used to accept input from the user.

input() will take every thing as a string.

num1 = input('Enter the first number: ') #"2"


num2 = input('Enter the second number: ') #"4"
num3=num1+num2
print(num3)

Output:
Enter the first number: 2
Enter the second number: 4
24

2 and 4 were concatenated but not added.

So,convert the str values to int values.

code:
num1 = int(input('Enter the first number: ')) #"2"
num2 = int(input('Enter the second number: ')) #"4"
num3=num1+num2
print(num3)

=====================================================
Accept different types of inputs from the user:

age = input('Enter your age ')#Accepting an integer


print("Your age is",age)
print(type(age))

package=input('Enter your package ')#Accepting a decimal value


print("Your package is",package)
print(type(package))

gender = input('Enter your gender ')#Accepting a character


print("Your gender is",gender)
print(type(gender))

name=input('Enter your name ')#Accepting a string


print("Your name is",name)
print(type(name))
====================================
In 3.6 and above,to accept all types of values,we use input()

But, in 2.7 to accept integers and decimals, we use input() and to accept the
strings,we will use raw_input().

input()--->integers and decimals


raw_input()---->String

Ex:

name=raw_input("Enter your name")

====================Literals=========================
Literal:

Value assigned to a variable.

a=10

we can call 10 as an integer literal

b=2.3

We can call 2.3 as a float literal

c=True

We can call True as a bool literal

s="Anushka"
s='Anushka'
s='''Anushka'''

We can call Anushka as a string literal.

===========Types of String literals=========================

There are two types of Strings supported in Python:

a)Single line String- Strings that are terminated within a single line are known as

Single line Strings.

Eg:

text1='hello'
text1="hello"
text1='''hello'''

b)Multi line String- A piece of text that is spread along multiple lines is known
as Multi line String.

Ex:

Hello how
are
you

There are two ways to create Multiline Strings:

1)By using \ and (\ is called as the line continution character)


2)By using ''' ''' (Triple quotes)

1)By using \ and (\ is called as a line continuion character):

If i want to write the content in the next line,then terminate the


current line by putting \ at the end of the line

===============================

text1='Hello \
user'
print(text1)

op:Hello user

2)By using ''' '''(Triple quotes):

To print the String as it is,we have to use ''' '''(Triple quotes)

str2='''welcome
to
SSSIT'''

print(str2)

op:
welcome
to
SSSIT

=================================

name='Anushka \
Akhil'
print(name)

name2='''Harika
Kotha
Vipra'''

print(name2)

===============Operators================
Operator:
An operator will perform operations.

Operand:
Upon what we are going to perform operation,they will become operands.

c=a+b
+ as operator

a,b ----->Operands

Types of operators:

1)Arithmetic operators:
Operators Description

+ To perform addition
- To perform subtraction
* To perform multiplication
/ To perform division(quotient with decimal part)
% To return remainder after division(Modulus)(Remainder will be the answer)
// Perform Floor division(quotient without decimal part)
** Perform exponent(raise to power)

eg:

>>> 10+20
30

>>> 20-10
10

>>> 10*2
20

>>> 10/3
3.3333333333333335

>>> 2**3 (2 power 3)


8

>>> 10%3 (Remainder)


1

>>> 10/3 (quotient with decimal part)


3.3333333333333335

>>> 10//3 (quotient without decimal part)


3
>>>

2)Relational Operators:
Operators Description
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
== Equal to (comparision operator)
!= Not equal to

They will tell the relation between two entities as true or false.
eg:

>>> 10<20
True
>>> 10>20
False
>>> 10<=10
True
>>> 20>=15
True
>>> 5==6
False
>>10==10
True

>>> 5!=6
True

3)Assignment Operators:
Operators Description
= Assignment
/= Divide and Assign
+= Add and assign
-= Subtract and Assign
*= Multiply and assign
%= Modulus and assign
**= Exponent and assign
//= Floor division and assign

eg:

>>> c=10
>>> c
10
>>> c+=5 (c=c+5)
>>> c
15
>>> c-=5
>>> c
10
>>> c*=2
>>> c
20
>>> c/=2
>>> c
10
>>> c%=3
>>> c
1
>>> c=5
>>> c**=2 #c=c**2
>>> c
25
>>> c//=2
>>> c
12
>>>

4)Logical Operators:
Operators Description
and Logical AND(When all the conditions are true then the result will be
true)
or Logical OR (If atleast one condition is true then the result will be
true)
not Logical NOT(Compliment the result i.e., reverse)

and:

If all the input bits(a,b) are 1 ,then the result is 1.Else,the result is 0.

a b a and b
1 0 0
0 1 0
1 1 1
0 0 0

or:

If atleast one input bit is 1,then a or b will become 1

a b a or b
1 0 1
0 1 1
1 1 1
0 0 0

not:
Negation / reverse

print(not(8==8))
not(1)

false

output:
false

True--->1
False-->0

==============================
a=5>4 and 3>2 #1 and 1 =1
print(a)
b=5>4 or 3<2 # 1 or 0 =1
print(b)
c=not(5>4) # not(True)
print(c)

output:
True
True
False

Membership Operators:
Operators Description
in Returns true if a variable's value is in the sequence ,else false.
not in Returns true if a variable's value is not in the sequence ,else
false.

eg:

in:
a=[1,2,3,4]
b=3

print(b in a) #true

not in:
a=[1,2,3,4]
b=3

print(b not in a) #False

Identity Operators:
Operators Description
is Returns true if identity(addresses) of two operands are same, else
false.

is not Returns true if identity(addresses) of two operands are not


same, else false.

Ex:

is:

a=20
b=20

print(a is b) #true

is not:
a=20
b=20
print(a is not b)#False

Unary operator:
Will be applied only on single operand

a=10
print(-a) #-10

Bitwise Operators:

1)Bitwise complement(~)
Always 2s complement compiler will print

2S complement= -(N+1)

a=4
print(~a) # -5

2)Bitwise And(&):

8421 code:
a=13
b=5
print(a&b)#5

13---->1101
5----->0101
------------
13&5-->0101--->5

3)Bitwise Or(|):

a=13
b=5
print(a|b)#13

13---->1101
5----->0101
------------
13|5-->1101--->13

4)Leftshift(<<) operator:

a=4

print(a<<2) #16

Formula:

x*2^y

Here x=4 and y=2

So, 4*2^2=4*4=16

5)Right shift(>>) operator:

a=4

print(a>>2) #1
Formula:

x/2^y

Here x=4 and y=2

So, 4/2^2=4/4=1

5)XOR(^):

If both the bits are same,false will be returned

a b a ^ b
1 0 1
0 1 1
1 1 0
0 0 0

a=5>4 ^ 3>2 #1 ^ 1
print(a) #False

==================Control instructions====================

Controls the flow of execution.


That means they will determine the order in which the instructions have to be
resolved.

---
---
---
---
---

---->Sequence control

---->Decision control

---->if(pure if)
---->if-else
---->if-elif /if-else ladder
---->Loop control
---->for
---->while
---->for-else
---->while-else

========Sequence Control instructions=============

In which order we do write the instructions,if in the same order the instructions
are getting executed,then they are called as sequence control instructions.

-----------
-----------
-----------
-----------
-----------
-----------

=================Decision control instructions======================


Depending on the condition,we will decide wether to execute or skip a set of
instructions.

1)if/simple if/pure if:


The if statement in python is same as c language which is used test a condition. If
the condition is true, statements of if block will be executed otherwise they is
skipped.

Syntax of python if statement:

---
---
if(condition):
statements
---
----

Example of if statement in python


===================================
a=10
if a==10:
print("Hello User")
print("End of program")

Output:

Hello User
End of program
===================================

age=int(input("Enter your age:"))

if age>=22:
print("eligible for marriage")
print("All the best")
print("Done")

===============================
num = 3

if num > 0:

print(num, "is a positive number.")


print("This is always printed.")

num = -1
if num > 0:

print(num, "is a positive number.")

print("This will also be printed.")


print("Done")

op:
(3, 'is a positive number.')
This is always printed.
Done

2)if else:

Syntax:

if condition:
statements
else:
statements

If the condition is true, the instructions of "if block" will be executed.


If the condition is false, the instructions of "else block" will be executed.

===================
num =3

if num >= 0:
print("Positive or Zero")
else:
print("Negative number")

op:Positive or Zero

===================
year=2000
if year%4==0:
print("Year is Leap")
else:
print("Year is not Leap")

Output:
Year is Leap

3)if else ladder/if elif:


If we need to check for multiple conditions,then we use if elif .

This statement is like executing a if statement inside a else statement.

Syntax:

if condition:
statements
elif condition:
statements
elif condition:
statements
elif condition:
statements
else:
statements
--
--
--

======================
if condition:
# logic 1
elif condition:
# logic 2
elif condition:
# logic 3
elif condition:
# logic 4
else:
# logic 5
--
--
--

Examples:

===================Determining the grade====================


marks=int(input("Enter the marks:")) #36

if marks>=90:
print("Grade A")

elif marks>=80:
print("Grade B")

elif marks>=70:
print("Grade C")

elif marks>=60:
print("Grade D")

else:
print("Failed")

print("Done")

=====================
num = 3.4

if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")

op:Positive number
=======================
a=10
if a>=20:
print("Condition is True")
elif a>=15:
print("Checking second value")
else:
print("All Conditions are false")

op:All Conditions are false


==================nested if====================
Nesting:
One inside another is called as nesting.
"if" inside another "if" is called as nested if

if condition:
-----
-----
if condition:
-----
-------
else:
-------
-------

else:
----
----

==================
num = int(input("Enter a number: ")) #10
if num >= 0:
if num == 0:
print("Zero")
else:
print("Positive number")
else:
print("Negative number")
op:
Enter a number: 10
Positive number

===================
a=10
if a>=20:
print("Condition is True")
else:
if a>=15:
print("Checking second value")
else:
print("All Conditions are false")

Output:
All Conditions are false.

=================User details validation===============


print(" personal details".strip().title()) #strip() -->To remove unwanted
spaces
#title()-->To put every word
starting
#letter as capital
first_name=input("Enter your first name ")
last_name=input("Enter your last name ")

full_name=first_name+last_name

print(full_name)

num=input("enter mobile number\n")


#print(type(num))
if (len(num)) != 10:
print("invalid mobile number")
elif num.isdigit()== False:
print(" invalid mobile number")
else:
print(" valid mobile number")

===================
age=int(input("Enter your age "))#29
gender=input("Enter your gender")#f
qua=input("Enter your qualification")#MBA

if(age<=30 and gender=="F"):


if (qua=="M.Tech" ):
print("2000 rupees")
elif (qua=="B.Tech" ):
print("1000 rupees")
else:
print("500 rupees")
else:
print("No con in the fee")

print("thanks")

===================
age=int(input("Enter your age "))
gender=input("Enter your gender")#f
qua=input("Enter your qualification")#mtech

if(age<=30 and gender.upper()=="F"):


if (qua.upper()== "M.TECH" or qua.upper()=="MTECH"):
print("2000 rupees")
elif (qua.upper()=="B.TECH" or qua.upper() == "BTECH"):
print("1000 rupees")
else:
print("500 rupees")
else:
print("No con in the fee")

print ("thanks")

MTECH
M.TECH
mtech
m.tech

=========Loops================

If you want to repeatedly execute a set of statements just by writing them for
once,then you can use loops.

Types:

1)for
2)for else
3)while
4)while else

========================for loop==================

for loop is used to iterate over a sequence of values.

Syntax:

for variable in sequence:


------
------
------ # Instructions that have to be executed repeatedly
------
------

========To print 1 to 10 numbers=======


for n in range(1,11): #11 means,upto 10 will be considered

print(n)

=======To display table of numbers========


num=2

for a in range (1,6):


print(num * a)
========Program to find sum of Natural numbers from 1 to 10==========

sum=0
for n in range(1,11):
sum=sum+n
print(sum)

=============================
# Program to find the sum of all numbers stored in a list

# List of numbers
numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]
sum = 0
for val in numbers:
sum = sum+val
print("The sum is", sum)

op:
The sum is 48

===========More about range() ==========================

range(StartingPoint,EndingPoint,Step)

0 is the default value for StartingPoint


1 is the default value for Step

for i in range(10): #This is similar to range(0,10,1).From 0 to 9 print the values


#with the increment value 1
print(i)

output:0 to 9

for i in range(10,20):
print(i) #Prints 10 to 19 values

for k in range(1,20,3):
print(k) #Prints 1 to 19 values with the increment value 3

for i in range(30,10,-3):
print(i)

Output:
30
27
24
21
18
15
12

======Write a python script accept a string and find length of the string without
using len()====

x=input("Enter a string :")#Harika

cnt=0
for i in x :
cnt=cnt+1
print("Length of ",x," is : ",cnt)

====Write a python script accept a string and count no.of vowels in a given
string===

x=input("Enter a string :")


cnt=0
for i in x : #Harika
if i in "aeiouAEIOU" :
cnt=cnt+1
print("Total no of vowels in ",x ,"is : ",cnt)

========================================================
x = input("Enter a string: ")
cnt = 0
for i in x:
if i.isalpha() and i not in "aeiouAEIOU":
cnt += 1
print("Total number of consonants in", x, "is:", cnt)

====== Write a python script print even numbers from 2 to 100 ==========

for i in range(2,101,2) :
print(i)

========= Write a python script to print odd numbers from 99 to 1 =================

for i in range(99,0,-2) :
print(i)

========To add 10 to all the values in a list==========

a=[1,2,3,4]

for i in a:
i=i+10
print(i)
(or)

a=[1,2,3,4]
b= [(i+10) for i in a]
print(b)

-Note:

for i in a ---->First this will be executed


(i+10)--------->This will be executed secondly

===========To print odd and even numbers from a list==========

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

for i in x:
if(i%2==0):
print("The number",i,"is even")
else:
print("The number",i," is odd")

=============================================================

x=input("Enter a string :")


cnt=0
for i in x :
if i in "aeiouAEIOU" :
cnt=cnt+1
print(i)
print("Total no of vowels in ",x ,"is : ",cnt)

==================for-else================
A for loop can have an optional else block as well. The else part is executed if
the items in the sequence used
in for loop exhausts.That means,after completing the execution of for,the cursor
will go to else part and will
execute the instructions under that else part.But,in a loop,if break statement is
used,else part will never be executed.
break statement can be used to stop a for loop. In such case, the else part is
ignored.
Hence, a for loop's else part runs if no break occurs.
===============================
Syntax:

for variable in sequence:


statements
else:
statements

Working:
After completely executing the loop, the cursor will go to the else part,execute
the instructions in the else part and then only the remaining instructions will be
executed.
(if "break" is not there in the for loop body)

If break is there in the for body, then the else part in the for else will not be
executed.
=========break=========
As soon as the cursor encounter the break
keyword,it will skip all the statements
after "break" and exits(comes out) of that
block in which break is written.

In the for body,if the "break" keyword is there,then the else part of for else will
not be executed.

Ex:

digits = [0, 1, 5]

for i in digits:
print(i)

else:
print("No items left.")

op:
0
1
5
No items left.
=======================
digits = [0, 1, 5]

for i in digits:
print(i)
break
else:
print("No items left.")
op:
0

=======If we write the program with out for-else..that is using normal if-else,
observe the problem========

=======Print the first even number in the list.If there is no even no. in the list,
print "Even no is not found"==========================

numbers=[1,3,4,5,6,7,8,9]

for i in numbers:
if(i%2==0):
print("Even no was found and it is",i)
break
else:
print("Even no has not found")
Op:
Even no is not found
Even no is not found
Even no was found and it is 4

========So use for else============


numbers=[1,3,4,5,6,7,8,9]

for i in numbers:
if(i%2==0):
print("Even no was found and it is",i)
break
else:
print("Even no has not found")

=============Nested loops============
Loops defined within another Loop is called Nested Loop.

When an outer loop contains an inner loop in its body it is called Nested Looping.
Syntax:

for <expression>:
for <expression>:
Body

eg:
==============to print 1 to 3 tables upto 10=================
for i in range(1,4):

for j in range(1,11):
print(i,"*",j,"=",i*j)

Note:
i=[1,2,3]
j=[1,2,3,4,5,6,7,8,9,10]

Output:
1 * 1 = 1

1 * 2 = 2

1 * 3 = 3

1 * 4 = 4

1 * 5 = 5

1 * 6 = 6

1 * 7 = 7

1 * 8 = 8

1 * 9 = 9

1 * 10 = 10

2 * 1 = 2

2 * 2 = 4

2 * 3 = 6
2 * 4 = 8

2 * 5 = 10

2 * 6 = 12

2 * 7 = 14

2 * 8 = 16

2 * 9 = 18

2 * 10 = 20

3 * 1 = 3

3 * 2 = 6

3 * 3 = 9

3 * 4 = 12

3 * 5 = 15

3 * 6 = 18

3 * 7 = 21

3 * 8 = 24

3 * 9 = 27

3 * 10 = 30

Purpose of nested loops:

If we have 10 files and in each file we need to perform some repeated operations,
then we can go for nested loops.
For performing operations on matrices(rows one loop variable,column one
loop variable).

=====using "end" keyword in the print statement=======


for i in range(10):
print(i,end=",")

output:
0,1,2,3,4,5,6,7,8,9,

for i in range(10):
print(i,end=" ")

output:
0 1 2 3 4 5 6 7 8 9

======
start = 10 # Change this value to adjust the start of the range
end = 50 # Change this value to adjust the end of the range

for num in range(start, end + 1):


if num > 1: # Prime numbers are greater than 1
is_prime = True
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
is_prime = False
break
if is_prime:
print(num)

========Using conversion string/format string in the print instruction=======

%d or %i --> integer
%s --> string,bool
%f ---> float

==================================
name = "ravi"
age = 24

print("student name is %s and age is %d" %(name,age))

=============================
name = "ravi"
age = 24
package=3.3
fact=False

print("student name %s and age is %i and package is %f and fact is %s" %


(name,age,package,fact))

=================while loop=============
while Loop is used to execute number of statements or body till the condition
passed in while is true.
Once the condition is false, the control will come out of the loop.

Syntax:

while condition:
Body

=============To print 1 to 10 numbers===========


a=1
while a<=10:
print("Value of a is",a)
a=a+1

=======================
a=10
while a>0:
print("Value of a is",a)
a=a-2
print("Loop is Completed")

Output:
Value of a is 10
Value of a is 8
Value of a is 6
Value of a is 4
Value of a is 2
Loop is Completed
==============================
n = 10
sum = 0
i = 1
while i <= n:
sum = sum + i
i = i+1 # update counter
print("The sum is", sum)

op:
('The sum is', 55)

==================while with else==============


That means,after completing the execution of while,the cursor will go to else part
and will execute the instructions under that else part.But,in a loop,if break
statement is used,else part will never be executed.
==============

while condition:
---
---
---
else:

---
----
---
counter = 0

while counter < 3:


print("Inside loop")
counter = counter + 1
else:
print("Inside else")
op:
Inside loop
Inside loop
Inside loop
Inside else
===================
counter = 0

while counter < 3:


print("Inside loop")
break
counter = counter + 1

else:
print("Inside else")

OP:
Inside loop
=========Write a python script to calculate the percentage of marks obtained by the
students using while loop====

more = True
while more==True:

name = input("Enter your name >>>")


maths_marks = float(input("Maths marks >>>"))
science_marks = float(input("Science marks >>>"))
english_marks = float(input("English marks >>>"))
comupter_marks =float(input("Computer marks >>>"))
total = maths_marks+science_marks+english_marks+comupter_marks
# using 400.0 to get faction value else if total will be less than 400(and
mostly it will be)#then it will #be 0
percentage = (total/400.0)*100
print( name,", your total marks is",total,"and your percentage
is",percentage)

#User have to enter y if he want to run it again


a =input("Want to enter more y/n >>>")#n
if a == "n":

more = False

========Python script to display the values 1,2,3 only by using while and break
combination =============
i = 1
while i < 6:
print(i)
if (i == 3):
break
i =i + 1
Purpose of for loop and while loop:

while---> if condition true then only it will entered

some tasks --> both loops can help

In python to read seqence datatypes "for" can be used , which we can't do in


"while".

=========break=========
As soon as the cursor encounter the break
keyword,it will skip all the statements
after "break" and exits(comes out) of that
block in which break is written.

===============================
for val in "string":
if val == "i":
break
print(val)

print("The end")

op:
s
t
r
The end

==========continue================
As soon as the cursor encounter the continue
keyword,it will skip all the statements
after continue and it will directly be
going to the condition.
of the loop.

================
for val in "string":
if val == "i":
continue
print(val)

print("The end")

op:
s
t
r
n
g
The end
============================
a=0
while a<=5:
a=a+1
if a%2==0:
continue
print a
print "End of Loop"

Output:
1
3
5
End of Loop

================pass=======================
In Python programming, pass is a null statement
We generally use it as a placeholder.

Suppose we have a loop or a function that is not implemented yet, but we want to
implement it in the future.
They cannot have an empty body. The interpreter would complain. So, we use the pass
statement to construct a body that does nothing.
=====================================
# pass is just a placeholder

# functionality to be added later.

sequence = {'p', 'a', 's', 's'}

for val in sequence:


++-
pass

==================Indexing and Slicing====================


Indexing:

Used to retrieve an element randomly from the sequence.

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

-5 -4 -3 -2 -1
10 20 30 40 50 =====>a[4],a[-1]==>50
0 1 2 3 4

The elements of a list will have two types of indices:


1)Positive index---->left to right---->Starts from 0

2)Negative index---->right to left---->Starts from -1

=================
To get 40
a[3]
a[-2]

20

a[1]=20
a[-4]=20
10
a[0]
a[-5]
=======================
Slicing:
To get a part of data from the sequence,we will use slicing.

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

Two slice operators are available:


1) ::
2) :

Printing::Leaving

Printing:Printing

::Leaving

:: ====>Leaving the values or printing the values :

::x ===>Leave the (x-1) values from the beginning


::-x ===>Leave the (x-1) values from the ending

a=(10,20,30,40,50,60)

print(a[::-2])#From ending,leave 1 value and print #(60, 40, 20)

=============================
print(a[::2])#From starting,leave 1 value and print #(10, 30, 50)
print(a[::3])#From starting,leave 2 values and print #(10, 40)
print(a[::-3])#From ending,leave 2 value and print #(60, 30)
print(a[::-1])

a=(10,20,30,40,50,60)

-x:: ====> From x(x is the index),print the values till end
x:: ====> From x,print the values till end

print(a[-4::])#From -4,it will print the values till end #(30,40, 50, 60)
print(a[4::])#From 4,it will print the values till end#(50, 60)
print(a[-2::])

Printing:Printing

a[Starting INDEX : Ending INDEX]


a=[10,20,30,40,50,60]
print(a[1:5])#From 1 to 4,the values will be printed #20,30,40,50

print a[-3:]#From -3,till end,all the elements will be printed #(40, 50, 60)
print a[-3::]#From -3,till end,all the elements will be printed #(40, 50, 60)
#If we put value(say -3:) before :: or : ,there is no difference because the
elements
will be printed till end.

print a[:3]#From starting to 2nd index,values will be printed#(10,20,30)


print a[::3]#From starting,it will leave 2 values and prints#(10,40)

#If we put value(say :3) After :: or :,there is difference as shown above.


============================
Ex1:To get the student address age and marks
student=[101,"John","US",23,"78","Computers"]

address,age,marks

print(student[?:?])

======Predict the output of the following script=====================


a=[10,20,30,40]
for i in a[0:3]:
print(i)
======Predict the output of the following script=====================
a=[10,20,30,40]
for i in a[::-2]:
print(i)

======Predict the output of the following script=====================


a=[10,20,30,40]
for i in a[:]:
print(i)

============To convert the words in the list into uppercase=================


Ex2:

dataset = ['python','java','perl']

for i in dataset:
print(i.upper())

output:

PYTHON
JAVA
PERL
==========To convert each word first letter into uppercase============
Ex3:

dataset = ['python','java','perl']
for i in dataset:
print(i[0].upper()+i[1:])

Python
Java
Perl

====================WAP print whatever elements ending with 's' character==========

x=['unix','linux','perl','python','java','perl','aws','linux','devops']

for i in x :
if i[-1] in "Ss" :
print(i)
=====================Special Data types========================

1)List
2)Set
3)Tuple
4)Dictionary

Indexing:

a=[10,20,30,40]

Consider the above list....

Negative index
<--------------------------
-4 -3 -2 -1

10 20 30 40

0 1 2 3
---------------------------->Positive index

Ex:
a=[10,20,30,40]

print(type(a))#list

print(a[2]);#30
print(a[0]);#10
print(a[-2]);#30
print(a[-4]);#10

======================List====================

1)Indicated by [] .

2)List is a collection of heterogeneous/homogeneous elements.


Ex:
b=["1001AB","Peter",35,"Hyd",18.9]
print("The details of our tutor")
print(b[3])

3)List elements are mutable(modifiable).


Ex:
a=[10,20,30,40]

a[1]=200 #Modifiying
print(a)#[10, 200, 30, 40]

a.append(50)
print(a)#[10, 200, 30, 40, 50]

a.remove(200) #will take the value to be removed but not the index
print(a)#[10, 30, 40, 50]

4)Lists are ordered.


It will take the values in the same order that we give.
Ex:
a=[10,20,30,40]
print(a)

output:
[10,20,30,40]

5)x=[] #empty list

6)Allows duplicates.
a=[1,2,3,4,3]
print(a) #[1, 2, 3, 4, 3]

================================
append() and extend() :
Both the methods are used to concatenate the values to the list.

a=[1,2,3,4]
a.append(5) #To append only one value
print(a)#[1,2,3,4,5]

a=[1,2,3,4]
b=[6,7,8,9]
a.extend(b)#To append multiple values
print(a)#[1,2,3,4,6,7,8,9]

=======================================
remove() and del

a=[1,2,3,4]
a.remove(3)#remove() directly takes the value to be removed
print(a)#1,2,4

b=[1,2,3,4]
del b[2]#del will takes the index of the value to be removed
print(b)#[1,2, 4]

b=[10,20,30,40]
del b[:] #removes all the elements in b by leaving the object b
print(b) #[]

del b #removes the object b from the memory


#print(b) #name 'b' is not defined
a=[10,20,30,40,50,60,70]
del a[2:5]
print(a)

=============================
append() and insert():

append() can insert a value at the end of the list by default.


insert() can insert a value at an index specified.

a=[1,2,3,4]
a.append(5)#To add a value at the end
print(a)

a=[10,20,30,40]
a.insert(2,300)#insert(index,value)
print(a)#[10, 20, 300, 30, 40]

=============================
pop():

a=[1,2,3,4]
a.pop()#Removes the last value in the list by default
print(a)#[1, 2, 3]

b=[1,2,3,4]
b.pop(0) #Removes the value at the specified index
print(b)#[2, 3, 4]

===========================
count(): To count the no of occurences of a specified value.
a=[1,2,3,4,2,3,5,2,2]
print(a.count(2))#4
print(a.count(12))#0

===========================
reverse():
a=[10,20,30,40]
a.reverse()
print(a)#[40,30,20,10]

============sort()==================
a=[1110,200,130,40,50,60]
#To print the list elements in the ascending order,we have to apply sort().
a.sort()
print(a)#[40, 50, 60, 130, 200, 1110]

#To print the list elements in the descending order,we have to apply
#sort() and then reverse()

a=[1110,200,130,40,50,60]
a.sort()
a.reverse()
print(a)#sort() will modify the source copy

output:
[1110, 200, 130, 60, 50, 40]
===========sorted()=======================
#Directly printing the list elements in the descending order using
#sorted()
c=[10,2,30,1]
d=sorted(c,reverse=True) #Sorted() will never change the source.To store
#the sorted values,one more object is required.
print(d)

print(c)

===================================================
index(VALUE):
a=[10,20,30,40]
print(a.index(20))

output:
1

==============
max(),len(),sum(),min()

a=[10,20,30,40]
print(len(a)) #4
print(max(a)) #40
print(min(a)) #10
print(sum(a)) #100

==========loops with list===========


x=["Coffee","Tea","Milk"]
for i in x:
print(i)

output:
Coffee,Tea,Milk

x=[10,20,30]
for i,j in enumerate(x):
#print(i)
#print(j)
print(i,j)

output:
0 10
1 20
2 30

x=[10,20,30]
for i,j in enumerate(x):
#print(i)
#print(j)
print(i+1,j)

output:
1 10
2 20
3 30

==============================
Concatenation:

a=[10,20,30]
b=[100,200,300]
c=a+b #A new list object will be created that has the data of both the lists
print(c)

Output:
[10, 20, 30, 100, 200, 300]
=====================

a=[10,20,30]
b=[100,200,300]
c=a[0]+b[0]
print(c)

output:
110

===========================
Repitition Operator:
==================
a=12
b=a*3 #int*int
print(b) #36
======================
a="12"
b=a*3 # str*int
print(b)#121212

=========Principle====
int*int===>Multiplication
str*int===>Repetition

=======================

a="#"*40
print(a)

print("Student details")
print("-"*40)
output:

Student details
##################################################

======================================

List comprehension:

x=[i*i for i in range(1,101)]


print(x)
Output:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256,
289, 324, 361, 400, 441, 484, 529, 576, 625, 676, 729, 784, 841, 900,
961, 1024, 1089, 1156, 1225, 1296, 1369, 1444, 1521, 1600, 1681, 1764,
1849, 1936, 2025, 2116, 2209, 2304, 2401, 2500, 2601, 2704, 2809, 2916,
3025, 3136, 3249, 3364, 3481, 3600, 3721, 3844, 3969, 4096, 4225, 4356,
4489, 4624, 4761, 4900, 5041, 5184, 5329, 5476, 5625, 5776, 5929, 6084, 6241, 6400,
6561, 6724, 6889, 7056, 7225, 7396, 7569, 7744, 7921,
8100, 8281, 8464, 8649, 8836, 9025, 9216, 9409, 9604, 9801, 10000]

==========================================

x=[i*i for i in range(1,101) if i%2==0]


print(x)

output:
[4, 16, 36, 64, 100, 144, 196, 256, 324, 400, 484, 576, 676, 784,
900, 1024, 1156, 1296, 1444, 1600, 1764, 1936, 2116, 2304, 2500, 2704,
2916, 3136, 3364, 3600, 3844, 4096, 4356, 4624, 4900, 5184, 5476, 5776,
6084, 6400, 6724, 7056, 7396, 7744, 8100, 8464, 8836, 9216, 9604, 10000]

#========List comprehension==========

#a=[10,20,30,30,20,40,10,50]
# list=[]
# [list.append(i) for i in a if i not in list]
# print(list)

# newlist=[x for x in range(10) if x<5]


# print(newlist)

# fruits=["apple","banana","cherry","kiwi","mango","apple"]
# newlist=[x for x in fruits if x!="apple"]
# print(newlist)

# fruits=["apple","banana","cherry","kiwi","mango"]
# newlist=[x.upper() for x in fruits]
# print(newlist)

fruits=["apple","banana","cherry","kiwi","mango","banana"]
newlist=[x if x!="banana" else "orange" for x in fruits]
print(newlist)

fruits=["apple","banana","cherry","kiwi","mango","banana"]
newlist=['hello' for x in fruits]
print(newlist)

===================WAP print whatever elements ending with 's' characters=======

====WAP program whatever elements length more than 5 characters=========


x=['unix','linux','perl','python','java','perl','aws','linux','devops']

for i in x :
if len(i)>5 :
print(i)
====WAP program whatever elements begining with vowel charactes======

x=['unix','linux','perl','python','java','perl','aws','linux','devops']

for i in x :
if i[0].lower() in "aeiou" :
print(i)

=========WAP accept a element and remove the given element from a lists without
using remove() method============

x=[100,20,503,3,35,600,73,5,200,400,200,56,10,20,9,1801,300,45678,90]
n=int(input("Enter a number to remove : "))#56
y=[]

for i in x:
if i!=n :
y.append(i)

print("After removing ",n,"number form list :",y)

==============To print the list elements using spaces and also in different
lines========
a = [1, 2, 3, 4, 5]

# printing the list using * operator separated


# by space
print(*a)

# printing the list using * and sep operator


print("printing lists separated by commas")

print(*a, sep = ", ")

# print in new line


print("printing lists in new line")

print(*a, sep = "\n")


Output:

===============================Set=============================================

1)Sets can also store both similar and dissimilar type of elements.
2)Set is denoted using {}.

Ex:
a={1,2,3,4,3}
print(type(a)) #set

3)It is unordered.(Stores the data in the random order)


a={10,2,30,4,3}
print(a)

output:
{2, 3, 4, 30,10}

4)It will not allow duplicates.


a={10,20,30,10,30,30,30}
print(a) #{10, 20, 30}

5)Indexing will not be there for the data inside the sets.
That means,
Item indexing,assignment,deletion is not possible.

a={100,92,3,4,3,50}

print(a[2])#Set object does not support indexing

#a[1]=920#set' object does not support item assignment


print(a)

del a[-1]#set' object doesn't support item deletion


print(a)

6)We can add the elements to a set.


a={12,34,1,2,3,6,9}
a.add(2) #No append() #adding at a particular index is aslo not possible
a.add(10)
print(a)#{1, 34, 3, 2, 6, 9, 10, 12}

7)

We can perform mathematical operations on a set.


=========================
union --> |

intersection --> &

minus ---> -

Symmetric difference ---> ^


=========================
1)Union(|)
| ===>Combines both the sets but will not print the duplicate values.

a={10,20,40,60}
b={10,30,40,50}
print(a|b)

output:
{40, 10, 50, 20, 60, 30}

Intersection (&) :
It will print the common values.
a={10,20,40,60}
b={10,30,40,50}
print(a & b)

output:
{10,40}

minus:

a-b means print the contents in a which are not in b.


a={10,20,40,60}
b={10,30,40,50}
print(a - b)

output:
{20, 60}

b-a means the contents of b which are not in a will be printed


a={10,20,40,60}
b={10,30,40,50}
print(b - a)

output:
{50, 30}

Symmetric difference (^):

a^b = (a-b)|(b-a) #{20, 60}|{50, 30}

a={10,20,40,60}
b={10,30,40,50}
print(a ^ b)

output:
#{50, 20, 60, 30}

To remove duplicates from a list:


a=[10,10,30,30,10,40,40,20,10,50,50,30]
print(type(a)) #list
x=set(a)
print(x)
print(type(x))
y=list(x)
print(y)
print(type(y))

output:
<class 'list'>
{40, 10, 50, 20, 30}
<class 'set'>
[40, 10, 50, 20, 30]
<class 'list'>

Sets will not support sort().Then how to perform sorting on set values??
a={100,10,200,20,30}
b=list(a)
print(type(b))#list
b.sort()
print(b)
b.reverse()
print(b)
b=set(b)
print(type(b))

output:
<class 'list'>
[10, 20, 30, 100, 200]
[200, 100, 30, 20, 10]
<class 'set'>

== Take the list x and take the list y and put all the common elements from x and
y into a list z==

x=['unix','linux','perl','python','java','perl','aws','linux','devops']

y=['c','c++','unix','python','dba','.net','aws']

z=list(set(x) & set(y))


print(z)

===WAP take x list and y list and display all the elements from both the lists just
for once===============

x=['unix','linux','perl','python','java','perl','aws','linux','devops']

y=['c','c++','unix','python','dba','.net','aws']

z=list(set(x) | set(y))
print (z)

======================Tuple==============================
Lists---->ordered,allows duplicates,supports indexing,mutable
Sets---->Unordered,does not allow duplicates,will not support indexing,mutable(we
can add using add())
Tuples--->ordered,allows duplicates,supports indexing,immutable(same as lists
except mutability)

==========================================================
1)
Tuple is also a collection of both similar or dissimilar types.

2)
Tuple is indicated using ().
a=(10,20,30)
print(type(a)) #tuple

Examples:
1. a=(10,20,30,40,50,60)
2. b=(10,2.3,"unix")
3. days=("sun","mon","tue","wed","thu","fri","sat")
4. x=(10) # int
5. y=(10,) # tuple

3)
It is same as list but elements are immutable.

So,tuples will not support item assignments because they are immutable
a=(10,20,30)
print(type(a))
a[1]=40 # Not possible
print(a)

#TypeError: 'tuple' object does not support item assignment

a=(10,20,30)
del a[1]

tuple' object doesn't support item deletion

a=(10,20,30,40,50,60)
print(a[2])
print(a[-1])

print(a[1:5])

del a[3] #Not possible as the tuple is immutable


print(a)

#TypeError: 'tuple' object doesn't support item deletion

a=(10,20,30,40,50,60)
a.append(70) #Not possible as the tuple is immutable

#'tuple' object has no attribute 'append'

================================
a=(10,20,30,40,50,60)
print(a.count(30))#1
print(a.index(30))#2
print(len(a))#6
print(max(a))#60
print(min(a))#10
print(sum(a))#210

==============================
a=(100,10,1,99,9)

print(sorted(a,reverse=True))

Output:
[100, 99, 10, 9, 1]

Note:
sort() is not supported by tuples

=================enumerate()==============
a=(10,20,30,40,50,60)
for i in a:
print(i)

output:
10
20
30
40
50
60

a=(10,20,30,40,50,60)
for i,j in enumerate(a):
print(i,j)#(0,10),(1,20),(2,30)

output:
0 10
1 20
2 30
3 40
4 50

a=(10,20,30,40,50,60)
for i,j in enumerate(a):
print(i+1,j)#(0,10),(1,20),(2,30)

output:
1 10
2 20
3 30
4 40
5 50
6 60
==================
x=("unix","perl","python","oracle","aws")
print(x,type(x))#('unix', 'perl', 'python', 'perl', 'oracle', 'aws') <class
'tuple'>
=================================================================
#Tuples are immutable.To make it mutable,change it to list

x=('unix','python', 'perl', 'oracle', 'aws')


x=list(x)
print(type(x))#list
x.append("Devops")
x.append("dJango")
x.remove("perl")#Removes the first occurance

print(x)

x=tuple(x)
print(x,type(x))

<class 'list'>
['unix', 'python', 'oracle', 'aws', 'Devops', 'dJango']
('unix', 'python', 'oracle', 'aws', 'Devops', 'dJango') <class 'tuple'>
=======================Dictionaries===========================
Dictionary is a collection of key value pairs. [] {} () {}

Ex:

{uid,pwd} =========>{Pinky,123456}
{State,Capital} =======>{Orissa,Bhuwaneswar}
{EmployeeId,EmployeeName} =====>{101,Pinky}

==================Dictionaries=====================================
1)It is indicated using {} .

2)It is a group key pair values.{Key1:Value1,Key2:Value2} --> {"Ap":"Hyd"} or


{"Username":"Password"}

Ex:

(username,password)
(States,Capitals)

Ex:
a={101:'Anushka',102:'Akhil'}
print(type(a)) #<class 'dict'>

3)The elements are mutable

4) It is an unordered list.(Random order)

5)Keys must be unique.

6)
d5={} # empty dictionary

Ex:
1. d1={'Ganesh':300000,'Hari':250000,'Sai':200000,'Lakshmi':300000}
2. d2={'AP':'Hyd','TN':'Chennai','KN':'Bangalore','UP':'Lucknow'}
3. d3={'a':97,'b':98,'c':99,'d':100}
4. d4={10:'Acc',20:'Sales',30:'IT',40:'Opeartions'}
5. d5={} # empty dictionary

========================
x={'Ap':'Hyd','TN':'Chennai','KN':'Banglore','UP':'Lucknow'}
print(x)
print(type(x))

============================================
To retrieve the value of a specific key

x={'Ap':'Hyd','TN':'Chennai','KN':'Banglore','UP':'Lucknow'}
print(x['TN'])#dict[key]
print(x['UP'])

output:
Chennai
Lucknow
==============================
To add a new key value pair into the dictionary
x={'Ap':'Hyd','TN':'Chennai','KN':'Banglore','UP':'Lucknow'}
x['MS']='Mumbai' #dic[newKey]=newValue
print(x)

output:
{'Ap': 'Hyd', 'TN': 'Chennai', 'KN': 'Banglore', 'UP': 'Lucknow', 'MS': 'Mumbai'}
============================================
Updating the value of a particular key

x={'Ap':'Hyd','TN':'Chennai','KN':'Banglore','UP':'Lucknow'}
x['Ap']='Amaravati' #x[key]=newValue
print(x)

output:
{'Ap': 'Amaravati', 'TN': 'Chennai', 'KN': 'Banglore', 'UP': 'Lucknow'}

=============================
Deleting a key value pair

x={'Ap':'Hyd','TN':'Chennai','KN':'Banglore','UP':'Lucknow'}
del x['KN']
print(x)

output:
{'Ap': 'Hyd', 'TN': 'Chennai', 'UP': 'Lucknow'}

==================

Deleting an object:
del x
#print(x)

============================
x={'Ap':'Hyd','TN':'Chennai','KN':'Banglore','UP':'Lucknow'}

print(x.keys())
print(x.values())
print(x.items())

output:
dict_keys(['Ap', 'TN', 'KN', 'UP'])
dict_values(['Hyd', 'Chennai', 'Banglore', 'Lucknow'])
dict_items([('Ap', 'Hyd'), ('TN', 'Chennai'), ('KN', 'Banglore'), ('UP',
'Lucknow')])

=================
x={'Ap':'Hyd','TN':'Chennai','KN':'Banglore','UP':'Lucknow'}
for i in x.keys():
print(i,"Capital is :",x[i])

output:
Ap Capital is : Hyd
TN Capital is : Chennai
KN Capital is : Banglore
UP Capital is : Lucknow
==============================
x={'Ap':'Hyd','TN':'Chennai','KN':'Banglore','UP':'Lucknow'}
for i,j in x.items():
print(i,"Capital is :",j)

========================================
copy():
To copy the contents of one dic to another dictionary.

x={'Ap':'Hyd','TN':'Chennai','KN':'Banglore','UP':'Lucknow'}
y=x.copy()
print(y)

=================================
x={'Ap':'Hyd','TN':'Chennai','KN':'Banglore','UP':'Lucknow'}
a={1:10,2:20,3:30}
a.update(x)#To add multiple kay,value pairs at a time
print(a)
print(x)

output:
{1: 10, 2: 20, 3: 30, 'Ap': 'Hyd', 'TN': 'Chennai', 'KN': 'Banglore', 'UP':
'Lucknow'}
{'Ap': 'Hyd', 'TN': 'Chennai', 'KN': 'Banglore', 'UP': 'Lucknow'}

===========To print the key value pairs in different lines===================


student_score = {'Ritika': 5,'Sam': 7,'John': 10,'Aadi': 8}
# Iterate over key/value pairs in dict and print them
for key, value in student_score.items():
print(key, ' : ', value)

=============================
TO DELETE THE ELEMENTS:

a={1:10,2:20,3:30}
a.clear()
print(a) #{}

=========================
TO DELETE THE OBJECT:
del a
#print(a)

=====================
x={i:i*i for i in range(1,101)}
print(x)

print(x[50])

output:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100, 11: 121, 12:
144, 13: 169, 14: 196, 15: 225, 16: 256, 17: 289, 18: 324, 19: 361, 20: 400, 21:
441, 22: 484, 23: 529, 24: 576, 25: 625, 26: 676, 27: 729, 28: 784, 29: 841, 30:
900, 31: 961, 32: 1024, 33: 1089, 34: 1156, 35: 1225, 36: 1296, 37: 1369, 38: 1444,
39: 1521, 40: 1600, 41: 1681, 42: 1764, 43: 1849, 44: 1936, 45: 2025, 46: 2116, 47:
2209, 48: 2304, 49: 2401, 50: 2500, 51: 2601, 52: 2704, 53: 2809, 54: 2916, 55:
3025, 56: 3136, 57: 3249, 58: 3364, 59: 3481, 60: 3600, 61: 3721, 62: 3844, 63:
3969, 64: 4096, 65: 4225, 66: 4356, 67: 4489, 68: 4624, 69: 4761, 70: 4900, 71:
5041, 72: 5184, 73: 5329, 74: 5476, 75: 5625, 76: 5776, 77: 5929, 78: 6084, 79:
6241, 80: 6400, 81: 6561, 82: 6724, 83: 6889, 84: 7056, 85: 7225, 86: 7396, 87:
7569, 88: 7744, 89: 7921, 90: 8100, 91: 8281, 92: 8464, 93: 8649, 94: 8836, 95:
9025, 96: 9216, 97: 9409, 98: 9604, 99: 9801, 100: 10000}

2500

=============================
x={i:i*i for i in range(1,101) if i%2==0}
print(x)

output:
{2: 4, 4: 16, 6: 36, 8: 64, 10: 100, 12: 144, 14: 196, 16: 256, 18: 324, 20: 400,
22: 484, 24: 576, 26: 676, 28: 784, 30: 900, 32: 1024, 34: 1156, 36: 1296, 38:
1444, 40: 1600, 42: 1764, 44: 1936, 46: 2116, 48: 2304, 50: 2500, 52: 2704, 54:
2916, 56: 3136, 58: 3364, 60: 3600, 62: 3844, 64: 4096, 66: 4356, 68: 4624, 70:
4900, 72: 5184, 74: 5476, 76: 5776, 78: 6084, 80: 6400, 82: 6724, 84: 7056, 86:
7396, 88: 7744, 90: 8100, 92: 8464, 94: 8836, 96: 9216, 98: 9604, 100: 10000}

===================================
#Creating single key with multiple values

x={'Ganesh':[101,'President',30000,10],
'Hari':[102,'Manager',25000,20],
'Lakshmi':[103,'Analyst',50000,30],
'sai':[104,'Programmer',20000,10]}
print(x)

print(x['Ganesh'])#To see the details of Ganesh


print(x['Lakshmi'])#To see the details of Lakshmi

print(x['Lakshmi'][2])#salary of Lakshmi
print(x['sai'][1])#Role of sai
print(x['Hari'][-1])#department of Hari

x['Ganesh'][2]=50000 #Updating the salary of Ganesh


print(x)
=================get()====================
details={101:'Satya',102:'harika',103:'Valli'}
print(details.get(101))#Satya
print(details.get(1001))#None
print(details.get(10003,'not found'))#not found

====Python script to create a dictionary that have courses and their respective
fees====

courses={}
print("To stop press 'Qq' : ")
while True :
cname=input("Enter a course name : ")#Q
if cname in "Qq" :
break
fee=input("Enter a fee : ")#25000
courses[cname]=fee
print(courses)

output:
To stop press 'Qq' :
Enter a course name : math
Enter a fee : 20000
Enter a course name : python
Enter a fee : 25000
Enter a course name : Q
{'math': '20000', 'python': '25000'}

============Script to store and see the player details=========

n=int(input("Enter the no. of. players:"))


player_datails={}

i=0
while(i<n):
player_name=input("Enter the player name ")
player_score=input("Enter the player score ")
player_datails.update({player_name:player_score})
i=i+1
print("Players details:",player_datails)

#To search for a particular player

player=input("Enter the player name to search")

if(player in player_datails.keys()):
print("player found")

else:
print("player not found")

================Differences in data structures=========================

'''
List:
[]
Allows duplicates
Ordered
Mutable
Supports indexing
Ex:
a=[10,20,30,40,50,60,60,20]
print a #[10, 20, 30, 40, 50, 60, 60, 20]
a.append(80)
print a#[10, 20, 30, 40, 50, 60, 60, 20, 80]

Set:
{}
Does not allow duplicates
Un ordered
Mutable
No indexing
Ex:
b={10,20,30,10}
print b #set([10, 20, 30])
b.append(80) #b.append(80)
#AttributeError: 'set' object has no attribute 'append'
print b

Tuple:
()
Allows duplicates
Ordered`
Immutable
Supports indexing
Ex:
a=(10,20,30,10)
print a #(10, 20, 30, 10)
a.append(80)
print a #a.append(80)
#AttributeError: 'tuple' object has no attribute 'append'

'''

Dictionary:
{}
Stores key value pairs
Duplicate keys should not be there
Un ordered
Mutable
Does not support indexing but if we consider a single key with multiple
values,these values have indices.

=============================Functions===========================
---
---
---
print("hello")
print("hai")
print("bye")

---
---
---
print("hello")
print("hai")
print("bye")
---
---
---
print("hello")
print("hai")
print("bye")
------
------
display()

Function:

A function is self contained block of instructions that


can be used any number of times any where in the program.

The main concept of function is


1. Easy to Develop
2. Easy to maintain
3. Reduces length code of the program.
4. It provides more readability .
5. Supports reuseabilty
6. Reduces cost of maintenance.

It have two parts namely:

1)Function definition/Reusable code


2)Function call

1)Syntax of function definition:

def functionName():
#Reusable code

Ex:

def display():
-----
-----
-----

2)Syntax for function call:

functionName()

Ex:

display()

==============================================================
1)Functions without parameters:
====================================
def sum():
a=10 #hard coding
b=20
c=a+b
print(c)
def sub():
a=10
b=20
c=a-b
print(c)
def mul():
a=10
b=20
c=a*b
print(c)
def div():
a=10
b=20
c=a/b
print(c)

print("Calculating the addition")


sum()
print("Calculated the addition successfully")
print("Calculating the subtration")
sub()
print("Calculated the subtraction successfully")
print("Calculating the multiplication")
mul()
print("Calculated the multiplication successfully")
print("Calculating the division")
div()
print("Calculated the division successfully")
print("Calculating the addition again")
sum()
print("Calculated the addition again successfully")

output:
Start of program
Going to calculate the sum
The sum is: 30
calculated the sum successfully
Going to calculate the multiplication
The multiplication is: 200
calculated the multiplication successfully
Going to calculate the subtraction
The sub is: -10
calculated the subtraction successfully
Going to calculate the division
The division is: 0.5
calculated the division successfully
Going to calculate the subtraction again
The sub is: -10
calculated the subtraction again successfully
==================================
Principle:
When the cursor encounters a function call,it will immediately go to the function
definition,executes the code in the definition and goes back to the next
instruction after the call as per the sequence.
=========================================

def hello() :
print('Hello good morning to all') #1
def bye() :
print("Bye. Have a lovely day") #2
def party() :
print("Welcome to gettogether party") #3
print("Hi") #4
hello()
party()
bye()
print("Done") #5

output:
Hi
Hello good morning to all
Welcome to gettogether party
Bye. Have a lovely day
Done

Passing parameters to a function:

Parameter:
Parameter is called as an extra information.
============================

def sum(): <----------------


---
---

sum()

==================
2,3
def sum(a,b): <----------------
---
---

sum(2,3)

=====================
2 3
def sum(a,b): <----------------
c=a+b
print(c) #5 30 300

sum(2,3)
sum(10,20)
sum(100,200)

x=int(input("Enter the first number"))#2


y=int(input("Enter the second number"))#1
sum(x,y) #sum(2,1)

x,y---->parameters/actual parameters
a,b---->formal parameters/arguments

====================
2,3 are called as parameters
Through function call call,we are passing parameters to the function
definition.

Ex:
==========================

def sum(a, b):


c = a + b
print(c)

sum(10, 20)
sum(100, 200)
sum(15, 29)

output:
30
300
44

2)Functions with normal parameters/arguments:

def sum(a,b):
c=a+b
print("The sum is:",c)

def sub(a,b):
c = a - b
print("The sub is:", c)

sum(9,9)
sub(9,9)

output:
The sum is: 18
The sub is: 0

==================================
def add(x,y) : #arguments
k=x+y
print ("Sum=",k)

a=int(input("Enter a number1 : "))#2


b=int(input("Enter a number2 : "))#3
add(a,b) #parameters
print("Done")

3)Functions with positional arguments

def f1(name,age) :

print('Hello ',name ,'Nice to meet you!, and you are ',age,' years old')
name=input('Enter a name : ')#Harika
age=input('Enter a age : ')#30
f1(name,age)
f1("hari",18)

op:
Enter a name : harika
Enter a age : 28
Hello harika Nice to meet you!, and you are 28 years old
Hello hari Nice to meet you!, and you are 18 years old

4)Functions with named or keyword arguments:

def f1(name,age) :

print('Hello ',name ,'Nice to meet you!, and you are ',age,' years old')

f1(18,"Anuska")
f1(age=18,name="Hari")
f1(age=21,name="sai")
f1(name="siva",age=18)

output:
Hello 18 Nice to meet you!, and you are Anuska years old
Hello Hari Nice to meet you!, and you are 18 years old
Hello sai Nice to meet you!, and you are 21 years old
Hello siva Nice to meet you!, and you are 18 years old

====================================
#accept a string and find string length

def strlen(x) : #harika


cnt=0
for i in x :
cnt=cnt+1
print("Length of ",x," is : ",cnt)

def str_vowels_cnt(x) :
cnt=0
for i in x :
if i in "aeiouAEIOU" :
cnt=cnt+1
print("Total no of vowels in ",x ,"is : ",cnt)

x=input("Enter a string :")


strlen(x)
str_vowels_cnt(x)

op:
Enter a string :harika
Length of harika is : 6
Total no of vowels in harika is : 3

5)Function with default arguments:


def f1(a,b=20,c=30):
print(' a is :',a,' and b is : ',b,' and c is : ',c)

f1(100)
f1(100,200)
f1(100,200,300)

a is: 100 and b is: 20 and c is: 30


a is: 100 and b is: 200 and c is: 30
a is: 100 and b is: 200 and c is: 300

==============================================

Without using default arguments:


===============================================
def Student_details(sno,sname,sdept):
print(sno,sname,sdept)

Student_details(101,"Anushka","Computers")
Student_details(102,"Akhil","Computers")
Student_details(103,"Harika","Computers")

Using default arguments:


==================================================
def Student_details(sno,sname,sdept="Computers"):
print(sno,sname,sdept)

Student_details(101,"Anushka")
Student_details(102,"Akhil")

Student_details(103,"Harika")
Student_details(104,"Satya","Medical")

output:
101 Anushka Computers
102 Akhil Computers
103 Harika Computers
104 Satya Medical

6)Functions with variable length arguments:

def f1(*a) :
print("values are : ",a,"no of elements:",len(a),type(a))
#a[0]=100

f1(10)
f1(10,20)
f1(10,20,30,40,50)

output:
values are : (10,) no of elements:1 <class 'tuple'>
values are : (10, 20) no of elements:2 <class 'tuple'>
values are : (10, 20, 30, 40, 50) no of elements:5 <class 'tuple'>

=======================================
def sum(*a) :
total=0
for i in a :
total=total+i
print("Sum of ", a, ' elemts are ',total)

sum(10,20,30,40)
sum(4534,457,457,478,487,468)
sum(365,436,47,47,7,40,50)

op:
Sum of (10, 20, 30, 40) elemts are 100
Sum of (4534, 457, 457, 478, 487, 468) elemts are 6881
Sum of (365, 436, 47, 47, 7, 40, 50) elemts are 992

=============================================================
# Calculator program
def add(a,b) :
"It returns sum of a,b"
c=a+b
print (c)
def sub(a,b) :
"It return difference of a,b"
c=a-b
print(c)
def prod(a,b) :
"It returns product of a,b"
c=a*b
print (c)
def div(a,b) :
"It returns division of a,b"
c=a/b
print(c)
def sqr(a) :
"It returns sqt returns suuare of a"
c=a*a
print (c)
def cube(a) :
"It returns cube of a"
c=a*a*a
print(c)
def power(a,b) :
"It returns power of a to the b"
i=1
c=a #2
if b==0 :
print(1)
else :
while i<b :
c=c*a
i=i+1
else :
print (c)
while True :
print("Main Menu")
print("---------")
print("1. Add")
print("2. Sub")
print("3. Product")
print("4. Division")
print ("5. Square")
print ("6. Cube")
print ("7.Power")
print ("8. Quit")

ans=int(input("Enter choice[1-8] : ")) #18


if ans==1 :
x=int(input("Enter number1 : "))
y=int(input("Enter number2 : "))
add(x,y)
elif ans==2 :
x=int(input("Enter number1 : "))
y=int(input("Enter number2 : "))
sub(x,y)
elif ans==3 :
x=int(input("Enter number1 : "))
y=int(input("Enter number2 : "))
prod(x,y)
elif ans==4 :
x=int(input("Enter number1 : "))
y=int(input("Enter number2 : "))
div(x,y)
elif ans==5 :
x=int(input("Enter number : "))
sqr(x)
elif ans==6 :
x=int(input("Enter number : "))
cube(x)
elif ans==7 :
x=int(input("Enter number1 : "))
y=int(input("Enter number2 : "))
power(x,y)
elif ans==8 :
print("Thank you.")
break
else :
print("Wrong choice.Try again")

===========example of local and global varaible=======


Local variable:
Variable created inside a block is called as a local variable.
Local variables can be accessed only inside the same block in which they have
written.

Global variable:
Variable created outside a block is called as a global variable.
Global variables can be accessed through out the program.

=================================
a=1 #Global variable
def myfunction():
b=2 #Local variable
print('a=',a)
print('b=',b)
myfunction()
print(a)
#print(b)#error
Op:
('a=', 1)
('b=', 2)
1

==============Functions returning values===================


Problem:

def sum(a,b):
c=a+b
print(c) #5

sum(2,3)
d=c+2
print(d)

=========================

If there is no return keyword in the definition,the cursor will go back to the


next line of the call.

If there is return keyword in the definition,the cursor will go back to the


same line in where it got the call(Goes back to the calling place).

def sum(a,b):
c=a+b
return c

d=sum(2,3)
e=d+3
print(e)
print("Done")

Returning a single value:


=======================================
def avg_marks(a, b, c):
d = a + b + c
x = d / 3
print(x)#92
return x

n = avg_marks(88, 98, 90)


if n >= 90:
print("A+ grade")
elif n >= 80:
print("A grade")
elif n >= 70:
print("B grade")
else:
print("C grade")
Returning multiple values:
If we want to use the values of several local variables from outside the block then
we can return all those values to the calling place.

=============================
def sum(a, b):
c = a + b
d = a - b
e = a * b
return c, d, e

x = sum(10, 20)
print('sum difference product: ', x[0], x[1], x[2], type(x))

z=x[0]+x[1]+x[2]
print(z)

output:
sum difference product: 30 -10 200 <class 'tuple'>
220

=========================================
Ways to call the functions:
1)Call by value
2)Call by reference

==============Call by value=========
Source copy will not be modified.

Separate copy of the data will be created and will be sent to the definition.
(Separate plate)

Syntax:

f1(a[:])

=============================================
def f1(x) :
print("The values in the given list : ",x,id(x)) #1001
print("Total no of elements is : ",len(x)) #3

x[1]=2000
x[2]=3000
x.append(4000)
print(x) #(10,2000,3000,4000)

a=[10,20,30] #global l1

f1(a[:])#call by value
print('outside functin , a=',a,id(a)) #1002

output:
The values in the given list : [10, 20, 30] 21580336
Total no of elements is : 3
[10, 2000, 3000, 4000]
outside functin , a= [10, 20, 30] 21579176
==============Call by Reference=========
We are passing the address of the sequence to the function definition.
So, a separate copy will not be created.
and hence the source copy will be modified.
(single plate)

Syntax:
f1(a)

==========================================
def f1(x) :
print("The values in the given list : ",x,id(x)) #1001
print("Total no of elements is : ",len(x))

x[1]=2000
x[2]=3000
x.append(4000)
print(x) #(10,2000,3000,4000)

a=[10,20,30] #global l1

f1(a)#Pass by reference
print('outside function , a=',a,id(a)) #1001

output:
The values in the given list : [10, 20, 30] 19219880
Total no of elemnts is : 3
[10, 2000, 3000, 4000]
outside functin , a= [10, 2000, 3000, 4000] 19219880

========================

1)without parameters

def sum(): <----------------


#logic

sum()

=============
2)with parameters

a,b--->formal/argumets
2,3
def sum(a,b): <--------
c=a+b
print(c)

sum(2,3)
sum(10,20)
sum(100,200)
x=
y=
sum(x,y)

ac/para

3)positional:
first parameter will be copied into first argument,second parameter into second
argument,and so on

4)Named/Keyword arguments:

f1(age=23,name="john")

5)default argumets

def Student_details(sno,sname,sdept="Computers"):
print(sno,sname,sdept)

6)variable number of arguments:


def f1(*a):
print(a,type(a))

* indicates 0 or any number

7)Local and Global

8)Function returning single value

return variable

9)Function returning multiple values

return variable1,variable2,variable3

10)Call by value
f1(a[:])

11)Call by reference
f1(a)

===============Recursive functions================
Functions calling itself are called as recursive functions.

============================
def fact(n):
if n==0:
res=1
else:
res=n*fact(n-1)
return res
i=5
print("Factorial of {} is {}".format(i,fact(i)))

Op:
Factorial of 5 is 120

==========================Modules==============================
Modules:

A .py file is called as a module only if it have variables and methods(classes


also).
It should not have other lines or logics.

Name of the file is equal to the name of the module.

Modules will generally be created by the team leads.

Team mates will use functions and data that are inside these modules.

To use the variables and methods of a module,we need to import the module
as shown below.....

Syntax to import a module:

import ModuleName

Way to access a variable inside a module:

ModuleName.VariableName

Way to access a method inside a module:

ModuleName.MethodName()

============Example 1===================================================
==================TeamLead.py========================
x=10
y="niit"

def hello() :
print("Hello...good morning")
def bye() :
print("Bye....enjoy")

def Party() :
print("Welcome to the party")

==================Anushka.py========================
import TeamLead

TeamLead.hello()

TeamLead.bye()

z=TeamLead.x

v=z+9
print(v)

=================Akhil.py=============================
import TeamLead

TeamLead.Party()
print(TeamLead.y)

============Example 2===================================================

======================CalculatorModule.py======================
'''
Author:Avneeth
ModuleName:CalculatorModule
Date Of Creation:15/11/2018
'''
x=109
y="Tecnosoft"

def add(a,b) :
"It returns sum of a,b"
c=a+b
return c
def sub(a,b) :
"It return difference of a,b"
c=a-b
return c
def Mul(a,b) :
"It returns product of a,b"
c=a*b
return c
def div(a,b) :
"It returns division of a,b"
c=a/b
return c
def square(a) :
"It returns square of a"
c=a*a
return c
def cube(a) :
"It returns cube of a"
c=a*a*a
return c

======================AkhilCal.py=====================
import CalculatorModule

squareRes=CalculatorModule.square(5)
print(squareRes)

cubeRes=CalculatorModule.cube(9)
print(cubeRes)

print(CalculatorModule.y)
==============================AnushkaCal.py======================
import CalculatorModule

sumRes=CalculatorModule.add(9,9)
print(sumRes)

divRes=CalculatorModule.div(10,5)
print(divRes)

print(CalculatorModule.x)

========To import a module from different directory====

import sys
sys.path.append("C:/Users/user/Desktop") #testm.py is created on desktop

import testm

testm.tt()

=====testm.py=====
def tt():
print("I am tt")

===================To see all the variables and methods inside a module======

For this, we have to use dir(modulename)


==================See.py====================================
import CalculatorModule
"To see all the members of the module,use the following command"
print("To see the variables and Methods in CalculatorModule :\
n",dir(CalculatorModule))

output:
To see the variables and Methods in CalculatorModule :
['Mul', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__',
'__name__', '__package__', '__spec__', 'add', 'cube', 'div', 'square',
'sub', 'x', 'y']

===from import==============

If we use from-import,only the methods and variables specified in our program will
be loaded.
Nextly,we can call the members directly without preceeding them with the
module name.

Syntax:
from ModuleName import variables,methods

===================EasyAccess.py==================================
from CalculatorModule import add,Mul,x

c=add(2,3)
print(c)

print(x)

===================EasyAccess2.py==================================
* means all the variables and methods will be included into the file.

from CalculatorModule import *

c=add(2,3)
print(c)

print(x)

====To see the type of data and the description of particular variable or method==
===========description.py============
import CalculatorModule

print(type(CalculatorModule.add))
print(type(CalculatorModule.sub))
sprint(type(CalculatorModule.x))
print(type(CalculatorModule.y))
print(help(CalculatorModule.add))
print(help(CalculatorModule))#To see the documentation of every member

output:
<class 'function'>
<class 'function'>
<class 'int'>
<class 'str'>
Help on function add in module CalculatorModule:

add(a, b)
It returns sum of a,b

None
Help on module CalculatorModule:

NAME
CalculatorModule

DESCRIPTION
Author:Harika
ModuleName:Calculator
Date Of Creation:15/11/2018

FUNCTIONS
Mul(a, b)
It returns product of a,b
add(a, b)
It returns sum of a,b

cube(a)
It returns cube of a

div(a, b)
It returns division of a,b

square(a)
It returns square of a

sub(a, b)
It return difference of a,b

DATA
x = 109
y = 'Tecnosoft'

FILE
c:\users\user\pycharmprojects\ronit\calculatormodule.py

None
==============Aliasing==================
Aliasing:

import modulename as aliasName


Ex:import module2 as md2
Now,we can access like md2.MemberName

===============properties of a module============
import CalculatorModule

print("Defaule name of the module",__name__)


print ("Documentation of the file is",CalculatorModule.__doc__)
print ("The file name is",__file__)
print( CalculatorModule.add.__doc__)

output:
Defaule name of the module __main__

Documentation of the file is


Author:Harika
ModuleName:Calculator
Date Of Creation:15/11/2018

The file name is C:/Users/user/PycharmProjects/modss/See.py


It returns sum of a,b

================
Doc String:
This is used to see the information regarding a function in some other file.

It can be of any of the following forms....


1) ''' '''
2) """ """
3) ' '

1 and 2 are used for both single line and multi line
3 is used only for single line.
==============syntaxes==============================
import modname
modname.variableName
modname.methodName()

dir(modname)

import modname as aliasname


aliasname.variablename
aliasname.methodName()

from modname import v1,v2,m1,m2


v1
v2
m1()
m2()

def data():
''' dsvfdgdf gdf dv dfg df fyus di tfi i''' --->n gdoc string
'''sd fdsfkjdhfiu hgfhdi giofdlv iflsdjfkldsj ''' --->comment

help(modname.__doc__)
help(modname.functionName)
help(modname)

============================
Math
--arithmetic.py ---> sum()
--facttable.py ---> fact()
--power.py ---> sq()

===john.py====
import Math
Math.arithmetic.sum()
Math.facttable.fact()
Math.power.sq()

=========
import packagename
packagename.modname.funName()

package:

Group of related modules

or

A folder with __init__.py file


=======================packages=====================
Functions+variables===>Module
set of modules (with __init__ file)====>Package
Package:
Package is a collection of related modules with init file.

Package must have an __init__.py file.Otherwise,it will be just a folder.

Let us say, 3 team members in a company are writing reusable logics in their own 3
differenty files/modules regarding a particular thing(say...logics regarding
mathematical operations).We will group these three related modules into a package.

--Arithmetic.py
--facttable.py ===========>Grouped into "Math" package.
--cubes.py

Advantage of a package:
easy to maintain..Modularity can be achieved.Lose coupling can also be
achieved.

x(folder) y(folder) z(folder)


5 modules 6 modules 7 modules.

Changes done to one module will not be reflected to other modules.

If we don't have init file in our folder,then that folder is no more treated
as a package.

What we write in init file?


We will simply import modules here.That is...
We will import the required modules to be grouped using the following commands..

==== __init__.py =====

import modulename1
import modulename2
Ex: import m1
import m2
How to access the methods of a package:

Syntax to import a package:


import packagename

Syntax to call a method of a module in a package:


packageName.moduleName.functionName()

Example:
import abc
abc.m1.f1()

Here,
abc--->PackageName(foldername with init file)
m1---->ModuleName
f1---->FunctionName

import abc----------------->imports all modules from abc package


from abc import m1--------->imports only m1 module from abc
from abc.m2 import f3,f4--->imports f3,f4 functions from m2 module of
abc package.

'''
===========================
Math
--Arithmetic.py -->add(),sub()
--FactTable--->fact(),table()
--Power.py--->square(),cube()
======================

import Math

Now all the modules will be imported because of which i can access any function
from any module.
Whenever i import a package,no need to import the modules
individually.Automatically all the modules will be imported into the current .py
file.

===============Harika.py===============
import Math
Math.Arithmetic.sub()
Math.FactTable.table()
Math.Power.cube()

Syntax to import a package:

import packageName

To call a method from a module in a package the syntax is:

packageName.moduleName.methodName()
===========================

====================Examples======================

=================Ex1============================
===============FirstPack(python package)=====================

Right click on the project---->New---->Python package(__init__.py) will


automatically
be created.

==============SumSub.py(Under FirstPack)==================
def sum():
a=10
b=20
c=a+b
print(c)
def sub():
a=10
b=20
c=a-b
print(c)

===========================MulDiv.py======================
def mul():
a=10
b=20
c=a*b
print(c)

def div():
a = 10
b = 20
c = a/b
print(c)

=============== __init__.py ========================


from FirstPack import SumSub
from FirstPack import MulDiv

=======================Access1.py========================
import FirstPack

FirstPack.SumSub.sum()
FirstPack.SumSub.sub()

FirstPack.MulDiv.mul()
FirstPack.MulDiv.div()

========================Access2.py=======================
from FirstPack.MulDiv import *
from FirstPack.SumSub import sum

mul()
div()

sum()

#from FirstPack import MulDiv.mul() not allowed

=================Ex2=======================

===============MyMath(Python Package)=================

=========arithmetic.py===============
def add(a,b):
return a+b

def sub(a,b) :
return a-b

def prod(a,b) :
return a*b
def div(a,b) :
return a/b
==================facttable.py==================
def factorial(n) :
fact=1
for i in range(1,n+1) :
fact=fact*i
return fact

def table(n) :
for i in range(1,11) :
print(n,"*",i,"=",n*i)

==================power.py================
def square(a) :
return a*a

def cube(a) :
return a*a*a
================= __init__.py=================
from MyMath import arithmetic
from MyMath import facttable
from MyMath import power

#from MyMath import * ===>Not acceptable in all the cases(depends on the way we
write "from import" statements and version of python we are using.)
=====================Access.py================
import MyMath
MyMath.facttable.table(10)
subRes=MyMath.arithmetic.sub(10,9)
cubeRes=MyMath.power.cube(9)
print("Sub result is",subRes)
print("Cube result is",cubeRes)

==================

from MyMath.power import square


squareRes=square(5)
print("Square result is",squareRes)

===================Access2.py================
from MyMath.arithmetic import sub
from MyMath.power import square

subRes=sub(10,2)
sqRes=square(9)

print(subRes)
print(sqRes)

=====================Sub packages==================================
Sub package:
Package inside another package is called as a subpackage.
Ex:

==================MainPack(Python Package)=====================
===========sumMain.py============
def sum():
a=10
b=20
c=a+b
print(c)
============subMain.py===============
def sub():
a=10
b=20
c=a-b
print(c)

============= __init__.py(MainPack)===============
from MainPack import sumMain
from MainPack import subMain
#from MainPack import SubPackk
================AccessMain.py=================
from MainPack.sumMain import sum
from MainPack.subMain import sub

sum()
sub()

==========SubPackk(Python Package)(under MainPack)=============


==============DivModuleSubPack.py====================
def div():
a=10
b=20
c=a/b
print(c)

============= __init__.py(under SubPackk)==================


from MainPack.SubPackk import DivModuleSubPack

==================AccessSubPack.py=============
from MainPack.SubPackk.DivModuleSubPack import div
div()
=============================
f()
m.f()
p.m.f()
p.sp.m.f()

f--->function
m--->module
p--->package
sp--->sub package

Syntax to access a method from sub package

from ParentPackage.Subpackage.ModuleName import FunctionName

FunctionName() # Calling the function


========= __init__.py(init file of main/package will look like below) ===========

from ParentPackage.SubPackage import ModuleName

Ex:
from MainPack.SubPackk import DivModuleSubPack

By using the above instruction,we are making DivModuleSubPack as a module of


SubPackk package

=======================================
Packages in python 3.7(In few versions)

Create a python package with the name MyPack


===========one.py===========
def add():
c=1+9
print(c)

def mul():
c = 1*9
print(c)

=========two.py=============
def sub():
c=1-9
print(c)

def div():
c = 10/5
print(c)
============= __init__ .py ==================
from .one import add,mul
from .two import sub,div

================Access.py===================
import MyPack

MyPack.one.add()
MyPack.one.mul()
MyPack.two.sub()
MyPack.two.div()

=========================OOPS==========================

Object Oriented Programming System

Procedural Oriented Programming System:

In this way of programming, the task to be done is divided into sub tasks.
Each sub task is called as a procudure(function).

Object Oriented Programming System:


In this way of programming, the task to be done is divided into sub tasks.
Each sub task is called as a class.

When can we call a language as object oriented:


In any language,if we write the code using classes and objects,then we can call
that language as object oriented.
In python also we will use classes and objects in writing the code.So we can call
python as object oriented language.

=======================================

class:

Collection of variables/attributes/properties and functions/methods/behaviours.

Object:
Any real wolrd entity is called as an object.It can represent a person,a bank
account,etc.

Student ======================>Class
sno,sname,sage,fee(),join(),reading(),writing()

Student1 ==================>Object 1
sno=101
sname="Anushka"
sage=14

Student2 ==================>Object 2
sno=102
sname="Akhil"
sage=12
===========================================

To store the data of 3 products

Product ---->class
---------
pid
pname
pprice

Product 1 --->object 1
---------
pid=11
pname=Pen
pprice=100

Product 2 -->object 2
---------
pid=12
pname=Pencil
pprice=50
Product 3 --->object 3
---------
pid=13
pname=Book
pprice=500

5 employees

c-->1
o-->5

4 mobiles

c-->1
o-->4

6 laptops

c-->1
o-->6

Python is both procedure oriented and object oriented programming language.

Python is a procudural oriented language because in python we are using


procedures/functions.

Python is an object oriented programming language too.

What is an Object oriented language??


In any language if the code is written using classes and objects,then we can call
that
language as object oriented.

===========Syntax to create a class================

class ClassName:
#variables and methods

=====================================
Program to show the way to access the variables and methods in a class:
To access the variables and methods in a class,we have to create an object
for the class.
============================
10 John US
=============================
class Student: #student1
sno=10
sname="John"
saddress="US"

def display(self):
print("Student Details")
print("-"*50)
print("The student no is:",self.sno) #10
print("The student name is:", self.sname) #John
print("The student address is:", self.saddress) #US
print("This student will join")

student1=Student() #objectName=ClassName()
print("Accessing the variables individually")
print(student1.sno) #Object.VariableName #10
print(student1.sname) #John
print(student1.saddress) #US
print("Complete data of the student")
student1.display() #Object.methodName()

===========
To use the variables and methods of a class,we have to create object for the class.

===================General Structure=============
class Demo:

variables + methods

Object Creation + Accessing

==================================
Object creation:
objectName=className()

=================================
Accessing:
object.variableName
object.methodName()

==============================
class Employee: #employee1

eno=1001
eage=34
epackage=9.8

def employee_details(self):
print("Employee Details")
print("#"*30)
print("The employee no is:",self.eno) #employee1.eno
print("The employee age is:",self.eage) #employee1.eage
print("The employee package is:",self.epackage) #employee1.epackage

employee1=Employee() #employee1{eno=1001,eage=34,epackage=9.8, employee_details()


body}
print(employee1.eno)#1001
print(employee1.eage)#34
print(employee1.epackage)#9.8
employee1.employee_details() #employee_details(employee1)

-------------------------------------------------------------------------------
employee1--->1001

Note:

What will happen if we create an object for the class??

As soon as we create an object for the class--


1)Object will occupy some memory
2)For which class we are creating the object,a copy variables and methods of that
class will be loaded into that object.

self:

To call a function inside the class, we must use an object.


With which object we are calling the function,the address of that object will be
sent as a parameter to the function we are calling.
To store the address of this object,we are taking the "self" argument.

=========================================

To every method inside a class,object will be sent as a first parameter by


default.

Thats why, to hold this parameter(object),we will take a an argument called


as "self"(usually) in the function definition.

def data(self,a,b):

pass

object.data(2,3) ===>data(object,2,3)

self--->ob
a------>2
b------>3

=============================================================

class employee:

def getdata(self,id,name,job,sal): #e1{id=101,name=sai,job=manager,sal=10000}


self.id=id #101
#e2{id=102,name=Anushka,job=Programmer,sal=100000}
self.name=name #sai #e3{id=103,name=Akhil,job=Doctor,sal=200000}
self.job=job #manager
self.sal=sal #10000
def display(self) :
print(self.id,"\t",self.name,"\t",self.job,"\t\t",self.sal)

e1=employee()
#e1{getdata(self,id,name,job,sal),display(self)}
e1.getdata(101,'sai','manager',10000) #getdata(e1,101,'sai','manager',10000)
e1.display() #display(e1)

e2=employee()
#e2{getdata(self,id,name,job,sal),display(self)}
e2.getdata(102,'Anushka','Programmer',100000)
#getdata(e2,102,'Anushka','Programmer',100000)
e2.display()#display(e2)

e3=employee()
#e3{getdata(self,id,name,job,sal),display(self)}
e3.getdata(103,'Akhil','Doctor',200000)#getdata(e3,103,'Akhil','Doctor',200000)
e3.display() #display(e3)

=========Difference between a method inside the class and outside the class===
To access a method inside a class, we have to create an object for the class.
To access a method created outside the class, no need to create object.We can
directly call it.

Every method inside a class will by default take an argument(address of the


object).
A method outside a class will not have any default argument.

===========================
class A:
print("Start")
def f1(self):
print("From f1")

def f2():
print("From f2")

f2() #functionName()

o1=A() #object=className()
o1.f1()# object.funName()

Op:
Start
From f2
From f1
===============How to call function within another function=================

class A:
def f1(self) :
print("I am a function witn the name f1")
def f2(self) :
print("I am a function witn the name f2")
def f3(self) :
self.f1()
self.f2()
print ("I am a function witn the name f3")

x=A() #x{f1() f2() f3()}


x.f3() #f3(x)
op:
I am a f1
I am a f2
I am a f3

==========================================
class Hello:
print("start")
a=10
print("The value of a Locally:",a)
a=20
print("The value of a Globally:",a)
x=Hello() #x{a=10}
print("Inside the class",x.a)
print("Outside the class",a)

'''
Op:
start
The value of a Locally: 10
The value of a Globally: 20
Inside the class 10
Outside the class 20
'''

===Difference between a variable inside the class and a variable ouside the
class===
class A:
x = 100
print("x=",x) # Direct accessing

def m1(self): #o1{x=100}


print("To access the variable x inside a function.....way 1=", self.x)
#self.x
print("To access the variable x inside a function.....way 2=",A.x)
#className.variableName
print("To access the variable x inside a function.....way 3=", o1.x)
#object.variableName
#print("x=",x)

y = 200
print("y=", y)

o1 = A() #o1{x=100 m1() body}


o1.m1() #m1(o1) #"To access the method m1() from outside the class(Only way)
print("To access x outside the class ...way1=",A.x) #Classname.variablename
print("To access x outside the class ...way2=", o1.x) #Object.variableName
#print("To access x outside the class ...=", self.x) #Not allowed
#print("method",A.m1()) #Not allowed
#print("method",self.m1()) #Not allowed

Op:
x= 100
y= 200
To access the variable x inside a function.....way 1= 100
To access the variable x inside a function.....way 2= 100
To access the variable x inside a function.....way 3= 100
To access x outside the class ...way1= 100
To access x outside the class ...way2= 100

==========Variable with same name inside and outside the class==============


class A:
x=10 #local
def m1(self):
print "Inside def x self.x=",self.x
print "Inside def x A.x=", A.x
print "Inside def x ob.x=", o1.x

x=20 #global
o1=A() #o1{x=10,m1() body}
o1.m1() #m1(o1)
print "outside def x A.x=", A.x
print "Outside def x ob.x=", o1.x
print "x=",x

Op:

Inside def x self.x= 10


Inside def x A.x= 10
Inside def x ob.x= 10
outside def x A.x= 10
Outside def x ob.x= 10
x= 20

===========================================
class c1:

def f1(self,c,d) :
self.a=c# a and b are local variables.c and d are called as parameters
self.b=d
print " i am f1, my a,b values are",self.a,self.b
def sum(self) :
print self.a+self.b

# object creation
x=c1() #x{}
y=c1() #y{}
k=c1() #k{}
#calling class methods
x.f1(10,20) #f1(x,10,20)
y.f1(100,200) #f1(y,100,200)
k.f1(1000,2000) #f1(k,1000,2000)
x.sum() #sum(x)
y.sum() #sum(y)
k.sum() #sum(k)
op:
i am f1, my a,b values are 10 20
i am f1, my a,b values are 100 200
i am f1, my a,b values are 1000 2000
30
300
3000

========================================================
class A :
x=100
def f1(self,a) :
print " I am a f1 function"
self.a=a #10
print "class variable x=",A.x #100
A.x=A.x+self.a #100+10=110
print "After incrementing , x=",A.x #110

print "first"
a1=A()

a2=A()
a1.f1(10)
a2.f1(20)
print "Outside of the class x=",A.x,"Throu object x=",a2.x
op:

I am a f1 function
class variable x= 100
After incrementing , x= 110
I am a f1 function
class variable x= 110
After incrementing , x= 130
Outside of the class x= 130 Throu object x= 130

=============class with class variables============

class Area :
pi=3.14 #class level variables.Can be accessed directly
#using class name
area=0
def area_circle(self,r) :

print Area.area #Accessing using class name


self.r=r #3
Area.area=Area.pi*self.r*self.r
print Area.area
def area_traingle(self,r) :
self.r=r
Area.area=2*Area.pi*self.r
print Area.area
c=Area()
t=Area()
c.area_circle(3)
t.area_traingle(3)
op:
0
28.26
18.84

=============Principles of OOPS===================

--classes
--objects
--Encapsulation
--Inheritence
--Abstraction
--Polymorphism

============Encapsulation==========
Encapsulation:
Grouping/Wrapping of important variables(data) and methods(sub parts) into a unit.

Purpose:
Data security

To provide security for a variable:

__variableName=value (__ --> 2 under scores)

To provide security for a method:

def __methodName(self):
#logic

====Data is getting modified=======================================


class Demo:
__a=10

d1=Demo() #d1{a=10}
d1.a=90
print(d1.a) #d1{a=90} #value is getting modified

==================Still gets modified but just giving a caution========


class Encap:
__a=10 #Just a caution
e=Encap()
e.a=100
print(e.a)

Note:
To use that "a" in the same class we have to put "print(__a)"
================================Applying encapsulation==============
A variable or method preceeded by __ is called as a private variable/a private
method.

Syntax to declare a private variable and a private method:

__variablename

__methodName()

Purpose:

To provide security for the data.

======================================

class Demo:
__a=10
b=20

def __m1(self):
print("From m1")
def m2(self):
print("From m2")
d1=Demo()
print(d1.b)
d1.m2()

#print(d1.__a)
#d1.__m1()

===============================
class Demo:
__a=10
b=20

d=Demo
#print(d.__a)
#c=d.__a+10
#print(c)
d.__a=30 #pupil will not do this
print(d.__a)#30

==============Accessing private functions of a class through public functions in


that class========================

class A:
__a=100 # private variable
b=200 # public variable
def __f1(self) : # private function
print("I am a private f1 function")
def f2(self) : # public function
print(" I am a public function, i am calling private function,..")
self.__f1()
print(" the private value is :",self.__a)
c=A.__a
d=c+9
print(d)

x=A() #x{b=200 f2() __a=100 __f1()}


#x.__a=900 #unmodifiable because a is not accessible
#x.__f1() #f1 is not accessible
x.f2() #f2(x)
print("Outside class, public b value is :",A.b)
output:
I am a public function, i am calling private function,..
I am a private f1 function
the private value is : 100
Outside class, public b value is : 200

Note:

One copy of variables(Not the methods) will be created and that copy is given to
the class in which those variables are created.

====================Inheritence=====================
Deriving a new class(child) from the existing class(parent),so that the child class
will get the properties of the parent class along with its own properties.

Ex:
Mother----->US

I have----->India,US

A ---->a,b,m1()

B ---->c,d,m2(),a,b,m1()

Types of inheritence:

1)Single
2)Multiple
3)Multi level
4)Hierarchical
5)Hybrid

Principle:
Using the object of parent class you can access only the parent class members.
But, by using an oject of child class,you can access both parent and child
class members.

Single inheritence:

One parent will have only one child.


A------>B

class A:
a=10
def m1(self):
print("Hello from A")

class B(A): #class child(parent):

b=30
def m2(self):
print("Hello from B")

Oa=A()
oB=B()
print(Oa.a)
Oa.m1()
oB.m1()
oB.m2()
print(oB.a)
print(oB.b)

2)Multiple inheritence:

Multiple Parents for single child.

A B

class A:
a=10
def m1(self):
print("Hello from A")

class B: #class child(parent):


b=10
def m2(self):
print("Hello from B ")

class C(A,B):
print("From class C")

oC=C()
print(oC.a)
print(oC.b)
oC.m1()# m1(oC)
oC.m2()

output:
From class C
10
10
Hello from A
Hello from A
3)Multi level inheritence:

Grand father , father and child relationship

class A:
a=10
def m1(self):
print("From A")

class B(A):
b=20
def m2(self):
print("From B")

class C(B):
c=30
def m3(self):
print("From C")

oC=C()
print(oC.a)
print(oC.b)
print(oC.c)
oC.m1()
oC.m2()
oC.m3()

output:
10
20
30
From A
From B
From C

Hierarchical inheritence:

One parent and multiple children.

class A:
a=10
def m1(self):
print("From A")

class B(A):
b=10
def m2(self):
print("From B")
class C(A):
c=10
def m3(self):
print("From C")
oA=A()
oA.m1()
print(oA.a)

oB=B()
oB.m1()
oB.m2()
print(oB.a)
print(oB.b)

oC=C()
print(oC.a)
print(oC.c)
oC.m1()
oC.m3()

'''
output:
From A
10
From A
From B
10
10
10
10
From A
From A

'''

=================Hybrid inheritence========================

Combination of inheritences:
class A:
def dA(self):
print("From A")

class B(A):
def dB(self):
print("From B")
class C(B):
def dC(self):
print("From C")
class D(B):
def dD(self):
print("From D")

a=A()
b=B()
c=C()
d=D()
a.dA()
b.dA()
b.dB()
c.dA()
c.dB()
c.dC()
d.dA()
d.dB()
d.dD()

'''
output:
From A
From A
From B
From A
From B
From C
From A
From B
From D
'''

==================multiple inheritence==========
class A:
def dA(self):
print("From A")

class B:
def dB(self):
print("From B")

class C(A,B):
def dC(self):
print("From C")

c=C()
c.dA()
c.dB()
c.dC()

===========Problem with multiple inheritence=======

class A:
def method(self):
print("This is A class")

class B:
def method(self):
print("This is B class")

class C(A,B):
pass

c=C()
c.method()

output:
This is A class ====>Only the First parent class method is getting executed.
In the case of multiple inheritence,if two parent classes are having the methods
with the same name,then by default, the method of the first parent class will be
executed.

But if we want to execute the methods of both the parent classes,we will use
super().

================Solution============
class A:
def method(self):
print("This is A class")
super().method() #Because of this class B method will be called

class B:
def method(self):
print("This is B class")

class C(A,B):
def method(self):
print("This is C class")
super().method() #Because of this,class A method will be called

c = C()
c.method()

output:
This is C class
This is A class
This is B class

=================Example to show how reusabilty can be achieved using


inheritence==========
==============Teacher.py(Module)===========
class teacher:
def setid(self,id): #s{id=1001,name=pavan,marks=98}
self.id = id
def getid(self):
return self.id
def setname(self,name):
self.name = name
def getname(self):
return self.name
def setsalary(self,sal):
self.sal = sal
def getsalary(self):
return self.sal

===========Student.py============

from Teacher import teacher


#from Molule import class
class student(teacher):
def setmarks(self,marks):
self.marks = marks
def getmarks(self):
return self.marks
s = student()
s.setid(1001)#setid(s,1001)
s.setname('PAVAN')#setname(s,'PAVAN')
s.setmarks(98)#setmarks(s,98)

print("student id is:",s.getid()) #getid(s)


print("student name is ",s.getname()) #getname(s)
print("student marks are",s.getmarks()) #getmarks(s)

Purpose: To achieve code reusability

==============================Files====================================

Collection of data.

Opening a files:
----------------
file_handler = open("filename","open mode",buffering)

buffering ---->optional

Buffer:Buffer represents the no. of. bytes of data we want to fetch for
reading/writing.
If we specify 500 then it will use 500 bytes of data to read and write.
If we don't mention any buffering integer , then default buffer size would be 4096
or 8192 bytes.

Ex:

f = open("myfile.txt","w")

open modes :
----------
w - write data into file.If data is already present in the file, it would
be deleted and present data will be stored.

r - To read data from file. The file pointer is positioned at the beginning
of file.

a - To append data to the file. Appending means adding at the end of


existing data.
The file pointer is placed at the end of the file. If the file does not
exist,it will create new file to write data.

w+ - To write and read data of a file. The previous data in the file will
deleted.

r+ - To read and write into a file. The previous data in the file will not
be deleted.The file pointer is placed at beginning of the file.

a+ - To append and read data of a file. The file pointer will be at the end
of the file.if file exists. If the file does not exist,it creates a new file
for reading and writing.

x - To open the file in exclusive creation mode.The file creation fails if


the file already exists.

f = open("myfile.txt","w")

Here f represents file handler or file object. It refers to the file


with the name 'myfile.txt' that is opened in 'w' mode.

Closing File:
----------------
A file which is opened should be closed using the close() method. Once file is
opened but not closed, then data of the file may be corrupted or deleted in
some cases. Also if the file is not close, the memory utilized by the file
not freed, leading to problems like insufficient memory. This happens when
we are working with several files simultaneously. Hence it is mandatory to
close file.

f.close()

=====Python program to create a text file to store one string(individual


characters).
(Creating the file in the default location)===============

write :
==============one.py====================
f = open('myfile.txt','w')

str = input("Enter text:")

f.write(str)

f.close()

Now u can see the file created.


=====Python program to create a text file to store one string(individual
characters).
(Creating the file a specific location)===============
=========two.py=============
f = open('D:\\core\\Aug9th.txt','w')

str = input("Enter text:")

f.write(str)

f.close()

To open the file that was created using cmd prompt,then, more filename.txt

Read :
===========Three.py=====================
f = open("myfile.txt","r")

str = f.read()
print(str)

f.close()

Append :
=====================four.py===============
f = open("myfile.txt","a")

str = input("Enter string:\n")

f.write("\n"+str)#To append to the next line

f.close()

======Python program to store a group of strings into a text file==========

===========five.py===================
f = open('myfile.txt','w')

print("Please enter text(@ at end):\n")

str = None
while(str != '@'):
str = input()

if(str != '@'):
f.write(str+"\n")

f.close()

The with statement:


===================

The with statement can be used while opening a file.


The advantage of with statement is it will take care of closing a file
which is opened by it.
Hence we need not to close the file explicitly.

Syntax:
with open("filename","openmode") as file_object:

==========A python program to use "with open" to open a file and write some
strings to the file===================
===========six.py===========
with open('this.txt','w') as f:
f.write('I am a learner\n')
f.write('Python is attractive\n')

=================================================
details.txt:
-----------
"id","name","sal","gender","dno"
101,Ravi,2000,M,10
102,Krish,3000,M,10
103,Rama,4000,F,20
104,Ramu,5000,M,20
105,lalitha,4000,F,10

======Difference between read(),readline(),readlines()=============


============seven.py=============

file_path ="details.txt"
f = open(file_path,'r')

print(f.read()) #Reads as it is

print(f.readlines()) #Reads the entire data in the form of a list

print(f.readline()) #Reads only one line


print(f.readline())

====================eight.py=================================
file_path = 'C:\\Users\\user\\Desktop\\details.txt'
f = open(file_path,'r')
print(f.read())
#'"id","name","sal","gender","dno"\n101,Ravi,2000,M,10\n102,Krish,3000,M,10\
n103,Rama,4000,F,20\n104,Ramu,5000,M,20\n#105,lalitha,4000,F,10'

''
f = open(file_path,'r')
print(f.readline())
'"id","name","sal","gender","dno"\n'
print(f.readline())
'101,Ravi,2000,M,10\n'
print(f.readline())
'102,Krish,3000,M,10\n'
print(f.readlines())
['103,Rama,4000,F,20\n', '104,Ramu,5000,M,20\n', '105,lalitha,4000,F,10']
==================
details.txt:
-----------
"id","name","sal","gender","dno"
101,Ravi,2000,M,10
102,Krish,3000,M,10
103,Rama,4000,F,20
104,Ramu,5000,M,20
105,lalitha,4000,F,10

===========select dno,sum(sal) from details group by dno==========================

nine.py:
---------------

'''
a={101:"satya",102:"Pinky"}
print(a.get(103))#None

a[104]="John" #dic[newKey]=newValue
print(a)

print(a[101])#To retrieve the value of a particular key

'''

=======================
file_path = 'details.txt'

aggr = {}
with open(file_path,'r') as f:
n = f.readline() #we dont want first line...so we r reading the first
line data #and storing in a variable n.Now pointer is
#in the second line."id","name","sal","gender","dno"
lines = f.readlines() #From second line,we are reding all the lines.
print(n) #"id","name","sal","gender","dno"
print(lines)
'''
['101,Ravi,2000,M,10\n', '102,Krish,3000,M,10\n', '103,Rama,4000,F,20\n',
'104,Ramu,5000,M,20\n', '105,lalitha,4000,F,10\n']
'''
for line in lines:
w = line.split(",")
dno = int(w[4].split('\n')[0])
#print "dno=",dno
sal = int(w[2])

if aggr.get(dno) == None:
aggr[dno] = sal
else:
aggr[dno] += sal #aggr[dno]=aggr[dno]+sal

print(aggr) #{10: 9000, 20: 9000}

============Step wise explanation of the above program=========


file_path = 'details.txt'

aggr = {}
with open(file_path, 'r') as f:
n = f.readline()
#print(n) #"id","name","sal","gender","dno"

lines = f.readlines()
print(lines)

'''
['101,Ravi,2000,M,10\n', '102,Krish,3000,M,10\n', '103,Rama,4000,F,20\
n','104,Ramu,5000,M,20\n', '105,lalitha,4000,F,10\t\t\n'] ===> lines
'''
for line in lines: # line====>101,Ravi,2000,M,10\n
w = line.split(",") # w===>w[0]=101 w[1]=Ravi w[2]=2000 w[3]=M w[4]=10\n
dno = int(w[4].split('\n')[0]) #dno=10
#print "dno=",dno
sal = int(w[2]) # sal===>2000

if aggr.get(dno) == None:
#aggr.get(dno)==>aggr.get(10)==None==>None==None==>True
aggr[dno] = sal # aggr{10:2000}
else:
aggr[dno] += sal #aggr[dno]=aggr[dno]+sal ===>2000+3000=5000

print(aggr) #{10: 9000, 20: 9000}

Note:
a = {101: "Hello", 102: "Hai"}
print(a.get(103)) # None #If key is not there in the dictionary,"None" will be
returned.
print(a[102])

==============select gen,sum(sal) from tablename ============================

===========file.txt(type .txt while creating the file in pycharm )==============


id,name,salary,gender
101,Harika,1000,F
102,Satya,5000,M
103,Mani,2000,F
104,Vikki,1000,M

=================================
aggr = {}
with open('file.txt', 'r') as f:
line1 = f.readline()
lines = f.readlines()
print('Employee details are\n',lines)

for line in lines:

w = line.split(',')
sal = int(w[2])
gen = w[3].split('\n')[0]

if (aggr.get(gen) == None):
aggr[gen] = sal
else:
aggr[gen] += sal
print(aggr)

Op:
('Employee details are\n', ['101,Harika,1000,F\n', '102,Satya,5000,M\n',
'103,Mani,2000,F\n', '104,Vikki,1000,M'])
{'M': 6000, 'F': 3000}
===================Merge multiples files to single file==========================
case1: Both having same schema
=========f1.txt====
id,name,gen
101,phani,M
102,Raji,F
103,Prasad,M
======f2.txt========
id,name,gen
104,Lakshmi,F
105,Pramod,M
106,Krishna,M

===========f1f2merge.py==============

f1 = open('f1.txt','r')
file1_content = f1.readlines()

f2 = open('f2.txt','r')
file2_content = f2.readlines()

file3_content = file1_content+file2_content

f = open('file_new.txt','w')

for line in file3_content:


f.write(line)

f.close()
f2.close()
f1.close()

Op:
id,name,gen
101,phani,M
102,Raji,F
103,Prasad,Mid,name,gen(without this if you want)
104,Lakshmi,F
105,Pramod,M
106,Krishna,M
=====================

If we want to get the output in the below manner:


id,name,gen
101,phani,M
102,Raji,F
103,Prasad,M
104,Lakshmi,F
105,Pramod,M
106,Krishna,M

Then,

==========================f1f2merge2.py===============
f1 = open('f1.txt','r')
file1_content = f1.readlines()

f2 = open('f2.txt','r')
file2_content1 = f2.readline()
#print(file2_content1)
file2_content11=f2.readlines()

file3_content = file1_content+['\n']+file2_content11 #In the list manner we are


adding the data in the #next
line

f = open('file_new.txt','w')

for line in file3_content:


f.write(line)

f.close()
f2.close()
f1.close()

case : both having same schema with different order

f3.txt
----------
id,name,gen
101,phani,M
102,Raji,F
103,Prasad,M

f4.txt
---------
id,gen,name
104,F,Lakshmi
105,M,Pramod
106,M,Krishna

==================================================
f1 = open('f3.txt','r')
file1_content = f1.readlines()

f2 = open('f4.txt','r')
h1 = f2.readline()
file2_content = f2.readlines()
print(file2_content) #['104,F,Lakshmi\n', '105,M,Pramod\n', '106,M,Krishna\n']

file2_new = [] #empty list

for line in file2_content: #line=[104,F,Lakshmi\n]


words = line.split(',') #words[0]=104 words[1]=F words[2]=Lakshmi\n
id = words[0] #104
gen = words[1] #F
name = words[2].split('\n')[0] # name=Lakshmi\n.split('\n')[0]
==>name=Lakshmi
rec = id+','+name+','+gen+'\n'
file2_new.append(rec)
file3_content = file1_content+['\n']+file2_new

#Concatenating the list data to \n


#In we dont concatenate with \n,then we will get the output like this in the
file....
#103,Prasad,M104,Lakshmi,F
#Because of \n,104,F,Lakshmi will be added from the next line.

f = open('file_new.txt','w')
for line in file3_content:

f.write(line)

f.close()

f2.close()
f1.close()

Note:
'''
The data in the files(file1 and file2_new) will by default be of type list.
While retieving the data from a file,the type of this data will by default become
string.

That is...
Type of data stored in a file---->lists
Type of data retrieved from a file--->string

=====To separate a string using multiple separators or delimiters==============


import re
def split_string_by_multiple_separators(text):
strings = re.split('[:,.\s]', text)
return strings
if __name__ == "__main__":
text = "hi,welcome to:coding:python.com"
strings = split_string_by_multiple_separators(text)
print("Splited strings: ")
for string in strings:
print(string)

============================
To open the file using cmd prompt
>>more filename.txt

=============================================
============== seek() =====================
seek() : To place pointer at required position in the file.

fileobject.seek(no.of bytes,offset)

Ex:
x.seek(5,0)
offset ===> 0(beginning) 1(current) 2(ending)

===============FlipKart application=======================
===========login_details.txt============
harikakotha|hari|123
SatyaKetavarapu|Satya|456
vallikumuda|valli|777

#This file will get the details when each user register
=============fwrite.py==========
file_name="login_details.txt"

#This is a module...In future,if we want to change the file name,we can directly
#write the new file name here that will be automatically reflected in all parts of
the program.

============flipkart.py================
import sys
import fwrite as fw

def login():
f = open(fw.file_name, 'r') # Opening login_details.txt in the read mode
usr_nm =input("Enter user name\n") #harika
pwd =input("Enter password\n")#123

lst_lines = f.readlines() # {harikakotha|hari|123\n,SatyaKetavarapu|Satya|456\


n}

aggr = {} #Empty dictionary

for lst in lst_lines: # lst====>{harikakotha|hari|123}


details = lst.split('|')#details[0]=harikakotha details[1]=hari
details[2]=123\n
un = details[1] #hari
pd = details[2].split('\n')[0]#[123\n].split('\n')[0]==>123

if (aggr.get(un) == None):#aggr.get(hari)==None ==> None==None


aggr[un] = pd #aggr[hari]=123 ===>aggr={hari:123}

#print("user name and pwd details are", aggr)

if (usr_nm in aggr.keys()): #hari in [hari,Satya]


if (pwd == aggr[usr_nm]): #123==aggr[hari] ===>123==123
print("login successfully")

else:
print("user not found. if you are new user please register")

f.close()

def register():
firstname =input("Enter firstname\n")
lastname =input("Enter lastname\n")
name = firstname + lastname
username =input("Enter username\n")
password =input("Enter password\n")

re_enterpassword =input("Reenter password\n")


if (password != re_enterpassword):
print("password mismatch")
sys.exit(1)
rec = name + '|' + username + '|' + password # Entering the details in the
file.
# The data in the file will be in string format while entering.So we are using
con-
# catination operator
with open(fw.file_name, 'a') as f:
f.write(rec + '\n')

print("1.login \n\n2.Register\n\n")
print("enter your choice\n")
n = int(input())
if(n==1):
login()
else:
register()

========================Constructors===================
A constructor is one of the ways to initialize the variables/object.
The name of the constructor is always " __init__(self) ".
When the object of the class is created,the constructor will automatically be
called.

syntax:

def __init__(self):
pass

At the time of creation of object,if we want to do some action,then we have to go


for a constructor.

=========Initializing the d object using a normal method====================


class Demo:
def data(self): <--Using a normal method we have initialized the object
self.a=10
self.b=20

d=Demo() #d{data()}
d.data() #data(d) #d{a=10,b=20}
===============================
class Demo:
def __init__(self): <-- Using a parameterless constructor we have initialized
the object
self.a=10
self.b=20
d=Demo() #Demo(d) #d{a=10,b=20}

As soon as we create object for the class,the constructor of that class will be
called with that object.
================================
class Demo:
def __init__(self,x,y): <--Using a parameterized constructor we have
initialized the object
self.a=x
self.b=y

d=Demo(10,20) #Demo(d,10,20) #d{a=10,b=20}

=====================================
======Program to show that constructor will be called if we create an object for
the class==============

class c1 :
def __init__(self) :
print("Hey, i am a constructor")
a=c1()
b=c1()
c=c1()

op:
Hey, i am a constructor
Hey, i am a constructor
Hey, i am a constructor

==============================
# example of constructor
class c1 :
i=0
def __init__(self) : # constructor method
c1.i=c1.i+1 #6
print(" hey, i am constructor :",c1.i)#6
def f1(self) :
print("total no of objects:",c1.i)#6

x=c1()
y=c1()
z=c1()
k=c1()
m=c1()
x.f1()
l=c1()
x.f1()
op:
hey, i am constructor : 1
hey, i am constructor : 2
hey, i am constructor : 3
hey, i am constructor : 4
hey, i am constructor : 5
total no of objects: 5
hey, i am constructor : 6
total no of objects: 6
===================Initializing the variables inside a method============
class c1:
def data(self): #o{width = 10,height = 10,depth = 10}
self.width = 10
self.height = 10
self.depth = 10

def area(self):
print(self.width * self.height * self.depth)

o = c1()#o{data(),area()}
o.data()#data(o)
o.area()#area(o)

Op:1000

==============Initializing variables using a constructor======================


============a)Using a Parameterless constructor=====================
class c1:

def __init__(self): #o1{width = 10,height = 10,depth = 10}


self.width = 10
self.height = 10
self.depth = 10

def area(self):
print(self.width * self.height * self.depth)

o1 = c1()
o1.area()

===================================
class student:
def __init__(self):
self.name = "sai"
self.age = 22
self.address = "hyd"

def display(self):
print("name = ", self.name)
print("age = ", self.age)
print("address =",self.address)

a = student()
a.display()

==============Using parameterized constructor============

class c1:

def __init__(self,sno,sname,sadd): #{o1,101,John,US}


#o1{sno=101,sname="John",sadd="US"}
self.sno = sno
self.sname = sname
self.sadd = sadd

def display(self):
print("The student number is:",self.sno)
print("The student name is:", self.sname)
print("The student address is:", self.sadd)

o1 = c1(101,"John","US")
o1.display()

...........................................................................
======================

class example:
def __init__(self, value1, value2):
self.myVariable1 = value1
self.myVariable2 = value2

def display(self):
print(self.myVariable1)
print(self.myVariable2)

myObj = example("First Variable", "Second Variable")


myObj.display()

=========To take input and to initialize the variables with the accepted
input======
'''
def __init__(self):
self.myVariable1 =input()
self.myVariable2 =input()
'''
=============================
class Hello:
def __init__(self): #a{myVariable1=2,myVariable2=3}
self.myVariable1 =input("Enter the first value")
self.myVariable2 = input("Enter the second value")

def display(self):
print("myVariable1=",self.myVariable1)
print("myVariable2=",self.myVariable2)

a=Hello()#a{}
a.display()

===================(Purpose)Difference between a method and constructor=====


If we store the a record in an object by using methods,then every time the method
must be called to store that record.
========Example=========
class employee:

def insert(self,id,name):
self.id=id
self.name=name

#a{id=101,name=Satya}
#b{id=102,name=Harika}
#c{id=103,name=Valli}

def display(self):
print(self.id)
print(self.name)

a=employee() #a{}
b=employee() #b{}
c=employee() #c{}
d=employee() #d{}
.
.
#calling the methods
a.insert(101,'Satya') #We have to create the object n call the method
b.insert(102,'Harika') #for each record.Then only the record will be inserted
c.insert(103,'Valli')
.
.
.
.
.
z.insert(1000,'mm')

a.display()
b.display()
c.display()

'''
op:
101
Satya
102
Harika
103
Valli

'''
Note:
We have to create the object n call the method for each record.Then only the
record will be inserted.
If we want to insert 100 records,then 100 times the insert() must be called.

But,if we use a constructor,at the time of object creation itself the data will be
stored in that object.So no need to call anything to store a record unlike a
method.

=========difference between classname.variable and self.variablename written inside


a method(Not outside the class)if both class variables and constructor variables
are available==============================

class c1:
x = 100

width=20
height=20 #variables of class(Called using c1.variablename)
depth=20

def __init__(self): #o1


self.width = 10
self.height = 10 #variables of constructor(Called using self.variablename)
self.depth = 10

def area(self):
print self.width *self.height * self.depth#1000
#If we write self.variablename inside the method,the values
#of variables inside the constructor will be called

print c1.width * c1.height * c1.depth # 8000


# If we write classname.variablename inside the method,the values
# of variables inside the class will be called

def display(self):
print "Directly c1.x =", c1.x #100 #self.variablename and
#classname.variable name both is same

print "Through self c1.x= ",self.x #100

o1 = c1()
o1.area()
o1.display()

===================(Purpose)Difference between a method and constructor=====


If we store the a record in an object by using methods,then every time the method
must be called to store that record.
========Example=========
class employee:
def insert(self,id,name):
self.id=id
self.name=name

#a{id=101,name=Satya}
#b{id=102,name=Harika}
#c{id=103,name=Valli}

def display(self):
print(self.id)
print(self.name)

a=employee() #a{}
b=employee() #b{}
c=employee() #c{}
d=employee() #d{}
.
.
#calling the methods

a.insert(101,'Satya') #We have to create the object n call the method


b.insert(102,'Harika') #for each record.Then only the record will be inserted
c.insert(103,'Valli')
.
.
.
.
.
z.insert(1000,'mm')

a.display()
b.display()
c.display()

'''
op:
101
Satya
102
Harika
103
Valli

'''
Note:
We have to create the object n call the method for each record.Then only the
record will be inserted.
If we want to insert 100 records,then 100 times the insert() must be called.

But,if we use a constructor,at the time of object creation itself the data will be
stored in that object.So no need to call anything to store a record unlike a
method.

==================Initializing using a constructor============


class employee:

def __init__(self, id, name):

self.id = id
self.name = name

def display(self):
print("The employee id is:", self.id)
print("The employee name is:", self.name)

a = employee(101, "Satya")#a{id=101,name=Satya}
b = employee(102,"Raghu")
c = employee(103,"Rashmi")
d = employee(104, "Raj")

a.display()
b.display()
c.display()
d.display()

===========Another example to understand that=======

class student :
cnt=0
def __init__(self,name,course,phno) :
self.name=name
self.course=course
self.phno=phno
student.cnt=student.cnt+1
def display(self) :
print("Name :",self.name)
print("Course : ",self.course)
print("Phno :",self.phno)
print("********************")
a=student('Hari','unix',999)
b=student('Sai','Python',272727)
c=student('Padma','Oracle',88888)
a.display()
b.display()
c.display()
print("Total no of students : ",student.cnt)

'''
op:
Name : Hari
Course : unix
Phno : 999
********************
Name : Sai
Course : Python
Phno : 272727
********************
Name : Padma
Course : Oracle
Phno : 88888
********************
Total no of students : 3

'''
So if there is any common functionality for all the objects,write the logic for
that functionality inside a constructor.For example,if a company want to give bonus
to all the emloyees and if u write that bonus logic inside a method,then for every
employee you have to call that method(emp1.bonus(),emp2.bonus(),etc).
So,use a constructor to write the bonus logic.
So,we have to use a method if a logic is specific to a particular object(employee).
We have to use a constructor if over all the objects(employees), the same logic is
to be applied.

============== seek() =====================


seek() : To place pointer at required position in the file.

fileobject.seek(no.of bytes,offset)

Ex:
x.seek(5,1)

offset ===> 0(beginning) 1(current) 2(ending)

===================two.py=========

# example of parameterised constructor,


# creaing objects at runtime

class student:
cnt = 0

def __init__(self, name, course, phno):


self.name = name
self.course = course
self.phno = phno
student.cnt = student.cnt + 1
row = self.name + "," + self.course + "," + self.phno
print(row, type(row))
fo.write(row)
fo.write("\n")
print("saved")

def display(self):
print("Name :", self.name)
print("Course : ", self.course)
print("Phno :", self.phno)
print("********************")

fo = open("stud.txt", "w+")#Opens a file with both writing and reading


while True: #To continuously prompt for the input
ans = input("To continue [y/n] : ")
if ans in "nN": break
x = input("Enter student name : ")
y = input("Enter course : ")
z = input("Enter phno:")
a = student(x, y, z)

fo.seek(0, 0) #this instruction will be executed only after the complete


termination of
#the loop
k = fo.read()
print(k)
fo.close()
print("Total no of students : ", student.cnt)
'''
op:
To continue [y/n] : y
Enter student name : satya
Enter course : computers
Enter phno:9876556789
satya,computers,9876556789 <type 'str'>
saved
To continue [y/n] : n
satya,computers,9876556789

Total no of students : 1
File will be created in the below location
C:\Users\user\PycharmProjects\CoreAppsPython\constructors
'''

=================Three.py===========
class ComplexNumber:

def __init__(self,r ,i): # parametrized constructor


self.real = r
self.imag = i

def getData(self): # class method


print self.real,"+",str(self.imag)+"j"
c1=ComplexNumber(2,3)
c1.getData()
c2=ComplexNumber(3,4)
c2.getData()
#del c1.imag
#c1.getData()
'''
op:
2 + 3j
3 + 4j
Note:3 is a no. that cannot be concatenated to a string j.
So,we have to convert integer to string

==========Destructors============
Destructor :
It is also a special method of a class.It is used to deallocate the resources
acquired by an object during its life cycle.
(like closing of opened files, closing database connections, cleaning up the buffer
or
cache etc).
It executes automatically whenever the control comes out of the block/whenever the
control come out of the object.

Destructors will be executed in the opposite order of constructors in any


particular block.

Garbage collector will deallocate the memory of the object.

Syntax:
The name of the destructor is :

def __del__(self) :
pass

To call the garbage collector:

del objectName

That is,del keyword will call the garbage collector

===========Destructors will be executed when the object is not in


use==================
class TestClass:

def __init__(self):
print("Constructor")

def __del__(self):
print("Destructor")

obj=TestClass()
print("obj=",id(obj))

del obj
#print("Address of obj=",id(obj))

==========================
class c1 :
def __init__(self) :
print(" I am constructor")
def __del__(self) :
print(" I am destructor")
def f1() :
a=c1()
b=c1()
x=c1()
f1()
y=c1()

OP:
I am constructor.....x
I am constructor...a
I am constructor....b
I am destructor................b
I am destructor................a
I am constructor....y
I am destructor...........y
I am destructor...........x

___________________________
# example of desrtuctor

class c1 :
i=0
def __init__(self) :
c1.i=c1.i+1
print("object is created,now total is :",c1.i)

def __del__(self) :
c1.i=c1.i-1
print("object is deleted, now total is : ",c1.i)

def f1() :
a=c1()
b=c1()

#x a b ba y yx

x=c1()
f1()
y=c1()
del x #del is used to deallacate the memory of the object (calling the gc
explicitly)
del y #calling gc explicitly

OP:

object is created,now total is : 1


object is created,now total is : 2
object is created,now total is : 3
object is deleted, now total is : 2
object is deleted, now total is : 1
object is created,now total is : 2
object is deleted, now total is : 1
object is deleted, now total is : 0

==============================Abstraction===================
A class is a model for creating objects(or instances). A class contains
variables(attributes),Methods(actions).Anything written in class is applicable to
all of
its objects. If a method written in class, it is available to all its class
objects.
If we create 3 objects for particular class, then all 3 objects get copy of that
class methods.

Definition of abstraction:

The term abstraction represents "incompleteness".

Representing the essential features by hiding the background details is called


as abstraction.

Method without body is called as an abstract method.


That method must be decorated using the following decorator " @abstractmethod"

=============================================
class Myclass:
def calculate(self,x):
print("square is ",x*x)

obj1 = Myclass()
obj1.calculate(2)

obj2 = Myclass()
obj2.calculate(3)

obj3 = Myclass()
obj3.calculate(4)

If all objects requirement is same i.e calculating square, then it is fine.

But some times the requirement of objects will be different and entirely dependent
on
the specific object only.For example in previous example first objects wants to
calculate square and second wants square root and third wants cube value.
In such cases how to write calculate() in Myclass ?

Since, the calculate() method has to perform 3 different tasks depending on the
object,
we can not write the code to calculate square value in the body of calculate
method.
On the other hand, if we write 3 different methods like
calculate_square(),calculate_sqrt() and
calculate_cube() in Myclass, then all 3 methods are available to all 3 objects
which is
not advisable. when each object wants one method,providing all the 3 does not look
reasonable. To serve each object with the one and only required method,
we can follow the steps.

1. First, lets write calculate() in Myclass. This means every object wants to
calculate something.
2. If we write body for calculate() method , it is commonly available to all the
objects.
So let's not write body for calculate() method. Such a method
is called abstract method. Since we write abstract method in Myclass ,
it is called abstract class.

3. Now derive a sub class Sub1 from Myclass, so that the calculate() method is
available
to the sub class. Provide body for calculate method in sub1 such that it
caluclates
square value. Similarly, we create another subclass sub2 where we write the
caluclate()
method with body to calculate square root value.We create the third class
calculate()
to calculate cube value.

4. It is possible to create objects for the sub classes. Using these objects, the
respective methods can be called and used. Thus , every object will have
it requirement fulfilled.

Abstract method and class :


========================

An abstract method is a method whose action is redefined in the subclasses as per


the
requirement of the objects. Generally abstract methods are written without body
since
their body will be defined in the subclasses anyhow. But it is possible to write an

abstract method with body also. To mark a method as abstract, we should use the
decorator @abstractmethod. On the other hand , a concrete method is method with
body.

An abstract class is a class that generally contains some abstract methods. Since
abstract class contains abstract methods whose implementation(or body)
is later defined in the subclasses, it is not possible to estimate the total memory

required to create the object for the abstract class. So PVM can not create objects

to an abstract class.

Once abstract class is written , we should create sub classes and all the abstract
methods should be implemented(body should be written) in the subclases.
Then, it is possible to create objects to the sub classes.

import math

class Myclass():

def calculate(self,x):
pass

class Sub1(Myclass):
def calculate(self,x):
print('square value is ',x*x)

class Sub2(Myclass):
def calculate(self,x):
print('square root=',math.sqrt(x))

class Sub3(Myclass):
def calculate(self,x):
print('cube value=',x**3)

obj1 = Sub1()
obj1.calculate(10)

obj2 = Sub2()
obj2.calculate(100)

obj3 = Sub3()
obj3.calculate(10)
===========Purpose of abstraction=======================

class Student:

def jFee(self):
#java fee logic

def pFee(self):
#python fee logic

def dFee(self):
#dotnet fee logic

s1=Student()#s1{jFee(),pFee(),dFee()}
s1.jFee()
s2=Student()#s2{jFee(),pFee(),dFee()}
s2.pFee()
s3=Student()#s3{jFee(),pFee(),dFee()}
s3.dFee()

=============================

class Student:

def fee(self): #method witout body


pass
class jStudent(Student):

def fee():
#Logic for Java Fee

class pStudent(Student):

def fee():
#Logic for python Fee

class dStudent(Student):
def fee():
#Logic for dotnet Fee

j=jStudent()#j{fee()}
j.fee()
p=pStudent()#p{fee()}
p.fee()
d=dStudent()#d{fee()}
d.fee()

================without abstraction============not req=


class Student:
def jfee(self):
print("fee for java is 7000")
def pfee(self):
print("fee for python is 8000")
def dfee(self):
print("fee for dotnet is 9000")

s1=Student()
#s1{jfee() pfee() dfee()}

s2=Student()
#s2{jfee() pfee() dfee()}

s3=Student()
#s3{jfee() pfee() dfee()}
All the objects are getting all the methods/bodies which is not necessary as memory
will be wasted.

=====================With abstraction==========================================
The term abstracion represents incompleteness.

Definition:
Representing the essential features by hiding the background details is called as
abstraction.

Abstract method:
Method without body is called as an abstract method.

Concrete method/Normal method/non abstract method:


Method with body

Abstract class:
If a class is having atleast one abstract method,then it is called as an abstract
class.

Syntax to create an abstract method:

@abstractmethod
def methodName():
pass

Syntax to create an abstract class:

class ClassName(ABC):
#body

ABC is called as Abstract Base Class.

We should not create object for the abstract class.

===============================
class Student:

def fee(self): #abstract method


pass

class pyStudent(Student):
def fee(self):
print("fee logic for python")

class jaStudent(Student):
def fee(self):
print("fee logic for java")

class dotStudent(Student):
def fee(self):
print("fee logic for dotnet")

p=pyStudent()
#p{fee() body in pyStudent class will only come}

j=jaStudent()
#j{fee() body in jaStudent class will only come}

d=dotStudent()
#d{fee() body in dotStudent class will only come}

======================Example 1==================================
==================StudentDemo.py=======================
class Student:
def regFee(self):
print("100 rupees is the registration fee for any course")

def fee(self):
pass
===================pythonStudent.py=================
from StudentDemo import Student
class pythonStudent(Student):
def fee(self):
corePython=4000
advancedPython=4000
pythonTotalFee=corePython+advancedPython
print("The fee for complete python is:",pythonTotalFee)

p=pythonStudent() #p{regFee(),fee()}
p.regFee()
p.fee()
===============javaStudent.py=====================
from StudentDemo import Student
class javaStudent(Student):
def fee(self):
coreJava = 2000
advancedJava = 3000
frameworks=2000
javaTotalFee =coreJava+advancedJava+frameworks
print("The fee for complete java is:", javaTotalFee)
j=javaStudent() #j{regFee(),fee()}
j.regFee()
j.fee()
=====================Actually abstraction should be implemented in the following
way==========
from abc import ABC,abstractmethod
class Student(ABC):
def regFee(self):
print("100 rupees is the registration fee for any course")

@abstractmethod
def fee(self):
pass
Note:
We cannot create object for an abstract class
To indicate the method as abstract,we are importing "abstractmethod".
To indicate that class is abstract,we are importing "ABC".

If i dont mention this @abstractmethod decorative,it will be like a normal method


whose body is going to be provided in future.

pass:We will use this when we know the body to be written perfectly but we want to
write that body in feature.
@abstractmethod and pass: will be used when we want to indicate that method as an
abstract method.Any how we will use abstraction to overcome the problem described
above.

ABC means Abstract Base Classes.It is not mandetory to import and use ABC.To
indicate clearly that the
parent(base) class is abstract we will just use it.(In java we will directly
preceed
the class with the abstract keyword.)

==============Example 2===========================

Car ==> Maruthi,Santro


m s

Fuel tank --> openTank and fill fuel. which is common for all
so openTank() concrete method.

Steering --> maruthi - manual steering


santro - power steering
Breaks --->
maruthi - Hydraulic breaks
santro - Gas breaks

Car
--openTank() -->NM
--steering() -->ABM
--breaks() -->ABM

====================abstractdemo.py======================
from abc import ABC,abstractmethod
class Car(ABC):

def openTank(self):
print('Fill the fuel into the tank ')

@abstractmethod
def steering(self):
pass

@abstractmethod
def braking(self):
pass

==========================Maruthi.py=========================
from abstractdemo import Car

class Maruthi(Car):

def steering(self):
print("maruthi uses manual steering")

def braking(self):
print("maruthi uses hydraulic brakes")
print("apply breaks and stop it")

m = Maruthi()
m.openTank()
m.steering()
m.braking()

=====================Santro.py==========================
from abstractdemo import Car

class Santro(Car):

def steering(self):
print(" Santro uses power steeting")
print(" Drive the car")

def braking(self):
print("Santro uses gas breaks")
print(" Apply breaks and stop it")

s = Santro()
s.openTank()
s.steering()
s.braking()

=============
class Bank: ---->interface
def withdraw(self):
pass
def deposit(self):
pass
def bal_eqry(self):
pass
def exit(self):
pass

class ICICI(Bank):

=================
Interfaces:
============

Abstract class is a class which contains some abstract methods as well as


concrete methods. If the class contains only abstract methods and there are no
concrete methods then it becomes interface. It means interface is an abstract class

contains only abstract methods. In java an interface is created using keyword


'interface'
but in python an interface is created as an abstract class only. The interface
concept is not explicitly available in python.

from abc import *


class Myclass(ABC):
@abstractmethod
def connect(self):
pass
@abstractmethod
def disconnect(self):
pass

class Oracle(Myclass):
def connect(self):
print("connecting to oracle database")
def disconnect(self):
print("Disconnected from oracle database")
class Mysql(Myclass):
def connect(self):
print("connecting to mysql database")
def disconnect(self):
print("Disconnected from mysql database")

class Database:

str = input("Enter database name") #Oracle


print("Globals=,"globals)
classname = globals()[str] #globals()[Oracle]

x=classname()

x.connect()
x.disconnect()

output:

Enter database nameOracle


Globals= <built-in function globals>
connecting to oracle database
Disconnected from oracle database
globals():
--------
In the main program , the programmer is supposed to create objects to the
sub classes without knowing their names. This is done using globals() function.

The globals() function returns a dictionary containing current global names and
globals()[str] returns the name of the class that is in 'str'

===========================Multi threading=======================
Performing multiple tasks simultaneously is called as multi tasking.
To achieve multi tasking,we will use multi threading.
Let us say, a large code is there that can perform 3 tasks.Let us divide the code
into 3 pieces.If we run that complete code, 3 tasks will be performed.
The point to be noted here is,these 3 tasks will be performed one after the other.
So lot of time is required to complete these tasks.
We can execute these 3 pieces of codes simultaneously, we will use multi threading.

Every program will be executed by a thread.Name of that thread is "main"

-----
----- .................................2 hrs
------ .......task 1 (t1)
------
-----

-----
------ ..................................4 hrs
------ .....task 2 (t2)
-----
-----

------
------
------ ....task 3 (t3)
------
------

thread --->CPU

Multi threading:

Ex:
Consider the yahoo application
It have messenger,mail,greetings,shopping,games.

Let us say,using messenger,i am chatting with my friend but he did not give
reply.So i am waiting for the reply.
Instead of waiting,i will go to greetings and will download a greeting.Till the
greeting is downloaded,i will not wait.
i will do shopping.While doing shopping,my friend replied.Now, a pop up will come
with some beep sound
as this have first priority and hence the contol went to msg.

So i am able to perform the tasks simultaneously without waiting.This can be done


using
multi threading.
We can achieve multi threading using functions.

def f1():
---
--- chat logic
---
---

def f2():
---
--- greetings download logic
---
---

def f3():
---
--- online shopping logic
---
---

f1()
f2()
f3()

Here,f1 f2 f3 are the diferent parts of the same program.

When ever we call f1,f1 defition will be executed.Let us say f1 require 1 hour to
complete the execution.
Only after f1 completes its execution(1 hours),then only the cursor will go to f2
and then to f3.
So,this is not multi threading as only one part of progam will be executed at a
time.

Let us say in f1(), if the cursor went to 4th line and it is waiting for the
printer.Say,printer
is busy.We dont know when it will become free.Here, only after the execution of 4th
statement,the cursor will go to
the 5th statement.

Instead of waiting there,it should execute f2().

Actually in f2(),we have written code to back up the data.It shows that 3hours is
required to back up the data.

Instead of waiting,it should go to f3.


Now it is running f3(),mean while,if the printer becomes free,automatically the
cursor should go to
f1().So,it should give first priority to f1().Then to f2() and then to f3().

We can achieve multi threading if the tasks are independent.


If f2 depends on f1 and f3 depends on f2,then threading is not possible.

if we call like...
f1()
f2()
f3(),

then they will be executed one by one.If we want then to get executed
simultaneously,we have to implement
threading over them.

In python,we have a module called as "threading"."Thread" is a class in this


"threading" module.

=============calculating the squares and cubes of numbers without using


threads==========

import time

def cal_square(numbers):#2,3,8,9
print("calculate the squares of the numbers")
for n in numbers:
time.sleep(0.2)# Waiting for some activity.Introducing artificial
delay.CPU is waiting
print("square:",n*n)

def cal_cube(numbers):#2,3,8,9
print("calculate the cubes of the numbers")
for n in numbers:
time.sleep(0.2)
print("cube:", n*n*n)

arr=[2,3,8,9]
t=time.time() # 17:32

cal_square(arr)
cal_cube(arr)

print("Program got executed in:",time.time()-t) #To check the time taken to execute
the
#program
print("Completed all the tasks")

Op:
calculate the squares of the numbers
square: 4
square: 9
square: 64
square: 81
calculate the cubes of the numbers
cube: 8
cube: 27
cube: 512
cube: 729
Program got executed in: 1.60399985313
Completed all the tasks
Note:
Taken 1.60399985313 sec to execute

=============calculating the squares and cubes of numbers using threads==========


==============threading.py=======================
class Thread:
def __init__(self,target,args):

pass
====================================
import time
import threading

def cal_square(numbers):
print("calculate the squares of the numbers")
for n in numbers:
time.sleep(0.2) #Waiting for some activity..Artificially adding delay
print("square:",n*n)

def cal_cube(numbers):
print("calculate the cubes of the numbers")
for n in numbers:
time.sleep(0.2)
print("cube:", n*n*n)

arr=[2,3,8,9]
t=time.time()
#Creating two threads
t1=threading.Thread(target=cal_square,args=(arr,))#If you create an object for the
Thread
#class,that object will become
your
#thread
t2=threading.Thread(target=cal_cube,args=(arr,))

t1.start()
t2.start()

t1.join()
t2.join()

print("Program got executed in:",time.time()-t)


print("Completed all the tasks")

Op:
calculate the squares of the numbers
calculate the cubes of the numbers
square:4
cube:8

square:9
cube:27

square:64
cube:512

square:81
cube:729
Program got executed in: 0.805000066757
Completed all the tasks

Note: Taken 0.805000066757 ns to execute

=====================join()=============================
If all the threads are given back to the CPU at a time by the PVM,then the
performance
will be increased.For this,we will use join().

Example:

t1.join()
t2.join()

join() is also used to eliminate orphan threads in the program.


An orphan thread is one whose parent was dead..............

Consider 3 threads t1,t2,t3....that are going to execute 3 pieces of codes


respectively.

---------
--------- -------->t1(parent)3ns
---------
---------

---------
--------- -------->t2(child)4ns
---------
---------
---------

---------
--------- -------->t3(child)5ns
---------
---------
---------
---------

The parent thread(t1) will complete its execution in 3ns and will die.
So,t2 and t3 will become orphans.If orphan threads are present in our
program,it will become unstable.

So,if we have to write..........


t2.join()
t3.join(),then
parent thread will wait for t2 and t3 to join.

================Without Threads(Running one by one)================


import time
from threading import Thread
#from package import class

def f1(i):
print "Thread ",i,"is going to sleep for 5 seconds"
time.sleep(5)#Waiting for some activity..Artificially adding delay
print "Thread ",i," woke up"
f1(1)
f1(2)
f1(3)

'''
OP:
Thread 1 sleep for 5 seconds
Thread 1 woke up
Thread 2 sleep for 5 seconds
Thread 2 woke up
Thread 3 sleep for 5 seconds
Thread 3 woke up
'''

f1 completely executes the definition and then only it will go to f2 calling place.
Then,f2 completely executes the definition and and then only it will go to f3.
Even though there is any resource waiting activity(or processing activity) in
f1,the control should
wait till that resource is released,used and gets also till everything gets done.
is available

==============Using Threading(Parallel processing)===================


import time
from threading import Thread

def f1(i):
print "Thread ",i,"sleep for 5 seconds"
time.sleep(5) #Execution will be paused for 5 seconds
print "Thread ",i," woke up"

for i in range(1,10):
t=Thread(target=f1,args=(i,))
t.start() #To start a thread

OP:
Thread 1 sleep for 5 seconds
Thread 2 sleep for 5 seconds
Thread 3 sleep for 5 seconds
Thread 4 sleep for 5 seconds
Thread 5 sleep for 5 seconds
Thread 6 sleep for 5 seconds
Thread 7 sleep for 5 seconds
Thread 8 sleep for 5 seconds
Thread 9 sleep for 5 seconds
Thread 1 woke up
Thread Thread Thread 324 woke up woke up woke up

Thread Thread 65 woke up woke up

Thread Thread Thread 987 woke up woke up woke up

Note:
In the above process,object was created for Thread class for 9 times.So,9 threads
were created.
These 9 threads will be activated and they will perform parallel processing.

Once the cursor encounters the sleep(5),it will leave that and activates another
thread and will make
that newly created thread to perform the next activity.

t=Thread(target=f1,args=(i,))

Creating an object for Thread class.Then constructor of that Thread class will be
called.
class Thread
{
Thread(target,args) #Target receives function as parameter,args takes tuple as a
parameter.
{

}
}

args=(i,) ===>tuple

target=f1,args=(i,) ====>Named arguments

for i in range(1,10):
t=Thread(target=f1,args=(i,))
t.start()

first 1 will go into i.Then,f1() will be called with a parameter 1

If we close the application,then only all the threads will be dead.Because,main


process will be killed
if we close the application.

Advantage:
Performance of the application will be greately improved.
=========================================
from threading import Thread
import time

def timer(name,delay,repeat):
print("Timer: " + name + "started")
while repeat > 0:
time.sleep(delay)
print(name+ ":" + time.ctime(time.time()))
repeat -=1
print("Timer: " + name + "Completed")

def simple():
print "hello world.."
t1 = Thread(target=timer,args=("Timer1",1,5))
t2=Thread(target=timer,args=("Timer2",2,5))
t1.start()
t2.start()
print("Main completed")

simple()
print "I am done.."

OP:

hello world..
Timer: Timer1started
Timer: Timer2started
Main completed
I am done..
Timer1:Wed May 16 17:40:24 2018
Timer2:Wed May 16 17:40:25 2018
Timer1:Wed May 16 17:40:25 2018
Timer1:Wed May 16 17:40:26 2018
Timer2:Wed May 16 17:40:27 2018
Timer1:Wed May 16 17:40:27 2018
Timer1:Wed May 16 17:40:28 2018
Timer: Timer1Completed
Timer2:Wed May 16 17:40:29 2018
Timer2:Wed May 16 17:40:31 2018
Timer2:Wed May 16 17:40:33 2018
Timer: Timer2Completed

Concurrent programming:
Executing the tasks or parts of the
program simultaneously is called 'concurrent programming'

When more than one thread is running at a time, the data of one thread is available
to
another thread. In such cases, there is possibility that the data may undergo
unwanted
changes. This happens especially when more that one thread is acting on data
simultaneously.
This will lead to wrong results. It means the PVM is not thread safe. Hence PVM
uses an
internal global interpreter lock(GIL) that allow only a single thread to execute at

any given moment.

Uses of Threads :
-----------------

Threads are highly useful when we want to perform more than one task
simultaneously.
this is also known as 'concurrent programming'. This makes the threads to be used
in the
following situations.
* Threads are mainly used in server side programs to serve the needs of multiple
clients
on a network or Internet. On Internet a server machine has to cater to the needs of

thousands of clients a time, thus can handle several clients.

* Threads are also used to create games and animations. Animation means moving
objects
from one place to other place. In many games , generally we have to perform more
than one
task simultaneously. There, threads will be of invaluable help. For example in a
game,
a flight may be moving from left to right. A machine gun should shoot it, releasing
the
bullets at the flight. There two tasks should happen simultaneously. for this
purpose
we can use 2 threads, one thread will move the flight and other one will move the
bullet,
simultaneously towards the flight.

============== Program to find the currently running thread in


python================

import threading

print("Program to find current thread")

print("Currently running thread:",threading.current_thread().getName())

=========Ways of creating threads in python=================


Python provide 'Thread' class of threading module that is useful to create threads.
To create your own thread, you are supposed to create an object Thread
class(t1=threading.Thread(target=cal_sum)).
The following are the different ways of creating our own threads in python.

i)Creating a thread directly without classes(our own class).That is by using normal


functions.
ii)Creating thread by creating sub class to "Thread" class.
iii)Creating threads using our own classes(without creating sub class to thread
class).

===================================================================================
=
i) Creating a thread directly without classes.
============Program to create a thread without creating our own
class==================
==========Without passing arguments to the function==========
from threading import Thread

def display():
print("This is my thread programming")

for i in range(5): # [0,1,2,3,4] 5 threads will be created


t = Thread(target=display) #t is the thread object
t.start() #goes to display() and executes it.
print(t.getName()) #To see the name of the thread.Thread-1 is the name of the
first #thread by default

output:
This is my thread programming
Thread-1
This is my thread programming
Thread-2
This is my thread programming
Thread-3
This is my thread programming
Thread-4
This is my thread programming
Thread-5

==========Passing arguments to the function==========


from threading import Thread

def display(str):
print(str)

for i in range(5):
t = Thread(target=display, args=("This is my first thread programming",))
t.start()
print("Executed display by",t.getName())

output:
This is my first thread programming
Executed display by Thread-1
This is my first thread programming
Executed display by Thread-2
This is my first thread programming
Executed display by Thread-3
This is my first thread programming
Executed display by Thread-4
This is my first thread programming
Executed display by Thread-5

ii)Creating Thread by creating a child class to the "Thread" class.


========================================================================
Since the 'Thread' class is already created by the python people in threading
module,
we can make our class as a sub class to Thread class so that we can inherit the
functionality of Thread class. This can be done by writing the following statement.

==========threading.py================
class Thread:
def run(self):
----
---- #some default logic
----
=============Process.py============

class A(Thread):
def run(self):
----
---- #my own logic #overriding
----

====Program to create a thread by creating a sub class to the "Thread" class=======

from threading import Thread

class MyThread(Thread):

# override the run() method of thread class


def run(self):
for i in range(1,6):
print(i)
t1 = MyThread() #t1 is our own thread
t1.start()

Note:
If we create an object for the Thread class,then that object will become our own
thread.
In the above program,t1 is indirectly an object of Thread class.So, t1 is our own
thread.

==========================Giving a call to start() instead of calling run()=====

import time
from threading import Thread

class MyThread1(Thread): #EVEN NOS


# override the run() method of thread class
def run(self):
for i in range(0,12,2):
time.sleep(0.2)
print(i)

class MyThread2(Thread):
#override the run() method of the class
def run(self):
for i in range(1,11,2):
time.sleep(0.2)
print(i)

t1 = MyThread1()
t2 = MyThread2()
t1.start() #run
t2.start() #run
t1.join()
t2.join()

===============================================
If you give a call to the run(),the cursor will go to run().
But,if you give a call the start(),then ----

1)The cursor will go to the run() and


2)The cpu will be switched among te different pieces of codes
==================================================
Thread class Methods:
------------------------

Below are the list of methods and properties available in Thread class

Method or Property Description


================== ============
t.start():
Starts the thread. It must be called at most once per thread object.It will call
the run() method from it.

t.sleep([timeout]):
Pauses the program execution for the time specified in it.'timeout' is a floating
point number specifying a timout for the operation in seconds(or fraction of
seconds)

t.is_alive():
Returns True. If the thread is alive in memory and False otherwise.A thread will be
alive() only if it is there inside the run().

t.setName(name):
To set a name to a particular thread

t.getName():
To see the name of a thread using this method.

t.name
We can see the name of a thread using this property even

=================program on methods of a thread==========================


import time
from threading import Thread

class MyThread1(Thread): #EVEN NOS


# override the run() method of thread class
def run(self):
for i in range(0,12,2):
time.sleep(0.2)
print(i)

t1 = MyThread1()

print("Getting the default name of the thread t1 using 'getname()'


method",t1.getName())#Thread-1
print("Getting the default name of the thread t1 using the 'name'
property",t1.name)#Thread-1

t1.setName("HelloThread")
print("Name kept by us for the thread t1",t1.getName())#HelloThread

print(t1.is_alive())#False
t1.start()
print(t1.is_alive())#True
t1.join()
print(t1.is_alive())#False

====================================================
iii)Creating threads using our own classes.
=====================================================
from threading import *
from time import *

class service:

def __init__(self, str): #obj1,prepare food #obj2,parcel food


self.str = str #obj1{str=prepare food} #obj2{str=parcel food}

def parcelservice(self): #obj1


for i in range(1, 5):
print(self.str, " : ", i)
sleep(0.1)

obj1 = service("prepare food") #service(obj1,preaparefood)


obj2 = service("parcel food") #service(obj2,parcelfood)

t1 = Thread(target=obj1.parcelservice)
t2 = Thread(target=obj2.parcelservice)

t1.start()
t2.start()

output:
prepare food : 1
parcel food : 1
prepare food : 2
parcel food : 2
prepare food : 3
parcel food : 3
prepare food : 4
parcel food : 4

====================Synchronization======================

Critical Section:
That piece of code which is needed to be executed by multiple threads
is called as critical section.

Synchronization:
Preventing more than one thread to execute the
critical section simultaneously is called as synchronization.

=========================Achieving synchronization using locks===============


import threading
import time

tlock = threading.Lock() #Creating an object for the Lock class of threading


module
def timer(name,delay,repeat):
print ("Timer " + name + "started")
tlock.acquire()
print (name + " has acquired the lock")
while repeat > 0: #some important logic that has to be executed only by one
thread at a time
time.sleep(delay)
print(name + ":" +str(time.ctime(time.time())))
repeat -= 1
print(name + " is releasing the lock")
tlock.release()
print("Timer: " + name + " completed..")

t1 = threading.Thread(target=timer, args=("Thead1",1,5))
t2 = threading.Thread(target=timer, args=("Thread2",2,5))
t1.start()
t2.start()

OP:

Timer Timer1strated
Timer1has acquired the lock
Timer Timer2strated
Main completed
Timer1:Fri Feb 09 17:19:10 2018
Timer1:Fri Feb 09 17:19:11 2018
Timer1:Fri Feb 09 17:19:12 2018
Timer1:Fri Feb 09 17:19:13 2018
Timer1:Fri Feb 09 17:19:14 2018
Timer1 is releasing the lock
Timer: Timer1completed..
Timer2has acquired the lock
Timer2:Fri Feb 09 17:19:16 2018
Timer2:Fri Feb 09 17:19:18 2018
Timer2:Fri Feb 09 17:19:20 2018
Timer2:Fri Feb 09 17:19:22 2018
Timer2:Fri Feb 09 17:19:24 2018
Timer2 is releasing the lock
Timer: Timer2completed..
======================================================
======================================================
======================================================
======================================================
======================================================
======================================================
======================================================
==================Semaphore===========================
Thread synchronization can be done 2 ways.
1. Using locks
2. Using semaphores

A semaphore is an object that provides synchronization based on counter. A


semaphore is created as an object of semaphore class as

l = Semahore(countervalue) #Here counter value is bydefault 1

when acquire method called,counter value is decremented by 1


and when release method called, counter value will be incremented by 1
in previous example use Semaphore method instead of lock()

========================Exception Handling=================================
Exception:
It is a run time error.That is,at the time of execution of the program,because of
the
input given by the user,if any problem ocucrs,then that is called as an exception.

It deviates the program from normal flow of execution.

As soon as an exception occur,the PVM will terminate the program execution abruptly
with
some message which is not understandable by the user.

This will frustate the user as he does not know what has happened.

Exception Handling:
Representing the exact problem to the user by displaying a simple understandable
message is called as Exception Handling.In that case,the user can read this message
and will give the proper input from next time.

a=int(input("Enter a number1 : "))#10


b=int(input("Enter a number2 : "))#0
c=a/b
print(c)
print("Successfully divided.")

output:
Enter a number1 : 10
Enter a number2 : 0
Traceback (most recent call last):
File "C:/Users/user/PycharmProjects/packs1030batch/exception1.py", line 4, in
<module>
c=a/b
ZeroDivisionError: division by zero

The user cannot understand the above message.


You should represent the problem properly to the user.(That is called as handling)

To handle the exceptions,we will use try,except and finally keywords.

try:
Those instructions that may probably raise exception will be kept under try block.

try:
a=
b=
c=a/b
except:
Used to handle the exception(Msgs).
We will write the messages in this block.

Syntax of except:

except TypeOfException:
#Msg

=============================================
Every exceptional situation is represented by a predefined class in python.

====IndexError=========

x=[10,20,30]

print(x[9]) #IndexError

====NameError========
a=10
b=20
print(a)
print(b)
print(c) #NameError

=====IndentationError=====
IndentationError
a=10
b=20
print(a)#IndentationError

======TypeError===========
a="John"
b=int(a)#TypeError

========KeyError===========
a={10:"Hari",20:"Raghu"}
print(a[30])#KeyError

========ZeroDivisionError=====
a=10
b=0
c=a/b #ZeroDivisionError
==============================================
Principle:
If really an exceptional instruction is encounterd in the "try" block,then the
cursor
will go the respective "except" block,print the message and then the program will
be
terminated.If there is no exception in the try block,then the complete try block
will be executed and all the except blocks will be skipped.
==============================================
try :
a=int(input("Enter a number1 : "))#10
b=int(input("Enter a number2 : "))#0
c=a/b
arr=[2,3,4,5]
index=int(input("Enter the index value:"))#2
print(arr[index])
except ZeroDivisionError :
print ("Sorry. Second number can't be a zero. Enter second number alwasys as
non-zero")
except IndexError :
print("Enter a proper index")
except : #Remaining exceptions will be caught here.Unpredictable exceptions will be
caught here
print( "Unknown Error.Pls check your input")
else :
print(c)
print("Successfully divided.")

OP:

Enter a number1 : 9
Enter a number2 : 0
Sorry. Second number can't be a zero. Enter second number alwasys as non-zero

Enter a number1 : 4 (In lower versions)


Enter a number2 : "h"
Make sure both must be numbers.

Enter a number1 : asd


Unknown Error.

===========================same==================
while True:
try:
a = int(input("Enter a number1 : "))
b = int(input("Enter a number2 : "))

c = a / b
arr = [2, 3, 4, 5]
index = int(input("Enter the index value:"))
print(arr[index])

except ZeroDivisionError:
print("Sorry. Second number can't be a zero. Enter second number alwasys as
non-zero")
except IndexError:
print("Enter a proper index")
except: # Remaining exceptions will be caught here.Unpredictable exceptions
will be caught here
print("Unknown Error.")
else:
print(c)
print("Successfully divided.")
break

==================================
try:
f = open('somefile.txt', 'r')
print(f.read())
f.close()
except IOError:
print('file not found')

===================================
eval():

eval() will take an expression as a parameter,evaluate that expression and produce


the
result.The expression must be passed in the form of a string.
Ex:
x=eval('2+3')
print(x)#5
=================To print the predefined msgs in case of an exception(psT() in
java)=========

try:
a=int(input("Enter a number"))
b=int(input("Enter one more number"))
c=a/b
print(c)
except ZeroDivisionError as ex:#ex is the reference
print("Predefined Message:", ex)#To print predefined message
print(type(ex).__name__)#To print the exception class
#print("Name Error encountered")#To print our own message

output:
Enter a number 10
Enter one more number 0
Predefined Message: division by zero
ZeroDivisionError
=====================To know the type of exception that have been
encountered========
try:
a=int(input("Enter a number"))
b=int(input("Enter one more number"))
c=a/b
print(c)
except ZeroDivisionError :#ex is the reference
print("second no. should be greater than zero")#To print predefined message

except Exception as e: #Exception is the parent class of all the Exceptional


classes.
#print("Unknown error")
print(type(e).__name__)

================finally============
finally:
This is also a block.
Those instructions that are to be executed for sure will be kept under finally
block.
We will put those instructions that can close the resources in the finally block.

===================================
try:
x = open("stud.txt", "r") #give the file that is there.Then AttributeError will
come
data = x.reads() #The method name should be read

except IOError:
print("Can't read data from file,because the given file doesn't exist")
except AttributeError:
print("Check the method.Mehod doesn't exist")
else:
print (data)
finally: # to close files,database and socket
x.close()
print("File closed")

Op:
Check the method.Method doesn't exist
File closed

========================================
try:
num1, num2 = eval(input("Enter two numbers, separated by a comma : "))
result = num1 / num2
print("Result is", result)

except ZeroDivisionError:
print("Division by zero is error !!")

except SyntaxError:
print("Comma is missing. Enter numbers separated by comma like this 1, 2")

except:
print("Wrong input")

else:
print("No exceptions")

finally:
print("This will execute no matter what")

output:
Enter two numbers, separated by a comma : 2 8
Comma is missing. Enter numbers separated by comma like this 1, 2
This will execute no matter what

===================User defined or custom exceptions=================


User defined exceptions are the exceptions created by us.

================To raise userdefined exceptions(our own) explicitly in our own


situation============
# define Python user-defined exceptions
class Error(Exception):
"""Base class for other exceptions"""
pass
class ValueTooSmallError(Error):
"""Raised when the input value is too small"""
pass

class ValueTooLargeError(Error):
"""Raised when the input value is too large"""
pass
class JohnError(Error):
"""Raised when the inputed value is 100"""
pass

# our main program


# user guesses a number until he/she gets it right

# you need to guess this number


number = 10

while True:
try:
i_num = int(input("Enter a number: "))#10
if i_num < number:
raise ValueTooSmallError
elif i_num==100:
raise JohnError
elif i_num > number:
raise ValueTooLargeError
break
except ValueTooSmallError:
print("This value is too small, try again!")

except ValueTooLargeError:
print("This value is too large, try again!")
except JohnError:
print("100 number belongs to John!You should not enter 100")

print("Congratulations! You guessed it correctly.")


================To raise predefined exceptions explicitly in our own
situation============
To raise predefined exceptions explicitly,no need to inherit the classes from
Exception and Error classes because they are already th children of these Exception
and Error classes.

===================================
def enterage(age):
if age < 0:
raise ValueError

elif age == 0:
raise NameError
elif age%2==0:
print("Your age is even")
else:
print("Your age is odd")

try:
num = int(input("Enter your age: "))#-10
enterage(num)
except ValueError:
print("No one will have negative age..Use comon sense")
except NameError:
print("You are so little!Your haven't completed an year yet")
except:
print("something is wrong")

======================List of common exceptions=============


Exception Cause of Error
AssertionError Raised when assert statement fails.
AttributeError Raised when attribute assignment or reference fails.
EOFError Raised when the input() functions hits end-of-file condition.
FloatingPointError Raised when a floating point operation fails.
GeneratorExit Raise when a generator's close() method is called.
ImportError Raised when the imported module is not found.
IndexError Raised when index of a sequence is out of range.
KeyError Raised when a key is not found in a dictionary.
KeyboardInterrupt Raised when the user hits interrupt key (Ctrl+c or delete).
MemoryError Raised when an operation runs out of memory.
NameError Raised when a variable is not found in local or global scope.
NotImplementedError Raised by abstract methods.
OSError Raised when system operation causes system related error.
OverflowError Raised when result of an arithmetic operation is too large to be
represented.
ReferenceError Raised when a weak reference proxy is used to access a garbage
collected referent.
RuntimeError Raised when an error does not fall under any other category.
StopIteration Raised by next() function to indicate that there is no further
item to be returned by iterator.
SyntaxError Raised by parser when syntax error is encountered.
IndentationError Raised when there is incorrect indentation.
TabError Raised when indentation consists of inconsistent tabs and spaces.
SystemError Raised when interpreter detects internal error.
SystemExit Raised by sys.exit() function.
TypeError Raised when a function or operation is applied to an object of
incorrect type.
UnboundLocalError Raised when a reference is made to a local variable in a function
or method, but no value has been bound to that variable.
UnicodeError Raised when a Unicode-related encoding or decoding error
occurs.
UnicodeEncodeError Raised when a Unicode-related error occurs during encoding.
UnicodeDecodeError Raised when a Unicode-related error occurs during decoding.
UnicodeTranslateError Raised when a Unicode-related error occurs during
translating.
ValueError Raised when a function gets argument of correct type but improper
value.
ZeroDivisionError Raised when second operand of division or modulo operation is
zero.
==============lambda,map and filter functions=========
================lambda=========
It is used to execute the programs with small logics fastly.
1. It is a keyword.
2. It is an anonymous function (Function without name)
3.This function cannot contain print and return instructions
4. It allows to write single line of expression

Syntax:
lambda arguments : expression

lambda operator can have any number of arguments, but it can have only one
expression. It cannot contain any statements and it returns a function object which
can be assigned to any variable.

That is,we can write the arguments and the logic(expression) in one line.
=====================
def add(x,y):
z=x+y
return z

x=add(2,3)
print(x)
==============================
lambda arguments : expression
===============================
add=lambda a,b : a+b #Parameter passing , calling and returning can be done
easily
x=add(10,20)
print(x)

========================================
Note:
Storing the return value of lambda function in a variable (function object) "add".

===========================

add=lambda a,b : a+b #Parameter passing , calling and returning can be done
easily

sub=lambda a,b : a-b

x=add(10,20)#30
y=sub(20,10)#10
print(x)
print(y)
==============map()================
map() takes one function and sequence of values as parameters and then,

It maps each value in the sequence to the function and will execute the logic
inside that
function and returns the the result obtained for every value.

map(function_object,iterable1,iterable2,...)
map functions expects a function object and any number of iterables like list,
dictionary, etc. It executes the function_object for each element in the sequence
and returns a list of the elements modified by the function object.

Example:
=====================Without map()=============
def multiply(x):
return x * 2

for i in range(1,5):
res=multiply(i)
print(res)
OP:
2
4
6
8

===================Using map()=================

def multiply(x):
return x * 2
x=map(multiply,[1,2,3,4]) # Calling functions,passing values all at a time.
print(list(x))

Output:
[2, 4, 6, 8]
==========================================
Let s see how we can write the above code using map and lambda.

In this case,we are passing the lambda function directly.

y=map(lambda x : x*2, [1, 2, 3, 4]) #Output [2, 4, 6, 8]


print(list(y))

Map() can any number of iterables

Ex:

a=[10,20,30,40,50]
b=[100,200,300,400,500]

c=map(lambda i,j : i+j,a,b)


print(list(c))

'''
===============================
c=map(lambda i,j : i+j,range(1,101),range(1000,1100))
print(list(c))
===============filter()=========
filter() also takes one function and sequence of values and then,
returns those values from the sequence that satisfied the condition.

Syntax:
filter(function_object,iterable) #only one iterable
===========================
map(function_object,iterable1,iterable2) #An no. of. iterables
filter function expects two arguments, function_object and an iterable.
function_object returns a boolean value. function_object is called for each element
of the iterable and filter returns only those element for which the function_object
returns true.

Like map function, filter function also returns a list of element. Unlike map
function filter function can only have one iterable as input.

===========================
def square(a):
if a%2==0 :
return a*a

x=filter(square,[1,2,3,4])#function and range of values can be passed directly


print(list(x))

output:
[2,4]

======Put map() and check===============================


def square(a):
if a%2==0 :
return a

x=map(square,[1,2,3,4])#function and range of values can be passed directly


print(list(x))
output:
[None, 4, None, 16]
==========================================
a = [1, 2, 3, 4, 5, 6]
b=filter(lambda x : x % 2 == 0, a) # Output: [2, 4, 6]
print(list(b))

=================================================
a = [1, 2, 3, 4, 5, 6]
b=filter(lambda x : x % 2 != 0, a)
print(list(b))

=================================================
# List of integers
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Function to check if a number is even


def is_even(number):
return number % 2 == 0

# Filter out even numbers from the list


even_numbers = list(filter(is_even, numbers))

# Print the filtered even numbers


print(even_numbers)

=========reduce()===================
from functools import reduce

result = reduce((lambda a, b: a + b), [1, 2, 3, 4])


print(result)

===========zip()===========
a = (11,12,13)
b = ("Jenny", "Christy", "Monica")

x = zip(a,b)
print(list(x))
======================Exact difference between map() and filter() ===============

1)map() function returns values for all the elements in the sequence irrespective
of the
condition.

1)filter() function returns those elements in the sequence that satisfies the
condition.

2)map() can take any no. of. sequences.


2)filter() can take only one sequence.

================Example=================
===========================
def square(a):
if a%2==0 :
return a*a

x=filter(square,[1,2,3,4])#function and range of values can be passed directly


print(list(x))

output:
[2,4]

======Put map() and check===============================


def square(a):
if a%2==0 :
return a

x=map(square,[1,2,3,4])#function and range of values can be passed directly


print(list(x))
output:
[None, 4, None, 16]

================OS Commands================
The functions of os module are generally called as OS commands.
They are used to perform operations at OS level.

>>> import os

>>> os.getcwd()
'C:\\Users\\user\\AppData\\Local\\Programs\\Python\\Python36-32'

>>> os.listdir(".") #To see all the files in the current working
directory(Python36-32)
['DLLs', 'Doc', 'include', 'jeegi1.py', 'jeegi2.py', 'Lib', 'libs', 'LICENSE.txt',
'MyTest', 'NEWS.txt', 'Om.py', 'python.exe', 'python3.dll', 'python36.dll',
'pythonw.exe', 'Scripts', 'tcl', 'Tools', 'vcruntime140.dll']

>>> x=os.listdir("MyTest") #To see the files in a particular folder(MyTest) of cwd


>>> print(x)
['eight.txt', 'Folder1', 'Folder2', 'seven.txt']

>>> print(type(x))
<class 'list'>
>>> len(x)
4
>>> x.count('Folder1')
1
>>> x.count('Folder111')
0
>>> os.getcwd()
'C:\\Users\\user\\AppData\\Local\\Programs\\Python\\Python36-32'
>>> os.chdir("MyTest") #Change directory #Making cwd as "MyTest"

>>> os.getcwd()
'C:\\Users\\user\\AppData\\Local\\Programs\\Python\\Python36-32\\MyTest'

>>> os.listdir() #To see all the files in MyTest(cwd) #OS3.6.txt say, a file is
there
['eight.txt', 'Folder1', 'Folder2', 'OS3.6.txt', 'seven.txt']

>>> os.remove("os3.6.txt")#To remove a file


>>> os.listdir()
['eight.txt', 'Folder1', 'Folder2', 'seven.txt']

>>> os.rename("oldfile","newfile")#To rename a file.

>> os.getcwd()
'C:\\Users\\user\\AppData\\Local\\Programs\\Python\\Python36-32\\MyTest'

>>> os.mkdir("Satya")#To create a new folder


>>> os.listdir(".")
['eight.txt', 'Folder1', 'Folder2', 'Satya', 'seven.txt']

>>> os.path.isdir("Satya")#Gives true if Satya is a folder


True

>>> os.path.isfile('seven.txt')#Gives true if seven is a file


True

>>> os.path.isdir("eight.txt")
False

>>> os.path.exists("Satya")#If Satya file or folder is there,it will give true


True
>>> os.path.exists("seven.txt")#If seven file or folder is there,it will give true
True
>>> os.path.exists("hello.txt")
False

>>> os.listdir(".")
['eight.txt', 'Folder1', 'Folder2', 'Satya', 'seven.txt']

>>> os.path.getsize("Folder1")#To see the size of a folder


>>4016
>>os.getcwd()
C:\\Users\\user\\AppData\\Local\\Programs\\Python\\Python36-32\\MyTest'

>>> os.listdir(".")
['eight.txt', 'Folder1', 'Folder2', 'Satya', 'seven.txt']
>>> os.chdir("Folder1")
>>> os.getcwd()
'C:\\Users\\user\\AppData\\Local\\Programs\\Python\\Python36-32\\MyTest\\Folder1'
>>> os.listdir(".")
['one.txt', 'three.txt', 'two.txt']

>>> os.system("type one.txt")


hello allcjdbgfnfh;yh
fhbnghjmk,mnhgfdsdfghj,kjhtres
rhjklkiuy
trdsx
hello allcjdbgfnfh;yh
fhbnghjmk,mnhgfdsdfghj,kjhtres
rhjklkiuytrdsx
hello allcjdbgfnfh;yh
fhbnghjmk,mnhgfdsdfghj,kjhtres
rhjklkiuytrdsx
hello allcjdbgfnfh;yh
fhbnghjmk,mnhgfdsdfghj,kjhtres
rhjklkiuytrdsx
hello allcjdbgfnfh;yh
fhbnghjmk,mnhgfdsdfghj,kjhtres
rhjklkiuytrdsx
===============Explanation=================

============os.getcwd()=============
It will get the current working directory.

=======os.listdir()=======

listdir() is used to get the files and folders of current working directory

=========os.listdir("folder")======
The above command is used to get the files and folders of that folder which is
specified listdir()

===============os.remove(file/folder)=====

This is used to remove a file or folder from the working directory=============

==========os.rename(oldFileName,NewFileName)===============
This is used to rename the files

==================os.mkdir("FolderName")===============
It is used to create a folder in the current working directory

===================os.chdir("folderName")========================
It is used to switch from one directory to some other directory in the current
folder.

===================os.path.isdir("Parameter")===============
isdir() is a boolean function.It will give true if the supplied argument is a
folder.Else, false
===================os.path.isfile("Parameter")===============
isfile() is a boolean function.It will give true if the supplied argument is a
file.Else, false

=================os.path.exists("parameter")===================
This will give true if the supplied parameter is existed(let it be a file or
folder) in the current working directory

====================os.path.getsize("File/Folder")==============
This will get the size of the supplied file/folder

=====================os.system("type filename")=================
This will read the data from the file that we supply

==================Working on D drive===============
import os
> os.chdir("D:\\core")
>>> os.getcwd()
'D:\\Hello'
>>> os.listdir()
>>> os.chdir("PythonTest")
>>> os.getcwd()
'D:\\Hello\\PythonTest'

==================
Program to check whether the file is exist or not.

import os,sys

fname = input("Enter file name")

if os.path.isfile(fname):
f = open(fname,'r')
str = f.read()
print(str)

else:
print(fname+'does not exist')
exit(1)

================Working with Excel files====================

pip install/uninstall modulename

To create an excel and to read/write data into it.

U have to give the following command

In the normal cmd prompt....


C:\Users\user\AppData\Local\Programs\Python\Python36-32\Scripts>

pip install openpyxl

using python script, if we want to communicate with excel files to manipulate


excel, first we need to download the python excel library.

go to google and type "python module for excel"

python excel
url: www.python-excel.org
and download the **** by clicking on documentation link under Openpyxl library, and
see the sample codes.

To install our module in pycharm tool:

ex: openpyxl

step1: open pycharm and go to File--> Settings --> project --> Interpreter -->
click on + symbol in the rhs --> type the package to be installed ex: openpyxl and
click on "Install package" button, wait for a while till u see "package installed
successfully".

=====================one.py=================
from openpyxl import Workbook
#Creating an object for the WorkBook class
wb = Workbook()

# grab the active worksheet..This work


ws = wb.active

# Data can be assigned directly to cells


ws['A1'] = "Hello Excel" #Data will be written to A1 cell

# Rows can also be appended


ws.append(['Unix','Python','Perl','Aws','Oracle'])

# Python types will automatically be converted


import datetime
ws['A3'] = datetime.datetime.now()

# Save the file


wb.save("sample.xlsx")

___________________two.py__________________________________
# Loading python list data into excel file

from openpyxl import Workbook

wb = Workbook()
ws=wb.active

x=[[1,2,3,4,5],
[10,20,30,40,50],
[100,200,300,400,500],
[1000,2000,3000,4000,5000]
]
ws.append(['col1','col2','col3','col4','col5'])
for i in x: #[1,2,3,4,5]
ws.append(i)

wb.save("numbers.xlsx")
print("Excel file created.")

_______________________________________________________
# Loading text file data into excel file

=====employee.txt========
101,Satya,CA,500000
102,Harika,M.Tech,200000

=========three.py========

from openpyxl import Workbook


wb = Workbook()
ws=wb.active

with open("employee.txt","r") as x:

k=x.readlines()

#[101,Satya,CA,500000],[102,Harika,M.Tech,200000]
ws.append(['Studnet ID','Student Name','Course','Fee'])

for i in k: #101,Satya,CA,500000
i=i.split(",") #After we split,the resulted data we are putting into cells
ws.append(i)

c = ws['A2'].value #To read the value at A2 cell


print(c) #101
ws['A4'] = "Done" #Appending data to excel
ws['A6']= "Got it"
d = ws.cell(row=9, column=9, value="HR") #inserting the data in the required cell

print(d) #<Cell 'Sheet'.I9>

print("Excel file created.")


wb.save("Studentss.xlsx")

Note:
We can see and open this file from our project folder itself after the program get
executed.
___________________________________________________________
# Creating an area chart in an excel file..............

from openpyxl import Workbook


from openpyxl.chart import (
AreaChart,
Reference,
Series,
)
wb = Workbook()
ws = wb.active

rows = [
['Number', 'Batch 1', 'Batch 2'],
[2, 40, 30],
[3, 40, 25],
[4, 50, 30],
[5, 30, 10],
[6, 25, 5],
[7, 50, 10],
]

for row in rows:


ws.append(row)

chart = AreaChart()
chart.title = "Area Chart"
chart.style = 18 #U can get the graph in different styles and formats
#We can put any number upto 48
chart.x_axis.title = 'Test'
chart.y_axis.title = 'Percentage'

data = Reference(ws, min_col=1, min_row=1, max_col=3, max_row=7)


chart.add_data(data, titles_from_data=True)

# max_col=3 means 3 cols will be created...Number,batch1,batch 2


# max_row=7 means 7 rows will be created.....7...no. of. rows u kept in the above
list=max_row
#value.
#titles_from_data=False means series1,series2,series3 cols will be created
#titles_from_data=True means Number,batch1,batch 2 cols will be created

ws.add_chart(chart, "B14")

wb.save("area.xlsx")

===================Command line arguments=============


Arguments that are going to be passed at the time of program execution are called
as command line arguments.

OR

Arguments that were given in the same line where the execution command has given is
called as command line arguments.

If we pass command line arguments,then an argument vector with the name "argv" will
be created.
Our file name will be in the 0th index in that vector and from 1st index onwards
the arguments passed by us will be captured.
Process of setting up the path:

right click
My Computer------------------->properties----->Advanced--->
Environmental variables------>User variables--->new--->

variable name:PATH
variable value:paste

ok----->ok----->ok.

C:\Users\user\AppData\Local\Programs\Python\Python36-32 -------->copy

To check wether the path was properly set or not


C:>python
It will show some information if the path was set properly.
Else,it will show cmd not found.

After setting the path,you can take a notepad and you can write the program.After
that save the file with the extension .py (hello.py say).

>>cd Desktop
>>>python filename.py 4 5 6

==================cml1.py===========
import sys

x=sys.argv[1:]
print(x)
print(type(x))

Execution command:
python cml1.py 34 hello f

output:
[34,hello,f],
[list]
==================cml2.py===========

import sys

x=sys.argv[1:]
if len(x)==3 :

c=int(x[0])+int(x[1])+int(x[2])
print("Sum=",c)
else :
print("Invalid args")

====================
python cml2.py 2 4 9

==============cml3.py=============================
import sys
fn=sys.argv[1]

x=open(fn,"r")
data=x.read()

print(data)

============================
python cml3.py Jony.txt

Advantages:

To pass the inputs quickly.Say,we want to perform oprations on a set of files.Then


we can pass these files as command line arguments.

Also used for quick testing.

================sum.py================
import sys

a=sys.argv[1]
b=sys.argv[2]

c=int(a)+int(b)
print(c)

======================
python sum.py -2 -3

===============Database Connectivity===================
Mysql--->https://dev.mysql.com/downloads/installer/

Database Connectivity:Using this,our python program is going to interact with the


db.

Database:
It is a collection of huge volumes of data.Data in the databases will be stored in
the form of a table.
Table is a collection of rows and columns.

Connecting a python application with the database:

Using connectors,we will connect our python applications with the databases.

For ex,if we want to connect with the mysql db,we will have to use mysql connector.
mysql connetor will have some pre defined methods which are useful to connect our
application with the database.
==================Working with Oracle DB========================
1)Install Oracle
2)Go to "Run Sql cmd line" from "All Programs"---->"Oracle 11g folder"
3)Give the command to connect with the database by using
" connect username/password; "
4)Create the table
5)Insert some data in the table that have been created
6)Open pycharm
7)Install cx-Oracle module
8)Create a .py file for writing your query
9)Run the file

==============================================
To connect with the database:
conn username/password;

1)conn system/password;

or

2)connect
system
password

To create a table:
create table tablename(colname1 datatype(size),colname2 datatype(size));

SQL> create table employees(eno number(10),ename varchar(30),eadd varchar(60));

Table created.

To see the table that has been created:


desc tableName;

SQL> desc employees;

Name Null? Type


----------------------------------------- -------- ----------------------------

ENO NUMBER(10)
ENAME VARCHAR2(30)
EADD VARCHAR2(60)

insert into tablename values(col1Value,col2Value,col3Value);


SQL> insert into employees values(1,'John','UK');

1 row created.

SQL> insert into employees values(2,'Benergy','UK');

1 row created.
SQL> insert into employees values(3,'Navin','US');

1 row created.

To see the data inside the table:

select * from tablename;


* ---->all columns of the table

SQL> select * from employees;

ENO ENAME
---------- ------------------------------
EADD
------------------------------------------------------------
1 John
UK

2 Benergy

UK

3 Navin
US

SQL> select ename from employees;

ENAME
------------------------------
John
Benergy
Navin

SQL> select ename from employees where eadd='UK';

ENAME
------------------------------
John
Benergy

delete from tablename where colname=value;

SQL> delete from employees where eno=1;

1 row deleted.

SQL> select * from employees;

ENO ENAME
---------- ------------------------------
EADD
------------------------------------------------------------
2 Benergy
UK

3 Navin
US
update tablename set colname=new_value where colname=value;

SQL> update employees set eadd='Aus' where eno=2;

1 row updated.

SQL> select * from employees;

ENO ENAME
---------- ------------------------------
EADD
------------------------------------------------------------
2 Benergy
Aus

3 Navin
US

==============================Oracle db==========================
install cx_Oracle

First open normal cmd prompt

c:\Python27\Scripts>pip install cx-Oracle ...Type this.

Type "python module for oracle database" in google.Select "using python with oracle
11g" link.

---------------------------------------------------------------
# Displays Oracle installed version

import cx_Oracle #import moduleName

con = cx_Oracle.connect('system/password')#oracle is in our system itself.


#con = cx_Oracle.connect('scott/[email protected]/orcl')# If we connect to a remote
server #where
oracle
#is installed,we have to give the ip address of the server
as specified above.
print(con.version)
con.close()

___________________________________________________________
# Display scott user emp table data

import cx_Oracle
con = cx_Oracle.connect('system/password')

cur = con.cursor()#Cursor allocates memory for the query and the results of the
#query can also be stored in a cursor.
cur.execute('select empno,ename,esal from emp')
'''
for result in cur: #displays all the records
print(result)
'''

'''
row = cur.fetchone()#Fetchs the first row
print(row)
row = cur.fetchone()#Fetchs the second row
print(row)
row = cur.fetchone()#Fetchs the Third row
print(row)
'''

'''
row = cur.fetchmany(5)#Fetching specified no. of. rows
print(row)
'''
row = cur.fetchall()#Fetches all the rows in a list format
print(row)
cur.close()
con.close()
________________________________________________________________
# loading oracle scott user emp table data into excel file and to text file.

import cx_Oracle
from openpyxl import Workbook
wb=Workbook() #Writing data to an excel file
ws=wb.active

x=open("emp.txt","w")#Opening a text file

con = cx_Oracle.connect('scott/tiger')
cur = con.cursor()
cur.execute('select empno,ename,job,sal,deptno from emp order by deptno')

for result in cur:


print(result) #Writing the data on to console
ws.append(result) #Writing data to excel file

x.write(str(result))#Writing data to text file.Actual data will be written in a


#listformat.
#But text file will take only the string data.So type cast
#(list to String)

cur.close()
con.close()
wb.save("emp.xlsx")
x.close()

==========================MySql database================

install mysql-connector
1)https://download.microsoft.com/download/E/2/1/E21644B5-2DF2-47C2-91BD-
63C560427900/NDP452-KB2901907-x86-x64-AllOS-ENU.exe
2)https://cdn.mysql.com//Downloads/MySQLInstaller/mysql-installer-community-
5.7.21.0.msi
Download from the second link.

username:
root
password:
admin

C:\Users\user\AppData\Local\Programs\Python\Python36-32\Scripts>pip install mysql-


connector

MYSQL Statements :
================
mysql> create database python_connectivity;#Creating our own schema
Query OK, 1 row affected (0.04 sec)

mysql> show databases;


+---------------------+(Sai123baba)
| Database |
+---------------------+
| information_schema |
| mysql |
| performance_schema |
| python |
| python_connectivity |
| sys |
+---------------------+
6 rows in set (0.00 sec)

mysql> use python_connectivity;


Database changed
mysql>
mysql> create table emp_details(empno int,empname char(200),salary int);
Query OK, 0 rows affected (0.29 sec)

mysql> insert into emp_details values(101,'RAVI',50000);


Query OK, 1 row affected (0.05 sec)

mysql> select * from emp_details;


+-------+---------+--------+
| empno | empname | salary |
+-------+---------+--------+
| 101 | RAVI | 50000 |
+-------+---------+--------+
1 row in set (0.00 sec)

mysql> insert into emp_details values(102,'RAJU',60000);


Query OK, 1 row affected (0.06 sec)

mysql> select * from emp_details;


+-------+---------+--------+
| empno | empname | salary |
+-------+---------+--------+
| 101 | RAVI | 50000 |
| 102 | RAJU | 60000 |
+-------+---------+--------+
2 rows in set (0.00 sec)

mysql>

1. WAP to connect to mysql database and check the connectivity.


We have to install mysql-connector module to connect with mysql db.

import mysql.connector #mysql--->packageName connector--->module

conn =
mysql.connector.connect(host='localhost',database='mysql',user='root',password='adm
in')#database='mysql'
#means what db we are using ,that we have to give
here.

if conn.is_connected():
print("connected to mysql database")

conn.close()

2. WAP to connect to mysql database and fetch all the rows.

import mysql.connector

conn =
mysql.connector.connect(host='localhost',database='harika2',user='root',password='p
assword')

if conn.is_connected():
print("connected to mysql database")

cursor = conn.cursor()

cursor.execute("select * from tt")

row = cursor.fetchall()

print("total number of rows = ",cursor.rowcount)


print(row)

for i in row:
empno = int(i[0])
empname = i[1]
sal = i[2]
print("%d%s%d"%(empno,empname,sal))
#print(empno,empname,sal)

cursor.close()
conn.close()

3. To insert row in to database


cursor.execute("insert into emp_details values (104,'RAMANA',80000)")
conn.commit()#To insert permanently

4. WAP to insert several rows into table from the keyboard.

import mysql.connector;

def insert_rows(empno, empname, salary):


conn = mysql.connector.connect(host='localhost', database='mysql', user='root',
password='admin')

if conn.is_connected():
print("connected to mysql database")

cursor = conn.cursor()

str = "insert into emp_details(empno,empname,salary) values ('%d','%s','%d')" %


(empno, empname, salary)
try:

cursor.execute(str)
conn.commit()
print("1 row inserted")
except:
conn.rollback()#To restore the previous state
finally:
cursor.close()
conn.close()

n = int(input("How many rows?"))#5

for i in range(n):
x = input("Enter empno\n") #101
y = raw_input("Enter empname\n") #Pinky
z = input("Enter salary\n") #10000
insert_rows(x, y, z)
========================================================

To which db we want to connect we have to type that


Example:
python module for sql.

Links ............

Reference :
http://www.python-excel.org/
https://openpyxl.readthedocs.io/en/default/
Oracle Module :
Reference :
http://www.oracle.com/technetwork/articles/dsl/python-091105.html
Mysql Module :
Reference :
https://www.tutorialspoint.com/python/python_database_access.htm
Csv
Reference :
https://dzone.com/articles/python-101-reading-and-writing

=======Actual implementation====================
==============SQL==============
1)Download mysql 5.5
https://downloads.mysql.com/archives/community/?version=5.5.41

2)Open the MYSQL DB by following the below procedure---

start--->MySQL 5.5 Command Line Client

3)Once the cmd prompt is opened,enter the password that you have given at the time
of installation.
password given by me at the time of installation is "password5" .(username by
default is "root")

4)Create the schema by using the below command--

mysql>create schema harika1;

Schema with the name harika1 will be created

Note:
Schema/database is like a package in where we can create tables and all.

5)To show the schema/database created above,give the below command--

mysql>show databases;

harika1 --->will be shown

6)To put all the tables or what ever we create subsequently in that harika1
database,give the below command--

mysql>use harika1;

7)Create a table with the name testtab and insert,update and delete some data in
that---
==================================

create table tablename(colName datatype(size),colName datatype(size),colName


datatype(size));

mysql>create table tt(eno int,ename varchar(20),salary int);


Query OK, 0 rows affected (1.43 sec)

desc tableName;
mysql> desc tt;
+--------+----------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------+----------+------+-----+---------+-------+
| eno | int | YES | | NULL | |
| ename | char(20) | YES | | NULL | |
| salary | int | YES | | NULL | |
+--------+----------+------+-----+---------+-------+
3 rows in set (0.06 sec)
insert into tablename values();

mysql> insert into tt values(101,'satya',300000);


Query OK, 1 row affected (0.25 sec)

mysql> insert into tt values(102,'harika',200000);


Query OK, 1 row affected (0.23 sec)

mysql> insert into tt values(103,'valli',500000);


Query OK, 1 row affected (0.08 sec)

select colnames from tablename;


mysql> select * from tt;
+------+--------+--------+
| eno | ename | salary |
+------+--------+--------+
| 101 | satya | 300000 |
| 102 | harika | 200000 |
| 103 | valli | 500000 |
+------+--------+--------+
3 rows in set (0.01 sec)

mysql> update tt set ename='satya Ketavarapu' where eno=101;


Query OK, 1 row affected (0.13 sec)
Rows matched: 1 Changed: 1 Warnings: 0

mysql> select * from tt;


+------+------------------+--------+
| eno | ename | salary |
+------+------------------+--------+
| 101 | satya Ketavarapu | 300000 |
| 102 | harika | 200000 |
| 103 | valli | 500000 |
+------+------------------+--------+
3 rows in set (0.00 sec)

mysql> delete from tt where eno=102;


Query OK, 1 row affected (0.08 sec)

mysql> select * from tt;


+------+------------------+--------+
| eno | ename | salary |
+------+------------------+--------+
| 101 | satya Ketavarapu | 300000 |
| 103 | valli | 500000 |
+------+------------------+--------+
2 rows in set (0.00 sec)

mysql> select eno,ename from tt;


+------+------------------+
| eno | ename |
+------+------------------+
| 101 | satya Ketavarapu |
| 103 | valli |
+------+------------------+
2 rows in set (0.00 sec)
mysql>

==========================================================
8)
==========================
Open pycharm and install "mysql-connector-python" module in pycharm.

9)Write the below code in pycharm and run it.

=================Testing the connection=========


import mysql.connector #mysql--->packageName connector--->module

conn =
mysql.connector.connect(host='localhost',database='harika2',user='root',password='p
assword')#database='harika1'
#means what db we are using ,that we have to give
here.

if conn.is_connected():
print("connected to mysql database")

conn.close()

=======To connect to mysql database and fetch all the rows==========

import mysql.connector

conn = mysql.connector.connect(host='localhost', database='harika2', user='root',


password='password')

if conn.is_connected():
print("connected to mysql database")

cur = conn.cursor()

cur.execute("select * from employees")

row = cur.fetchall()

print("total number of rows = ", cur.rowcount)


print(row)

for i in row:
empno = i[0]
empname = i[1]
sal = i[2]
print(empno,empname,sal)

cur.close()
conn.close()

==========Inserting==============================
import mysql.connector
def insert_rows(empno, empname, salary):
conn = mysql.connector.connect(host='localhost', database='satya', user='root',
password='password')

if conn.is_connected():
print("connected to mysql database")

cursor = conn.cursor()
str = "insert into empinfo(eno,ename,salary) values ('%d','%s','%d')" % (empno,
empname, salary)
try:

cursor.execute(str)
conn.commit()
print("1 row inserted")
except:
conn.rollback()#To restore the previous state
finally:
cursor.close()
conn.close()
n = int(input("How many rows?"))#2
for i in range(n): #0 to 1
x = int(input("Enter empno\n")) #101
y = input("Enter empname\n") #Pinky
z = int(input("Enter salary\n")) #10000
insert_rows(x, y, z)

================================

import mysql.connector

# Connect to the database


conn = mysql.connector.connect(
host="localhost",
user="root",
password="password",
database="example"
)
cursor = conn.cursor()

# Create a table
cursor.execute('''CREATE TABLE IF NOT EXISTS users
(id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
age INT NOT NULL)''')

# Insert data into the table


cursor.execute("INSERT INTO users (name, age) VALUES (%s, %s)", ('John', 25))
conn.commit()

# Fetch data from the table


cursor.execute("SELECT * FROM users")
rows = cursor.fetchall()
for row in rows:
print("ID: {}, Name: {}, Age: {}".format(row[0], row[1], row[2]))

# Close the database connection


conn.close()
==============================Encapsulation and Polymorphism==============
Encapsulation and access modifiers.
Grouping of important variables into a unit is called as encapsulation.
To protect a variable:
__variableName --->Encapsulation

Access modifiers will tell the accessibility of a particular variable/member.

public,protected,private

var1 -->public --->accessible any where in the code.


_var2 -->protected->accessible in the same class(in which it is created) and also
in its child class.
__var3 -->private--->accessible only in the same class in which it is created.
==================Encap1===========To prevent Accidental
modification================
class Bank1:
def __init__(self,name,phno,pwd):
self.name=name #public
self._mob=phno #protected
self.__bank=pwd #private

b=Bank1("SBI",88888,123)
print(b.name)
print(b._mob)
#print(b.__bank)
print(b._Bank1__bank)#Name mangling from python 3

===================Encap2===============
class Bank1:
def __init__(self,name,phno,pwd):
self.name=name #public
self._mob=phno #protected
self.__bank=pwd #private

b=Bank1("SBI",88888,123)
print(b.name)
#print(b.mob)#error Without _ i cannot call the protected member directly
#print(b.bank)#error Without name mangling we cannot call the private members
#print(b._Bank1__bank)#Name mangling from python 3

==========Encap3==================
Accessing protected members without _ and accessing private members without using
name mangling===========
getter methods as shown below---

#we set the values using the constructor directly


class Bank1:
def __init__(self,name,phno,pwd): #b{name=SBI,_mob=88888,__bank=123}
self.name=name #public
self._mob=phno #protected
self.__bank=pwd #private

#Defining setter and getter methods for the variables

def getmob(self):
return self._mob
def getbank(self):
return self.__bank
b=Bank1("SBI",88888,123)
print(b.name)
print(b.getmob())
print(b.getbank())

==================Polymorphism====================
poly-->many
morphism-->forms

Ex:Shape

Same function name with different logics/bodies.

Types:
Method Overloading
Method Overriding

Overloading--
==========Overloading---Not supported directly============
class Student:
def sum(self,a,b,c):
s=a+b+c
print(s)

def sum(self,a,b): #Only this latest is considered.Should call only asper this
s=a+b
print(s)
s=Student()
s.sum(2,3,4)
s.sum(2,3)
=============Small trick to achieve the above=========
class Student:
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 #Not important.Just in case if we pass only one parameter
return s
s=Student()
print(s.sum(2,3,4))
print(s.sum(2,3))
print(s.sum(2))

But python cannot support overloading as we can't have multiple methods with the
same name.

========================Overriding====================
class Mobile:
def BF(self):
print("Important features to be implemented by all the Mobiles")

class SM(Mobile):
def BF(self):
print("Features specific to SM")

class MM(Mobile):
def BF(self):
print("Features specific to MM")

class MI(Mobile):
def BF(self):
print("Features specific to MI")

mob=Mobile()
mob.BF()

smob=SM()
smob.BF()

mmmob=MM()
mmmob.BF()

mi=MI()
mi.BF()

==================================Polymorphism(Not
required)===================================
Polymorphism :
=================
poly -> many
morphos -> forms
If something exist in various forms, it is called polymorphism.

In programming, a variable,object or method will exist in various forms.

A variable can store different types of data, an object may exhibit different
behaviors
in different contexts or a method may performs various tasks in python.
This type of behaviour is called polymorphism.

Python has built in polymorphism. The following topics are examples for
polymorphism
in python.

1. operator overloading
2. Method overloading
3. Method overriding

Operator overloading:
---------------------
We know that operator is symbol that performs some action. For example, '+' is an
operator
that performs addition when used on numbers and also can be used to concatenate two
lists say.
When an operator can perform different actions it is said to exhibit polymorphism.

eg :
print(10+15)

s1 = "Hello"
s2 = "Pinky"

print(s1+s2) #Hello Pinky

lst1 = [10,20,30]
lst2 = [40,50,60]
print(lst1+lst2) # [10,20,30,40,50,60]

operator overloading :
----------------------

#Overloading "+" operator

class book1:
def __init__(self, price):
self.price = price #b1{price=100}

def __add__(self, others): #add is the predefined method.__ will be there for
predefined methods
return self.price + others.price

class book2:
def __init__(self, price):
self.price = price #b2{price=150}

b1 = book1(100)
b2 = book2(150)
print("total price is ", (b1 + b2)) #Objects will not be concatenated.__add__()
will be called
#b1+b2 means b1.__add__(b2)

Note:
If we write b1+b2, we have to write __add__() in book1 class as b1 is the object of
book1 class
If we write b2+b1, we have to write __add__() in book2 class as b2 is the object of
book2 class

===============Ex2===============================
#Overloading ">" operator

class book1:
def __init__(self, price):
self.price = price #b1{price=100}

def __gt__(self, b): #def __gt__(b1,b2)#def __gt__(100,150)


return self.price > b.price #100>150

class book2:
def __init__(self, price):
self.price = price #b2{price=150}

b1 = book1(100)
b2 = book2(150)
if (b1 > b2): #b1.__gt__(b2)
print("b1 price is high")
else:
print("b2 price is high")

Method overloading:
-----------------------
Like other languages (for example method overloading in C++) do, python does not
supports method overloading. We may overload the methods but can only use the
latest defined method.

class A:
def m(self):
print("parameterless")
def m(self,a):
print("a")

def m(self,a,b):
print("a,b")
a=A()
#a.m()
#a.m(2)
a.m(2,3) #You can call only like this as it takes the last/latest definition only

------But there is a code which is similar to overloading ------------------

class addition:
def sum(self,a=None,b=None,c=None): #None is the default argument
if (a!=None and b!=None and c!=None):
print("This is logic 1")
print("sum is ",a+b+c)
elif (a!=None and b!=None):
print("This is logic 2")
print("sum is ",a+b)
else:
print("This is logic 3")
print("please enter two or three arguments")
#Comment every call and explain
m = addition()
m.sum(10,20,30)
m.sum(10,20)
m.sum() #please enter two or three arguments

-------Dont think that the below code is the alternative for the above code--------
class A:
def data(self,*args):
print("args=",args)
a=A()
a.data(1,2,3)
a.data(1,2)
a.data(1,2,3,4)
a.data()

From the above program,we have to notice that only one logic can be performed by
all the calls.
But if i want to perform different logics with different parameters,then the above
way of coding(var args)is not possible.

Method overriding:
------------------
class square:
def __init__(self,side):
self.side = side
def area(self):
print("area of square is :",self.side * self.side)

class rectangle(square):

def __init__(self,l,b):

self.l = l
self.b = b
def area(self):
print("area of rectangle is:",self.l*self.b)

r=rectangle(10,12)
r.area()
================date functions==================================================
Date and time module:
====================

Python provides 3 modules for date and time related.

1. datetime
2. time
3. calender

i) Python program to know current date and time using ctime() function.

>>> import time #time is a module


>>> t = time.ctime()
>>> t
Op:
Thu May 03 16:42:02 2018

ii) Python program to know local date and time.

from datetime import *


now = datetime.now()
print(now) #2018-05-03 16:43:05.313000

print(" Date now : {}/{}/{}".format(now.day,now.month,now.year))


print(" Time now : {}:{}:{}".format(now.hour,now.minute,now.second))

iii) python program to know today's date and time.

>>> print(datetime.today())

2018-03-04 23:06:38.900203
>>> print(date.today())

2018-03-04
>>>

The contents of the 'datetime' and 'time' classes objects can be formatted using
strftime() method. 'strftime' represent 'string format of time'. This method
converts the objects into a specified format and returns the formatted string.

>>> import datetime


>>> td = datetime.date.today()
>>> print(td)
2018-03-04
>>> td.strftime("%d,%B,%Y")
'04,March,2018'
>>> td.strftime("%d,%b,%y")
'04,Mar,18'

Here d,b,y are called it as formatted codes

>>> import calendar


>>> clndr = calendar.month(2018,3)
>>> print(clndr)
March 2018
Mo Tu We Th Fr Sa Su
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31

The date, datetime, and time objects all support a strftime(format) method,
to create a string representing the time under the control of an explicit format
string.

Here is a list of the format codes with their directive and meaning

%a Locale s abbreviated weekday name.


%A Locale s full weekday name.
%b Locale s abbreviated month name.
%B Locale s full month name.
%c Locale s appropriate date and time representation.
%d Day of the month as a decimal number [01,31].
%f Microsecond as a decimal number [0,999999], zero-padded on the left
%H Hour (24-hour clock) as a decimal number [00,23].
%I Hour (12-hour clock) as a decimal number [01,12].
%j Day of the year as a decimal number [001,366].
%m Month as a decimal number [01,12].
%M Minute as a decimal number [00,59].
%p Locale s equivalent of either AM or PM.
%S Second as a decimal number [00,61].
%U Week number of the year (Sunday as the first day of the week)
%w Weekday as a decimal number [0(Sunday),6].
%W Week number of the year (Monday as the first day of the week)
%x Locale s appropriate date representation.
%X Locale s appropriate time representation.
%y Year without century as a decimal number [00,99].
%Y Year with century as a decimal number.
%z UTC offset in the form +HHMM or -HHMM.
%Z Time zone name (empty string if the object is naive).
%% A literal '%' character.

>>>>
import time
import datetime

print("Current date and time: " , datetime.datetime.now())


print("Or like this: " ,datetime.datetime.now().strftime("%y-%m-%d-%H-%M"))

print("Current year: ", datetime.date.today().strftime("%Y"))


print("Month of year: ", datetime.date.today().strftime("%B"))
print("Week number of the year: ", datetime.date.today().strftime("%W"))
print("Weekday of the week: ", datetime.date.today().strftime("%w"))
print("Day of year: ", datetime.date.today().strftime("%j"))
print("Day of the month : ", datetime.date.today().strftime("%d"))
print("Day of week: ", datetime.date.today().strftime("%A"))

That will print out something like this:

Current date and time: 2012-10-03 15:35:46.461491


Or like this: 12-10-03-15-35
Current year: 2012
Month of year: October
Week number of the year: 40
Weekday of the week: 3
Day of year: 277
Day of the month : 03
Day of week: Wednesday

=============================Compilers and Interpreters==========================

Compilation : Conversion of hign level code to machine understandable code is


called as compilation.

Execution : Resolution of binary code step by step is called as execution.

===============Python file execution process================

.py file upon compilation will produce .pyc file.


.pyc file upon interpretation will produce .exe which is a machine level code.
The computer will understand the code in this .exe file,resolves it step by step
and will produce the results.
Python script execution:
c i
.py---->.pyc---->.exe

Comipler:
Will take all the instructions at a time for processing

Interpreter:
Will take line by line for processing.
That why the results produced by the interpreters will be more accurate.
But processing time will be bit high while compared to compilers.

To execute a python program using a normal command prompt:

For that we have to firstly set the path.

Process of setting up the path:

right click
My Computer------------------->properties----->Advanced--->
Environmental variables------>User variables--->new--->

variable name:PATH
variable value:paste

ok----->ok----->ok.

C:\Users\user\AppData\Local\Programs\Python\Python36-32 -------->copy

To check wether the path was properly set or not


C:>python
It will show some information if the path was set properly.
Else,it will show cmd not found.

After setting the path,you can take a notepad and you can write the program.After
that save the file with the extension .py (hello.py say).
Let us say your file is there in the desktop.
Now, open the command prompt and give the compilation and execution commands.

Command for compilation:

>>python -m py_compile hello.py

In the current working directory," __pycache__ " folder will be created


and inside that you can see hello.pyc file.

Command for execution:

>>python hello.py
Note:
Directly you can give the execution command without giving the compilation command.
If you want to have .pyc file to make it portable,in that case only you should give
the compilation command.

C:\Users\QSHORE>cd desktop

C:\Users\QSHORE\Desktop>python test.py
Hello all

==========Importance of .pyc file===================

It is use to achieve platform independency

Platform independency:

Code will be in one computer with one OS and output can be seen in a separate
computer with different OS.

==================ATM application==========
balance=10000
while True :
print("Press 1 to deposit the money")
print("Press 2 to withdraw the money")
print("Press 3 to check the balance")
print("Press 4 to exit")
ans=int(input("Enter choice[1-4] : "))
if(ans==1):
Damount = int(input("Enter the amount to be deposited:"))
balance = balance + Damount
print("Your current balance", balance)
elif(ans==2):
Wamount = int(input("Enter the amount to be withdrawn:"))
balance =balance - Wamount
print("Your current balance", balance)
elif(ans==3):
print("Your current balance", balance)
elif(ans== 4):
print("Thank you.")
break

else :
print("Wrong choice.Try again")

==================Railways==============
print("************Wecome to Indian railways ***********")
username = "Apoorva"
password = "HelloWorld@123"

uname = input("Enter your username:")


pwd = input("Enter your password:")
if (uname==username and pwd==password):

source = input("Enter the source:")


destination = input("Enter the destination:")
date = input("Enter the date of travel:")

print("**********Available trains on",date,"************ ")


print("TrainNo" + "\t" + "TrainName" + "\t" + "ArraivalTime" + "\t" +
"DepartureTime")
print("123456"+"\t"+"AmaravathiExpress"+"\t"+"16: 50"+"\t"+"17: 05")
print("123488" + "\t" + "GodavariExpress" + "\t" + "1: 50" + "\t" + "17: 05")
print("123489" + "\t" + "GareebradthExpress" + "\t" + "5: 50" + "\t" + "19:
05")
print("123487" + "\t" + "PhalaknomaExpress" + "\t" + "8: 50" + "\t" + "21: 05")

trainNo = int(input("Provide the train number in which you want to travel:"))

if(trainNo == 123456 or trainNo == 123488 or trainNo == 123489 or trainNo ==


123487):
seats = int(input("Enter the number of seats you want to book:"))
fare = seats * 500
print("Total fare:",fare)
confirm = input("Do you want to confirm [y/n]")
if (confirm == 'y'):
print("Your tickets have been confirmed")
print("Your train number ",trainNo)
print("No of seats ",seats)
print("Date of journey ",date)
print("Amount to be paid ",fare)
print("Thank you......Visit again")
else:
print("Thank you......Visit again")
else:
print("No train available")

else:
print("Username or password is not valid")

================Decorators=========================
https://www.youtube.com/watch?v=aLBnKIu_WVU

Types of variables:
1)Instance variables(same as java)
2)class variables(static variables in java)

By default the variables are instance in python.Because they will be loaded in each
and every instance or object.

==========1)Instance variables=========
Instance variables will be defined inside the methods/constructors.
class Student:
def __init__(self,name,age):
self.name=name #name and age are the instance variables
self.age=age
def msg(self): #instance method
print(self.name," ",self.age)

print("Object 1:")
s1=Student("Nia",20)
print(s1.name)
print(s1.age)
s1.msg()
print("************")
print("Object 2:")
s2=Student("Ria",21)
print(s2.name)
print(s2.age)
s2.msg()

Note:
In the above code, msg() is called as an instance method as it can access any data
in that instance.

=================2)Class variables===============
Variables defined at class level are called as class variables.
They can be used by all the objects in either of the below ways--

1)object.variableName
2)classname.variableName

==================================
class Student:
clg_name="xyz" #class variable
def __init__(self,name,age):
self.name=name #name and age are the instance variables
self.age=age
print(Student.clg_name)#Accessing the class variable inside the class
def msg(self):
print(self.name," ",self.age)

print("Object 1:")
s1=Student("Nia",20)
print(s1.name)
print(s1.age)
s1.msg()

print(s1.clg_name)#accessing a class_variable using object


print(Student.clg_name)#accessing a class_variable using classname

Note:
Any object can use the class variables.If a variable is needed to be accessed by
multiple objects then we will create that variable as a class level variable.

=============Types of methods==========
1)Instance methods
2)Class methods
3)Static nethods

==================1)Instance methods===================
For instance methods the object/instance is passed as an agrument.
def data(self):
pass

=========================2)Class methods=====================
In a class method we will not pass object(no self).In this method we will pass
class itself.
So the first argument of a class should be "cls"(Any name) .

Syntax to create a class method:

@classmethod
class data(cls,arg1,arg2):
pass

===============Getting the object count using a class method==========


class Student:
counter=0
def __init__(self,name,age):
self.name=name #name and age are the instance variables
self.age=age
Student.counter=Student.counter+1

def msg(self):
print(self.name," ",self.age)

@classmethod
def object_count(cls):#In cls "Student" class will be copied
return cls.counter

s1=Student("Nia",20)
s2=Student("Ria",21)
s3=Student("Ria",21)
print(Student.object_count())#object_count(Student) #Calling a class method with
the class name
print(s3.object_count()) #Calling a class method with the object name

================Class method with parameters=================


class Student:
def __init__(self,name,marks):
self.name=name #name and age are the instance variables
self.marks=marks

def msg(self):
print(self.name+" got "+self.marks+"%")

@classmethod
def get_per(cls,name,marks):#In cls "Student" class will be copied
return cls(name,str((int(560)/600)*100))
#str((int(560)/600)*100)

marks="560"
name="Sia"

s1=Student.get_per(name,marks)#Sia and percentage will be returned to s1 object


s1.msg()
==========================static method=================
@staticmethod is used to create a static method.It will not take any madatory arg
like self,cls,etc.
It is a regular method which can be created inside a class.It will not take object
or class name as
argument.
So, inside a class if we want to create a regular method without any argument then
we can create that method as static method.

class Demo:

@staticmethod
def data():
pass

============Example==============
class Student:
def __init__(self,name,marks):
self.name=name #name and age are the instance variables
self.marks=marks

def msg(self):
print(self.name+" got "+self.marks+"%")

@classmethod
def get_per(cls,name,marks):#In cls "Student" class will be copied
return cls(name,str((int(560)/600)*100))
#str((int(560)/600)*100)
@staticmethod
def get_age(age):
if age<=17:
print("Belongs to school")
else:
print("Dont belong to school")

marks="560"
name="Sia"

s1=Student.get_per(name,marks)#Sia and percentage will be returned to s1 object


s1.msg()
s1.get_age(16)

========ATM===========
Press 1 to deposit the money
Press 2 to withdraw the money
Press 3 to check the balance
Press 4 to exit
Enter choice[1-4] : 1
Enter the amount to be deposited:2000
Your current balance 12000
Press 1 to deposit the money
Press 2 to withdraw the money
Press 3 to check the balance
Press 4 to exit
Enter choice[1-4] : 2
Enter the amount to be withdrawn:6000
Your current balance 6000
Press 1 to deposit the money
Press 2 to withdraw the money
Press 3 to check the balance
Press 4 to exit
Enter choice[1-4] : 3
Your current balance 6000
Press 1 to deposit the money
Press 2 to withdraw the money
Press 3 to check the balance
Press 4 to exit
Enter choice[1-4] : 4
Thank you.

Process finished with exit code 0

==========Railways===========

C:\Users\harik\PycharmProjects\Files\venv\Scripts\python.exe C:\Users\harik\
PycharmProjects\Files\DB1.py
************Wecome to Indian railways ***********
Enter your username:Apoorva
Enter your password:HelloWorld@123
Enter the source:hyd
Enter the destination:vskp
Enter the date of travel:09/09/2023
**********Available trains on 09/09/2023 ************
TrainNo TrainName ArraivalTime DepartureTime
123456 AmaravathiExpress 16: 50 17: 05
123488 GodavariExpress 1: 50 17: 05
123489 GareebradthExpress 5: 50 19: 05
123487 PhalaknomaExpress 8: 50 21: 05
Provide the train number in which you want to travel:123456
Enter the number of seats you want to book:3
Total fare: 1500
Do you want to confirm [y/n]y
Your tickets have been confirmed
Your train number 123456
No of seats 3
Date of journey 09/09/2023
Amount to be paid 1500
Thank you......Visit again

Process finished with exit code 0

You might also like