PythonNotesFinal (3)
PythonNotesFinal (3)
Purpose:
1)To get the results in a faster manner.
2)To get the results in an accurate manner.
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
{
int value;
value=19;
System.out.println(value);//19
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.
5)It is Portable/flexible language that means,it runs on many Unix variants, on the
Mac, and Windows 2000 and later.
===========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.
3)The language isn t a good choice for mobile applications as it is very weak in
mobile computing.
5)Runtime errors:
More errors(Exceptions) will be shown at Runtime.(At the time of execution)
===========================
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
After the installation,you can see python3.7 folder in "All programs" column of
your computer.
(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.
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
To open pycharm:
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
>>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=====================
Example:
a=10
print(a)
o/p:10
==================
a=100
a=20
a=90
print(a) #90
===========================
a=10
b=20
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".
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
Syntax:
var1,var2,var3=val1,val2,val3
a,b,c=5,10,15
print(a)
print(b)
print(c)
op:
5
10
15
name,gender="Harika","F"
print(name,gender)
Output:
Harika F
================id()==================
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
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:
===========================
To check the keywords available in python:
Open python in the command mode
>>>help()
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".
help> keywords
Here is a list of the Python keywords. Enter any keyword to get more help.
============Comments==========================
Comments:
What ever we do write under comments,that will not be considered for execution.
Eg:
#single line comment
print("Hello Python")
output:
Hello Python
eg:
''' This
Is
Multipline comment
'''
eg:
"""
This is also a
perfect example of
multi-line comments
"""
======================================
'''
====>triple quotes
'''
"""
"""
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
Syntax:
type(VariableName)
Important note:
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
Ex:
"pinky"
"1001AbC100@"
a=10 #(int---->Integers(+ve,-ve,0))
print(type(a)) #<type 'int'>
String:
Group of characters is called as a string.
Character means any individula entity like '1' 'a' '@'
name1='Peter'
print(type(name1)) #<type 'str'>
type():
Used to see the type of value stored in a variable.
Ex:
a=10
print(type(a))#int
() ----->function/method/
format() is a function
'''
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))
'''
a=23
b="Rosy"
f="hello"
print(f"The name is {b} {f} and the age is {a}")
==============Boolean functions=========
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())
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()===========
But the string should not contain any special symbols like @, space, etc.
a="Hello world"
print(a.isalnum())
>>> 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().
mNo.isdigit() #false
If the user enters a valid no. then only i will perform the required
logic/operations.
Purpose:
Also, these boolean functions are used to validate the user input.
=============Type casting===================
Type Casting:
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().
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
Purpose:
a=98909890
#print(a.isdigit()) #error.....You cannot apply this method to an integer type
value
b=str(a)
print(b.isdigit())
Output:
Enter the first number: 2
Enter the second number: 4
24
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:
But, in 2.7 to accept integers and decimals, we use input() and to accept the
strings,we will use raw_input().
Ex:
====================Literals=========================
Literal:
a=10
b=2.3
c=True
s="Anushka"
s='Anushka'
s='''Anushka'''
a)Single line String- Strings that are terminated within a single line are known as
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
===============================
text1='Hello \
user'
print(text1)
op:Hello user
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)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:
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
Identity Operators:
Operators Description
is Returns true if identity(addresses) of two operands are 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
So, 4*2^2=4*4=16
a=4
print(a>>2) #1
Formula:
x/2^y
So, 4/2^2=4/4=1
5)XOR(^):
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====================
---
---
---
---
---
---->Sequence control
---->Decision control
---->if(pure if)
---->if-else
---->if-elif /if-else ladder
---->Loop control
---->for
---->while
---->for-else
---->while-else
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.
-----------
-----------
-----------
-----------
-----------
-----------
---
---
if(condition):
statements
---
----
Output:
Hello User
End of program
===================================
if age>=22:
print("eligible for marriage")
print("All the best")
print("Done")
===============================
num = 3
if num > 0:
num = -1
if num > 0:
op:
(3, 'is a positive number.')
This is always printed.
Done
2)if else:
Syntax:
if condition:
statements
else:
statements
===================
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
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:
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")
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.
full_name=first_name+last_name
print(full_name)
===================
age=int(input("Enter your age "))#29
gender=input("Enter your gender")#f
qua=input("Enter your qualification")#MBA
print("thanks")
===================
age=int(input("Enter your age "))
gender=input("Enter your gender")#f
qua=input("Enter your qualification")#mtech
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==================
Syntax:
print(n)
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
range(StartingPoint,EndingPoint,Step)
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()====
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:
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)
for i in range(99,0,-2) :
print(i)
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:
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")
=============================================================
==================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:
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
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
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).
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
%d or %i --> integer
%s --> string,bool
%f ---> float
==================================
name = "ravi"
age = 24
=============================
name = "ravi"
age = 24
package=3.3
fact=False
=================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
=======================
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 condition:
---
---
---
else:
---
----
---
counter = 0
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:
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:
=========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
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
=================
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]
Printing::Leaving
Printing:Printing
::Leaving
a=(10,20,30,40,50,60)
=============================
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
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.
address,age,marks
print(student[?:?])
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
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]
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 [] .
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]
output:
[10,20,30,40]
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) #[]
=============================
append() and insert():
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
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:
==========================================
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)
# 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)
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)
==============To print the list elements using spaces and also in different
lines========
a = [1, 2, 3, 4, 5]
===============================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
output:
{2, 3, 4, 30,10}
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}
7)
minus ---> -
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:
output:
{20, 60}
output:
{50, 30}
a={10,20,40,60}
b={10,30,40,50}
print(a ^ b)
output:
#{50, 20, 60, 30}
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']
===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)
a=(10,20,30)
del a[1]
a=(10,20,30,40,50,60)
print(a[2])
print(a[-1])
print(a[1:5])
a=(10,20,30,40,50,60)
a.append(70) #Not possible as the tuple is immutable
================================
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
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 {} .
Ex:
(username,password)
(States,Capitals)
Ex:
a={101:'Anushka',102:'Akhil'}
print(type(a)) #<class 'dict'>
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 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['Lakshmi'][2])#salary of Lakshmi
print(x['sai'][1])#Role of sai
print(x['Hari'][-1])#department of Hari
====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'}
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)
if(player in player_datails.keys()):
print("player found")
else:
print("player not found")
'''
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:
def functionName():
#Reusable code
Ex:
def display():
-----
-----
-----
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)
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
Parameter:
Parameter is called as an extra information.
============================
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,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:
==========================
sum(10, 20)
sum(100, 200)
sum(15, 29)
output:
30
300
44
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)
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
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 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)
op:
Enter a string :harika
Length of harika is : 6
Total no of vowels in harika is : 3
f1(100)
f1(100,200)
f1(100,200,300)
==============================================
Student_details(101,"Anushka","Computers")
Student_details(102,"Akhil","Computers")
Student_details(103,"Harika","Computers")
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
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")
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
def sum(a,b):
c=a+b
print(c) #5
sum(2,3)
d=c+2
print(d)
=========================
def sum(a,b):
c=a+b
return c
d=sum(2,3)
e=d+3
print(e)
print("Done")
=============================
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
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)
return variable
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:
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.....
import ModuleName
ModuleName.VariableName
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)
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")
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.
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:
===============properties of a module============
import CalculatorModule
output:
Defaule name of the module __main__
================
Doc String:
This is used to see the information regarding a function in some other file.
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)
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:
or
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.
If we don't have init file in our folder,then that folder is no more treated
as a package.
import modulename1
import modulename2
Ex: import m1
import m2
How to access the methods of a package:
Example:
import abc
abc.m1.f1()
Here,
abc--->PackageName(foldername with init file)
m1---->ModuleName
f1---->FunctionName
'''
===========================
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()
import packageName
packageName.moduleName.methodName()
===========================
====================Examples======================
=================Ex1============================
===============FirstPack(python package)=====================
==============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)
=======================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()
=================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)
==================
===================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()
==================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
Ex:
from MainPack.SubPackk import DivModuleSubPack
=======================================
Packages in python 3.7(In few versions)
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==========================
In this way of programming, the task to be done is divided into sub tasks.
Each sub task is called as a procudure(function).
=======================================
class:
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
===========================================
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
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:
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--->1001
Note:
self:
=========================================
def data(self,a,b):
pass
object.data(2,3) ===>data(object,2,3)
self--->ob
a------>2
b------>3
=============================================================
class employee:
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.
===========================
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")
==========================================
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
y = 200
print("y=", y)
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
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:
===========================================
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 Area :
pi=3.14 #class level variables.Can be accessed directly
#using class name
area=0
def area_circle(self,r) :
=============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
def __methodName(self):
#logic
d1=Demo() #d1{a=10}
d1.a=90
print(d1.a) #d1{a=90} #value is getting modified
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.
__variablename
__methodName()
Purpose:
======================================
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
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)
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:
class A:
a=10
def m1(self):
print("Hello from A")
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:
A B
class A:
a=10
def m1(self):
print("Hello from A")
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:
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:
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()
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
===========Student.py============
==============================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.
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.
f = open("myfile.txt","w")
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()
write :
==============one.py====================
f = open('myfile.txt','w')
f.write(str)
f.close()
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")
f.close()
===========five.py===================
f = open('myfile.txt','w')
str = None
while(str != '@'):
str = input()
if(str != '@'):
f.write(str+"\n")
f.close()
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
file_path ="details.txt"
f = open(file_path,'r')
print(f.read()) #Reads as it is
====================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
nine.py:
---------------
'''
a={101:"satya",102:"Pinky"}
print(a.get(103))#None
a[104]="John" #dic[newKey]=newValue
print(a)
'''
=======================
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
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
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])
=================================
aggr = {}
with open('file.txt', 'r') as f:
line1 = f.readline()
lines = f.readlines()
print('Employee details are\n',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')
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
=====================
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()
f = open('file_new.txt','w')
f.close()
f2.close()
f1.close()
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']
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 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
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")
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
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
=====================================
======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
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()
class c1:
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)
=========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()
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.
class c1:
x = 100
width=20
height=20 #variables of class(Called using c1.variablename)
depth=20
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
def display(self):
print "Directly c1.x =", c1.x #100 #self.variablename and
#classname.variable name both is same
o1 = c1()
o1.area()
o1.display()
#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.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.
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()
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.
fileobject.seek(no.of bytes,offset)
Ex:
x.seek(5,1)
===================two.py=========
class student:
cnt = 0
def display(self):
print("Name :", self.name)
print("Course : ", self.course)
print("Phno :", self.phno)
print("********************")
Total no of students : 1
File will be created in the below location
C:\Users\user\PycharmProjects\CoreAppsPython\constructors
'''
=================Three.py===========
class ComplexNumber:
==========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.
Syntax:
The name of the destructor is :
def __del__(self) :
pass
del objectName
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:
==============================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:
=============================================
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)
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 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():
#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()
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.
Abstract class:
If a class is having atleast one abstract method,then it is called as an abstract
class.
@abstractmethod
def methodName():
pass
class ClassName(ABC):
#body
===============================
class Student:
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".
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===========================
Fuel tank --> openTank and fill fuel. which is common for all
so openTank() concrete method.
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:
============
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:
x=classname()
x.connect()
x.disconnect()
output:
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.
-----
----- .................................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.
def f1():
---
--- chat logic
---
---
def f2():
---
--- greetings download logic
---
---
def f3():
---
--- online shopping logic
---
---
f1()
f2()
f3()
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.
Actually in f2(),we have written code to back up the data.It shows that 3hours is
required to back up the data.
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.
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
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()
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
=====================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()
---------
--------- -------->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.
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
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
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
for i in range(1,10):
t=Thread(target=f1,args=(i,))
t.start()
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
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
* 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.
import threading
===================================================================================
=
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")
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
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
==========threading.py================
class Thread:
def run(self):
----
---- #some default logic
----
=============Process.py============
class A(Thread):
def run(self):
----
---- #my own logic #overriding
----
class MyThread(Thread):
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.
import time
from threading import Thread
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 ----
Below are the list of methods and properties available in Thread class
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
t1 = MyThread1()
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:
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.
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
========================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.
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.
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
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
===========================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():
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
================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
class ValueTooLargeError(Error):
"""Raised when the input value is too large"""
pass
class JohnError(Error):
"""Raised when the inputed value is 100"""
pass
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")
===================================
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")
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
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.
Ex:
a=[10,20,30,40,50]
b=[100,200,300,400,500]
'''
===============================
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
output:
[2,4]
=================================================
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]
=========reduce()===================
from functools import reduce
===========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.
================Example=================
===========================
def square(a):
if a%2==0 :
return a*a
output:
[2,4]
================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']
>>> 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.getcwd()
'C:\\Users\\user\\AppData\\Local\\Programs\\Python\\Python36-32\\MyTest'
>>> os.path.isdir("eight.txt")
False
>>> os.listdir(".")
['eight.txt', 'Folder1', 'Folder2', 'Satya', 'seven.txt']
>>> 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.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)=====
==========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
if os.path.isfile(fname):
f = open(fname,'r')
str = f.read()
print(str)
else:
print(fname+'does not exist')
exit(1)
python excel
url: www.python-excel.org
and download the **** by clicking on documentation link under Openpyxl library, and
see the sample codes.
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()
___________________two.py__________________________________
# Loading python list data into excel file
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========
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)
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..............
rows = [
['Number', 'Batch 1', 'Batch 2'],
[2, 40, 30],
[3, 40, 25],
[4, 50, 30],
[5, 30, 10],
[6, 25, 5],
[7, 50, 10],
]
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'
ws.add_chart(chart, "B14")
wb.save("area.xlsx")
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
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:
================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:
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.
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));
Table created.
ENO NUMBER(10)
ENAME VARCHAR2(30)
EADD VARCHAR2(60)
1 row created.
1 row created.
SQL> insert into employees values(3,'Navin','US');
1 row created.
ENO ENAME
---------- ------------------------------
EADD
------------------------------------------------------------
1 John
UK
2 Benergy
UK
3 Navin
US
ENAME
------------------------------
John
Benergy
Navin
ENAME
------------------------------
John
Benergy
1 row deleted.
ENO ENAME
---------- ------------------------------
EADD
------------------------------------------------------------
2 Benergy
UK
3 Navin
US
update tablename set colname=new_value where colname=value;
1 row updated.
ENO ENAME
---------- ------------------------------
EADD
------------------------------------------------------------
2 Benergy
Aus
3 Navin
US
==============================Oracle db==========================
install cx_Oracle
Type "python module for oracle database" in google.Select "using python with oracle
11g" link.
---------------------------------------------------------------
# Displays Oracle installed version
___________________________________________________________
# 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
con = cx_Oracle.connect('scott/tiger')
cur = con.cursor()
cur.execute('select empno,ename,job,sal,deptno from emp order by deptno')
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
MYSQL Statements :
================
mysql> create database python_connectivity;#Creating our own schema
Query OK, 1 row affected (0.04 sec)
mysql>
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()
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()
row = cursor.fetchall()
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()
import mysql.connector;
if conn.is_connected():
print("connected to mysql database")
cursor = conn.cursor()
cursor.execute(str)
conn.commit()
print("1 row inserted")
except:
conn.rollback()#To restore the previous state
finally:
cursor.close()
conn.close()
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)
========================================================
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
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")
Note:
Schema/database is like a package in where we can create tables and all.
mysql>show databases;
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---
==================================
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();
==========================================================
8)
==========================
Open pycharm and install "mysql-connector-python" module in pycharm.
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()
import mysql.connector
if conn.is_connected():
print("connected to mysql database")
cur = conn.cursor()
row = cur.fetchall()
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
# 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)''')
public,protected,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---
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
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
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.
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"
lst1 = [10,20,30]
lst2 = [40,50,60]
print(lst1+lst2) # [10,20,30,40,50,60]
operator overloading :
----------------------
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}
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
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:
====================
1. datetime
2. time
3. calender
i) Python program to know current date and time using ctime() function.
>>> 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.
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
>>>>
import time
import datetime
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.
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
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.
>>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
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"
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()
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) .
@classmethod
class data(cls,arg1,arg2):
pass
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
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"
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"
========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.
==========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