Python Full Notes
Python Full Notes
History of Python
Python is a general-purpose high-level, interpreted, interactive and object-
oriented programming language.
Python was developed by Guido van Rossum during 1985- 1990, at the National
Research Institute for Mathematics and Computer Science in the Netherlands.
Python is derived from many other languages, including ABC, Modula-3, C, C++,
Algol-68, SmallTalk, Unix shell, and other scripting languages. Python is
copyrighted. Like Perl, Python source code is now available under the GNU
General Public License (GPL).
Python is Interactive: You can actually sit at a Python prompt and interact
with the interpreter directly to write your programs.
Python Features
Python's features include:
Easy-to-learn: Python has few keywords, simple structure, and a clearly defined
syntax. This allows the student to pick up the language quickly.
Easy-to-read: Python code is more clearly defined and visible to the eyes.
A broad standard library: Python's bulk of the library is very portable and
cross-platform compatible on UNIX, Windows, and Macintosh.
Interactive Mode: Python has support for an interactive mode which allows
interactive testing and debugging of snippets of code.
Portable: Python can run on a wide variety of hardware platforms and has the
same interface on all platforms.
Extendable: You can add low-level modules to the Python interpreter. These
modules enable programmers to add to or customize their tools to be more
efficient.
GUI Programming: Python supports GUI applications that can be created and
ported to many system calls, libraries, and windows systems, such as Windows
MFC, Macintosh, and the X Window system of Unix.
Scalable: Python provides a better structure and support for large programs
than shell scripting.
Apart from the above-mentioned features, Python has a big list of good features,
few are listed below:
It supports functional and structured programming methods as well as OOP.
It can be used as a scripting language or can be compiled to byte-code for
building large applications.
It provides very high-level dynamic data types and supports dynamic type
checking.
It supports automatic garbage collection.
It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.
Python Environment
Python is available on a wide variety of platforms including Linux and Mac OS X.
Let's understand how to set up our Python environment.
Installing Python
Python distribution is available for a wide variety of platforms. You need to
download only the binary code applicable for your platform and install Python.
Windows Installation
Follow the link for the Windows installer python-XYZ.msi file where XYZ is the
version you need to install.
To use this installer python-XYZ.msi, the Windows system must support
Microsoft Installer 2.0. Save the installer file to your local machine and then run it
to find out if your machine supports MSI.
Run the downloaded file. This brings up the Python install wizard, which is
really easy to use. Just accept the default settings, wait until the install is
finished, and you are done.
Running Python
There are three different ways to start Python:
1. Interactive Interpreter
2. Script from the Command-line
3. Integrated Development Environment
You can run Python from a Graphical User Interface (GUI) environment as well, if
you have a GUI application on your system that supports Python.
Windows: PythonWin is the first Windows interface for Python and is an IDE
with a GUI.
Data Objects
A Python identifier is a name used to identify a variable, function, class, module,
or other object. An identifier starts with a letter A to Z or a to z, or an underscore
(_) followed by zero or more letters, underscores and digits (0 to 9).
Python does not allow punctuation characters such as @, $, and % within
identifiers. Python is a case sensitive programming language. Thus, Manpower
and manpower are two different identifiers in Python.
Python Keywords
The following list shows the Python keywords. These are reserved words and you
cannot use them as constant or variable or any other identifier names. All the
Python
The data stored in memory can be of many types. For example, a person's age is
stored as a numeric value and his or her address is stored as alphanumeric
characters. Python has various standard data types that are used to define the
operations possible on them and the storage method for each of them. Python
has five standard data types:
1. Numbers
2. String
3. List
4. Tuple
5. Dictionary
Python Numbers
Number data types store numeric values. Number objects are created when you
assign a value to them. For example:
var1 = 1
var2 = 10
You can also delete the reference to a number object by using the del
statement. The syntax of the del statement is:
del var1[,var2[,var3[....,varN]]]]
C1 2 + 3i
C2 5 + 4i
C3=C1+c2 7 + 7i
C4=c1-c2 -3 – 1 i
C5= c1*c2
2+3i
5+4i
----------------
10+15i
8i + 12 i2
----------------
23i-2
Python Strings
Strings in Python are identified as a contiguous set of characters
represented in the quotation marks. Python allows for either pairs of
single or double quotes. Subsets of strings can be taken using the slice
operator ([ ] and [:] ) with indexes starting at 0 in the beginning of the
string and working their way from -1 at the end.
The plus (+) sign is the string concatenation operator and the asterisk (*) is the
repetition operator.
Python Lists
Lists are the most versatile of Python's compound data types. A list
contains items separated by commas and enclosed within square
brackets ([]). To some extent, lists are similar to arrays in C. One
difference between them is that all the items belonging to a list can be of
different data type.
The values stored in a list can be accessed using the slice operator ([ ] and [:])
with indexes starting at 0 in the beginning of the list and working their way to
end -1. The plus (+) sign is the list concatenation operator, and the asterisk (*) is
the repetition operator.
The main differences between lists and tuples are: Lists are enclosed in brackets
( [ ] ) and their elements and size can be changed, while tuples are enclosed in
parentheses ( ( ) ) and cannot be updated. Tuples can be thought of as read-
only lists.
my_tuple = ()
print(my_tuple)
dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"
# nested tuple
# Output: ("mouse", [8, 4, 6], (1, 2, 3))
my_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
print(my_tuple)
# parentheses is optional
# Output: <class 'tuple'>
my_tuple = "hello",
print(type(my_tuple))
# nested tuple
n_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
print(n_tuple[0][3])
# nested index
print(n_tuple[1][1])
Function Description
Basic Operators
Operators are the constructs which can manipulate the value of operands.
Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands and
+ is calledoperator.
Types of Operators
Python language supports the following types of operators.
1. Arithmetic Operators
2. Comparison (Relational) Operators
3. Assignment Operators
4. Logical Operators
5. Membership Operators
6. Identity Operators
Arithmetic operators
+ - Addition
- - Subtraction
* - Multiplication
/ - Division
% - Modulus
** - Exponent
// - Floor Division 9//2 = 4 and 9.0//2.0 = 4.0, -11//3 = -4, -11.0//3 = -4.0
Comparison/Relational Operators
== equal
!= not equal
> greater than
< less than
>= greater than or equal
<= less than or equal
Logical operators
Assignment operators
= += -= *= /= %= //= **=
Special Operators
1.Identity
2.Membership
x1 = 5 y1 = 5
x2 = 'Hello' y2 = 'Hello'
x3 = [1,2,3] y3 = [1,2,3]
Output:
False
True
False
Membership operators
in and not in are the membership operators in Python. They are used to
test whether a value or variable is found in a sequence (string, list, tuple,
set and dictionary). In a dictionary we can only test for presence of key,
not the value.
Operator Meaning
in True if value/variable is
found in the sequence
Multi-line statement
In Python, end of a statement is marked by a newline character. But we
can make a statement extend over multiple lines with the line
continuation character (\).
Example: Adding values
a=1+2+3+\
4+5+6+\
7+8+9
print(a)
a = (1 + 2 + 3 +
4+5+6+
7 + 8 + 9)
print(a)
colors = ['red',
'blue',
'green']
"""This is also a
perfect example of
multi-line comments"""
Print function(output)
The print function can print an arbitrary number of values ("value1,
value2, ..."), which are separated by commas. These values are separated
by blanks.
print("Hello")
Hello
print blank line(s)
print(5 * "\n")
print("\n\n\n\n\n")
print(5 * "\n")
x, y = 1, 2
print(x),; print(y)
12
print x,y,
Special characters
character Description
\ backslash
\’ Single quote
\” Double quote
\a Bell
\b Backspace
\n newline
\r carriage return
\t tabulation
\v vertical tabulation
Input
Python has two functions for accepting data directly from the user:
-> input()
input()
if condition :
block
If.py
a=int(input())
b=int(input())
max=a
if max < b :
max=b
if-else statement
It is an extension of simple if statement.
The general form of an if-else statement is
if condition :
if block
else:
else block
If-else.py
print ("Enter any two values")
a=int(input())
b=int(input())
if a> b :
max=a
else :
max=b
print("Maximum value :",max)
if-else1.py
print ('Enter any Number ')
n=int(input())
if n%2==0 :
print("Given Number is Even")
else :
print("Given Number is Odd")
Nested if statement :
Using a if statement within another if is called as nested if. If a series of
decisions are involved, we use nested if statement.
Form : 1
if condition-1 :
if condition-2 :
………….
………..
If condition-n :
Statements
Form : 2
if condition-1 :
if condition-2 :
Statement-1
else :
Statement-2
else :
If condition-3 :
Statement-3
else :
Statement-4
To find maximum of three values
Nest-if.py
print("Enter any 3 values ")
a=int(input())
b=int(input())
c=int(input())
if a>b :
if a>c :
max=a
else :
max=c
else :
if b>c :
max=b
else :
max=c
print("Maximum value :",max)
if-elif-else statement
This statement is also used for a series of decisions are involved.
Syntax:
if condition-1 :
statements-1
elif condition-2 :
statements-2
………………….
………………….
elif condition-n:
statements-n
else :
else block - statements
If-elif.py
write a python script to enter student number, name, marks in c, c++ and
java calculate and display total marks, average, result and grade.
Stu.py
print("Enter Student Number :",end='');
sno=int(input())
print("Enter Student Name :",end='');
sname=input()
print("Enter Marks in C,C++ and Java ");
c=int(input())
cpp=int(input())
java=int(input())
tot=c+cpp+java
avg=float(tot/3)
if c>=50 and cpp>=50 and java>=50 :
result='Pass'
if avg >=90 :
grade='a+'
elif avg>=70 :
grade='A'
else :
grade='B'
else :
result='Fail'
grade='-'
print(" RESULT ")
print("-------------------------------------")
print("Sudent Number :",sno)
print("Sudent Name :",sname)
print("Marks in C :",c)
print("Marks in C++ :",cpp)
print("Marks in Java :",java)
print("Total Marks in :",tot)
print("Average :%.2f" %(avg))
print("Result :",result)
print("Grade :",grade)
print("-------------------------------------")
# To check whether the given character is alphabet or digit or special
character
While loop
It is a conditional controlled loop statement in python.
Syntax:
while condition :
statements
In this loop first the condition will be evaluated. If it is true, then the
statement block will be executed. After the execution of statements, the
condition will be evaluated once again, if it is true then the statement
block will be executed once again. This process of repeated execution
continues until the condition becomes false.
range(x):
Returns a list whose items are consecutive integers from 0 to x-1 .
range(x, y):
Returns a list whose items are consecutive integers from x to y-1 .
range(x, y, step):
Returns a list of integers from x to y-1 , and the difference between each
successive value is the value defined by step.
Syntax:
continue
The following program prints numbers from 1 to 10 except for the value 7
continue.py
k=1
while k <=10 :
if k==7:
k+=1
continue
print (k,end=’\t’)
k=k+1
Output:
1 2 3 4 5 6 8 9 10
passex1.py
k=1
while k <=10 :
if k==7:
pass
else:
print (k,”\t”,end=’’)
k+=1
Output:
1 2 3 4 5 6 8 9 10
Nested loops
patteren1
n = int(input("Enter the value of n : "))
for i in range(1,n) :
j=1
while j<=i :
print('*',end=" ")
j=j+1
print()
patteren2
n = int(input("Enter the value of n : "))
s=n*2
for i in range(1,n) :
for k in range(1,s):
print(end=" ")
j=1
while j<=i :
print('*',end=" ")
j=j+1
print()
s=s-2
patteren3
n = int(input("Enter the value of n : "))
s=n*2
x=1
for i in range(1,2*n) :
for k in range(1,s):
print(end=" ")
j=1
while j<=x :
print('*',end=" ")
j=j+1
print()
if i<n :
s=s-2
x=x+1
else :
s=s+2
x=x-1
Data Structures
1)Sequences
A sequence is a collection objects . You can identify an object in a
sequence by its index.
Examples of sequences: lists, tuples, and strings.
2) Sets
3) Dictionaries
Note: Sets and Dictionaries are containers for sequential data.
Lists
A list is a data structure in Python that is mutable (changeable)
sequence of elements. Each element or value that is inside of a list is
called an item. A list is created by placing all the items (elements) inside a
square brackets, separated by comma. It can have any number of items
and they may be of different types (integer, float, string etc.).
Syntax:
List_Name = [item-1,item-2,………,item-n]
# empty list
my_list = []
# list of integers
my_list = [1, 2, 3]
# list with mixed data types
my_list = [1, "Hello", 3.4]
List Index
We can use the index value to access an item in a list. List Index value
starts from 0. So, a list having 5 elements , will have index from 0 to 4.
Eg:
Slicing
We can access a range of items in a list by using the slicing operator :
(colon).
Syntax:
List_name[x:y]
It displays list Items from x to y-1;
>>> my_list=[10,20,30,40,50,60,70,80,90,100]
# elements 3rd to 5th
>>> print(my_list[2:5])
[30, 40, 50]
# elements beginning to 4th( index 0 to 4)
>>> print(my_list[ : 5])
[10, 20, 30, 40, 50]
#Write a python script to accept a List from key board and display list
elements
List1.py
n=int(input("Enter No of Elements :"))
a=[]
print("Enter Elements")
for i in range(n):
a.append(int(input()))
print("Given Elements :",a)
2)Insert
Insert an Element at given position(index).
Syntax:
insert(i, x)
i – index
x- element
Eg:
>>> a = [1,2,4,5,6]
>>> a
[1, 2, 4, 5, 6]
>>> a.insert(2,3)
>>> a
[1, 2, 3, 4, 5, 6]
Note: If the specified index is not available ,the element will be inserted at
last index.
remove
Removes an Element from the list
Syntax:
remove(x)
x – element
Note:
1.It removes first occurrence of the specified element
2.if there is no such item, it displays an error
Eg:
>>> a = [1,2,3,4,5]
>>> a
[1, 2, 3, 4, 5]
>>> a.remove(2)
>>> a
[1, 3, 4, 5]
>>> a.remove(8)
ValueError: list.remove(x): x not in list
pop
Removes and returns an element at the given index in the list, and return
it. If no index is specified, It removes and returns the last item in the list.
Syntax :
Pop([i])
i – index
Eg:
>>> a = [1,2,3,4,5,6]
>>> a
[1, 2, 3, 4, 5, 6]
>>> a.pop(3)
4
>>> a
[1, 2, 3, 5, 6]
>>> a.pop()
6
>>> a
[1, 2, 3, 5]
>>> a.pop(10)
IndexError: pop index out of range
clear
Removes all elements from the list.
Syntax:
clear()
Eg:
>>> a=[1,2,3,4,5]
>>> a
[1, 2, 3, 4, 5]
>>> a.clear()
>>> a
[]
index
Returns the index of the First matched Element
Syntax:
index(x)
x – element
Eg:
>>> a=[1,2,5,2,8]
>>> a
[1, 2, 5, 2, 8]
>>> a.index(2)
1
>>> a.index(10)
ValueError: 10 is not in list
count
Return the number of times Element appears in the list.
Syntax:
count(x)
x – element
>>> a=[1,2,4,2,6,2]
>>> a
[1, 2, 4, 2, 6, 2]
>>> a.count(2)
3
>>> a.count(8)
0
extend
Extend the list by appending all the Elements from another list
Syntax:
extend(another list)
Eg:
>>> a=[1,2,3]
>>> a
[1, 2, 3]
>>> b=[4,5,6]
>>> b
[4, 5, 6]
>>> a.extend(b)
>>> a
[1, 2, 3, 4, 5, 6]
sort
Sort Elements in a list in ascending or descending order.
Syntax:
sort([reverse=False])
sort() – ascending
sort(reverse=True) - descending
Eg:
>>> a=[5,2,6,1,4,3]
>>> a
[5, 2, 6, 1, 4, 3]
>>> a.sort()
>>> a
[1, 2, 3, 4, 5, 6]
>>> a.sort(reverse=True)
>>> a
[6, 5, 4, 3, 2, 1]
reverse
Reverse the order of Elements in the list
Syntax:
reverse()
>>> a=[1,2,3,4,5]
>>> a
[1, 2, 3, 4, 5]
>>> a.reverse()
>>> a
[5, 4, 3, 2, 1]
Buit-in functions
1)len(list)
Gives the total length of the list.
2)max(list)
Returns the maximum element in the list.
3)min(list)
Returns the minimum element in the list.
4)sorted(list)
Returns the sorted list
Eg:
>>> a=[3,5,1,9,6,4]
>>> a
[3, 5, 1, 9, 6, 4]
>>> len(a)
6
>>> max(a)
9
>>> min(a)
1
>>> sorted(a)
[1, 3, 4, 5, 6, 9]
Tuples
A tuple is a sequence of immutable Python objects. Tuples are just like
lists. The differences between tuples and lists are, the tuples cannot be
changed unlike lists and tuples use parentheses, whereas lists use square
brackets.
Strings
A string is a sequence of characters used to store text information. A
string can be enclosed in single quotes (') (or) double quotes (")
Eg:
st='Hello World!'
st="Hello World!"
String functions
str:
Returns a string representation of the specified object.
Syntax:
str(x)
x – object of any datatype
eg:
>>> str(123)
'123'
>>> str(10.345)
'10.345'
max():
Returns the maximum alphabetical character in the string.
eg:
>>> max("ABCDEFGH")
'H'
min():
Returns the minimum alphabetical character in the string.
eg:
>>> min("ABCDEFGH")
'A'
len():
Counts and returns the number of characters in the string.
eg:
>>> len("ABCD")
4
sorted():
Returns the List representation string’s characters in sorted order.
>>> st="CFADEB";
>>> sorted(st)
['A', 'B', 'C', 'D', 'E', 'F']
String Methods
lower():
Returns the string converted to lowercase.
eg:
>>> st="WelCome"
>>> st.lower()
'welcome'
upper():
Returns the string converted to uppercase.
eg:
>>> st="WelCome"
>>> st.upper()
'WELCOME'
swapcase():
Returns the string with uppercase characters converted to lowercase and
lowercase characters converted to uppercase .
Eg:
>>> st="WELcome"
>>> st
'WELcome'
>>> st.swapcase()
'welCOME'
title():
Returns the string with first character of each word converted to
uppercase characters and the rest all characters in lowercase.
eg:
>>> st="welcome to python programming"
>>> st
'welcome to python programming'
>>> st.title()
'Welcome To Python Programming'
isalpha():
Returns true if all characters in the string are alphabetic, otherwise
returns false.
eg:
>>> st="abcd"
>>> st.isalpha()
True
>>> st="123abcd"
>>> st.isalpha()
False
isdigit():
Returns true if all characters in the string are digits, otherwise returns
false.
eg:
>>> st="123"
>>> st.isdigit()
True
>>> st="123abcd"
>>> st.isdigit()
False
islower():
Returns true if all characters in the string are lowercase, otherwise
returns false.
eg:
>>> st="abcd"
>>> st.islower()
True
>>> st="abcd123"
>>> st.islower()
True
>>> st="ABCD"
>>> st.islower()
False
>>> st="1234"
>>> st.islower()
False
>>> st="abcdABCD"
>>> st.islower()
False
isupper():
Returns true if all characters in the string are in uppercase, otherwise
returns false.
eg:
>>> st="ABCD"
>>> st.isupper()
True
>>> st="abcd"
>>> st.isupper()
False
>>> st="ABCD123"
>>> st.isupper()
True
>>> st="abcdABCD"
>>> st.isupper()
False
>>> st="1234"
>>> st.isupper()
False
Sets
A set is a collection of values(elements)with no duplicate elements. Sets
support mathematical operations like union, intersection, difference, and
symmetric difference.
Curly braces or the set() function can be used to create sets.
Syntax :
1)Set_name={item-1,item-2,..,item-n}
2)set_name = set([iterable])
Note: The Elements stored in a set are in ascending order.
Eg:
>>> a={1,2,3,4,5}
>>> a
{1, 2, 3, 4, 5}
>>> b={1,2,3,1}
>>> b
{1, 2, 3}
>>> s=set([3,1,5,4])
>>> s
{1, 3, 4, 5}
Sets can be used to carry out mathematical set operations like union,
intersection, difference and symmetric difference. We can do this with
operators or methods.
Set Union
Union of A and B is a set of all elements from both sets.
Set1.py
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
print(A | B)
Output: {1, 2, 3, 4, 5, 6, 7, 8}
union syntax:
union(Another set)
Eg:
>>> a={1,3,5,7,9}
>>> b={1,2,3,4,5}
>>> a.union(b)
{1, 2, 3, 4, 5, 7, 9}
>>> b.union(a)
{1, 2, 3, 4, 5, 7, 9}
Set Intersection
Intersection of A and B is a set of elements that are common in both
sets.
Intersection is performed using & operator. Same can be accomplished
using the method intersection() .
Ins.py
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
print(A & B)
Output: {4, 5}
Eg:
>>> A.intersection(B)
{4, 5}
Set Difference
Difference is performed using '-' operator. Same can be accomplished
using the method difference() .
Difference of A and B ( A - B ) is a set of elements that are only in A but
not in B . Similarly, B - A is a set of element in B but not in A .
Diff.py
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
print(A - B)
Output: {1, 2, 3}
Eg:
>>> A = {1, 2, 3, 4, 5}
>>> B = {4, 5, 6, 7, 8}
>>> A.difference(B)
{1, 2, 3}
Eg:
>>> A.symmetric_difference(B)
{1, 2, 3, 6, 7, 8}
>>> B.symmetric_difference(A)
{1, 2, 3, 6, 7, 8}
2) clear
Remove all elements form a set
Syntax:
clear()
Eg:
>>> A={1,2,3,4,5}
>>> A
{1, 2, 3, 4, 5}
>>> A.clear()
>>> A
set()
3) copy
Return a copy of a set
Syntax:
copy()
Eg:
>>> A={1,2,3,4,5}
>>> A
{1, 2, 3, 4, 5}
>>> B=A.copy() (B=A)
>>> B
{1, 2, 3, 4, 5}
4) pop
Remove and return first set element.
Syntax:
pop()
Eg:
>>> A={1,2,3,4,5}
>>> A
{1, 2, 3, 4, 5}
>>> A.pop()
1
>>> A
{2, 3, 4, 5}
5) remove
Remove an element from a set.
Syntax:
remove(element)
Eg:
>>> A={1,2,3,4,5}
>>> A
{1, 2, 3, 4, 5}
>>> A.remove(3)
>>> A
{1, 2, 4, 5}
>>> A.remove(8)
KeyError: 8
Buit-in functions
1)len(set)
Returns the number of items in the set.
2)max(set)
Returns the maximum element in the set.
3)min(set)
Returns the minimum element in the set.
4) sum(set)
Returns the sum of items in the set.
5)sorted(set)
Return a new sorted list from elements in the set
Eg:
Set_fun.py
s=set()
print("Enter Elements")
while 1:
s.add(int(input()))
print("Enter Anohter Element(y/n) :",end='')
ch=input();
if(ch=='n'):
break
print('Given set is :',s)
print ('Length of set is :', len(s))
print ('Maximum value is :' , max(s))
print ('Minimum value is :' , min(s))
print ('Sum of items in set is :', sum(s))
Dictionaries
Python dictionary is an unordered collection of items. Creating a
dictionary is placing items inside curly braces {} separated by comma. An
item has a key and the corresponding value expressed as a pair. Each key
is separated from its value by a colon ( key : value ).
Syntax:
Dictionary_name = { key-1: value-1, key-2: value-2,….., key-n: value-n}
Eg1:
>>> d = {'a':10, 'b':1, 'c':22}
>>> d
{'a': 10, 'b': 1, 'c': 22}
Eg2:
>>> dict = {'Name': 'Harsha', 'Age': 6, 'Class': 'First'}
>>> print (dict['Name'])
Harsha
>>> print (dict['Age'])
6
>>> print (dict['Class'])
First
Updating Dictionary
Eg1:
>>> dict = {'Name': 'Hari', 'Age': 7, 'Class': 'First'}
>>> dict
{'Class': 'First', 'Name': 'Hari', 'Age': 7}
>>> dict['Age'] = 8
>>> dict['School'] = "ABC School"
>>> dict
{'Class': 'First', 'Name': 'Hari', 'Age': 8, 'School': 'ABC School'}
1 len(dict)
1 clear()
Eg1:
>>> dict = {'a':10, 'b':20, 'c':30}
>>> dict
{'b': 20, 'a': 10, 'c': 30}
>>> len(dict)
3
>>> str(dict)
"{'b': 20, 'a': 10, 'c': 30}"
Eg2:
d = {'a':10, 'b':1, 'c':22}
>>> t = d.items()
>>> t
dict_items([('a', 10), ('b', 1), ('c', 22)])
>>> print(t)
dict_items([('a', 10), ('b', 1), ('c', 22)])
Eg3:
>>> dict.values()
dict_values([20, 10, 30])
>>> dict.items()
dict_items([('b', 20), ('a', 10), ('c', 30)])
>>> dict.keys()
dict_keys(['b', 'a', 'c'])
>>> dict.clear()
>>> dict
{}
Note:
Arrays
Arrays are fundamental part of most programming languages. It is the
collection of elements of a single data type. However, in Python, there is
no native array data structure. So, we use Python lists instead of an array.
FUNCTIONS
Syn :
def functionname( parameters ):
"function_docstring"
function_suite
return [expression]
1)
#Function Defination
def show(str):
print(str)
#Function Calling
show("Welcome")
show("BDPS")
show("Thank You")
2)
#Function Defination
def sum(a,b):
c=a+b
return c
#Function Calling
a=int(input("Enter Value of A "))
b=int(input("Enter Value of B "))
c=sum(a,b)
print("Sum of A and B is ", c)
3)
#Function Defination
def fact(n):
f=1
for i in range(1,n+1):
f=f*i;
return f
#Function Calling
n=int(input("Enter Any Value "))
f=fact(n)
print(n,"Fact is ",f)
4)
#Function Defination
def change(mylist):
mylist.append([1,2,3])
print("Value inside of the function ",mylist)
return
#Function Calling
mylist=[10,20,30]
change(mylist)
print("Value Outside of the funciton",mylist)
1)
#anonymous function, lambda function
#Function definition is here
2)
#key word arguments
# Function definition is here
def printinfo( name, age ):
"This prints a passed info into this function"
print "Name: ", name
print "Age ", age
return;
3)
#key word arguments
# Function definition is here
def printinfo( name="aaa", age=20 ,sal=20000):
"This prints a passed info into this function"
print("Name: ", name)
print("Age ", age)
print("Salary ",sal)
return;
printinfo(sal=400000)
4)
#variable length argument
#Function definition is here
def printinfo( arg1, *vartuple ):
"This prints a variable passed arguments"
print ("Output is: ")
print (arg1)
for var in vartuple:
print (var)
return;
5)
def add(a, b):
print ("ADDING %d + %d" % (a, b))
return a + b
Modules
A module allows you to logically organize your Python code. Grouping
related code into a module makes the code easier to understand and use.
A module is a Python object Simply, a module is a file consisting of Python
code. A module can define functions, classes and variables. A module can
also include runnable code.
syntax:
import module1[, module2[,... moduleN]
import <file_name1, file_name2,...file_name(n)="">
1)
def myfun(st):
print("Hello : ",st)
return
def sum(a,b):
c=a+b
print("Sum of A and B is ",c)
return
def prime(n):
c=0
for i in range(1,n+1):
if n%i==0:
c=c+1
if c==2:
print("It is Prime ")
else:
print("It is not a Prime")
import demo1
demo1.myfun("welcome")
demo1.myfun("BDPS")
demo1.myfun("Thank You")
demo1.sum(10,20)
demo1.prime(7)
1)
def myfun(st):
print("Hello : ",st)
return
def sum(a,b):
c=a+b
print("Sum of A and B is ",c)
return
def prime(n):
c=0
for i in range(1,n+1):
if n%i==0:
c=c+1
if c==2:
print("It is Prime ")
else:
print("It is not a Prime")
The above file save as demo1.py
import demo1
demo1.myfun("welcome")
demo1.myfun("BDPS")
demo1.myfun("Thank You")
demo1.sum(10,20)
demo1.prime(7)
Packages in Python
===============================
A package is basically a directory with Python files and a file with the
name __init__.py. This means that every directory inside of the Python
path, which contains a file named __init__.py, will be treated as a package
by Python. It's possible to put several modulesinto a Package
def mymod1_fun():
print("This is Mymod1 Function ")
step 3 : Creat a file with the name of mymod2.py save this file in mypack
folder the write the following code in a file
def mymod2_fun():
print("This is Mymod1 Function ")
step 4 : Creat a file with the name of mymod3.py save this file in mypack
folder the write the following code in a file
def mymod3_fun():
print("This is Mymod1 Function ")
step 5 : Creat a file with the name of __init__.py save this file in mypack
folder the write the following code in a file
Modes Description
R Opens a file for reading only. The file pointer is placed at the
beginning of the file. This is the default mode.
r+ Opens a file for both reading and writing. The file pointer is
placed at the beginning of the file.
w Opens a file for writing only. Overwrites the file if the file
exists. If the file does not exist, creates a new file for writing.
w+ Opens a file for both writing and reading. Overwrites the
existing file if the file exists. If the file does not exist, creates a
new file for reading and writing.
a Opens a file for appending. The file pointer is at the end of the
file if the file exists. That is, the file is in the append mode. If
the file does not exist, it creates a new file for writing.
a+ Opens a file for both appending and reading. The file pointer is
at the end of the file if the file exists. The file opens in the
append mode. If the file does not exist, it creates a new file for
reading and writing.
write()
The write() method writes any string to an open file. It is important to note
that Python strings can have binary data and not just text. The write()
method does not add a newline character ('\n') to the end of the string:
fo=open("one.txt","w")
fo.write("This is for Sameple Example")
fo.close()
read()
The read() method reads a string from an open file. It is important to note
that Python strings can have binary data, apart from text data.
fo=open("one.txt","r+")
#fo.write( "Python is a great language.\nYeah its great!!\n");
str=fo.read(10)
print(str)
str=fo.read()
print(str)
fo.close()
2)
fo=open("one.txt","r+")
#fo.write( "Python is a great language.\nYeah its great!!\n");
str=fo.read(10)
print(str)
position = fo.tell();
print ("Current file position : ", position)
position = fo.seek(0, 0);
str = fo.read(10);
print ("Again read String is : ", str)
fo.close()
3)
fo=open("one.txt","w")
while(1):
str=input("Enter Any String ")
if(str=="end"):
break;
fo.write(str)
fo.close()
4)
fo=open("two.txt","r")
str=fo.read()
print(str)
fo.close()
5)
fo=open("three.txt","w")
ch='y'
while(ch!='n'):
str=input("Enter Number :")
str = str +'\t' + input("Enter Name : ")
str = str + '\t' + input("Enter Salary : ")
str = str + '\n'
fo.write(str)
ch=input("Enter Any More ")
fo.close()
6)
fo=open("three.txt","r")
str=fo.read()
print(str)
fo.close()
1)
ch='y'
while(ch!='n'):
f=open("emp.txt","a")
no=input("Enter Emp Number ")
name=input("Enter Emp Name ")
sal = input("Enter Emp Salary ")
f.write(no+';'+name+';'+sal+'\n')
ch=input("Any More...... ")
f.close()
2)
f=open("emp.txt","r")
content=f.readlines()
print(content)
f.close()
3)
f=open("emp.txt","r")
content=f.read()
print(content)
f.close()
4)
f=open("emp.txt","r")
for line in f:
print(line)
f.close()
5)
f=open("emp.txt","r")
no=input("Enter Number for Search ")
f.seek(0)
content=f.readline()
while content!='':
if content.find(no)!=-1:
print(content + "Found ")
flag=1
break
else:
content=f.readline()
flag=0
f.close()
if flag==0:
print("Not found ")
Os Commands
============
The rename() Method
The rename() method takes two arguments, the current filename and the
new filename.
Syntax
os.rename(current_file_name, new_file_name) os.rename( "test1.txt",
"test2.txt" )
Syntax
os.mkdir("newdir")
Syntax
os.rmdir('dirname')
File.readline([size])
The method readline() reads one entire line from the file. A trailing
newlinecharacter is kept in the string. If the size argument is present and
non-negative, it is a maximum byte count including the trailing newline
and an incomplete line may be returned. An empty string is returned only
when EOF is encountered immediately.
fo = open("foo.txt", "rw+")
print "Name of the file: ", fo.name
line = fo.readline()
print "Read Line: %s" % (line)
line = fo.readline(5)
print "Read Line: %s" % (line)
# Close opend file
fo.close()
file.seek(offset[,whence])
The method seek() sets the file's current position at the offset. The
whence argument is optional and defaults to 0, which means absolute file
positioning, other values are1 which means seek relative to the current
position and 2 means seek relative to the file's end. There is no return
value. Note that if the file is opened for appending using either 'a' or 'a+',
any seek() operations will be undone at the next write. If the file is only
opened for writing in append mode using 'a', this method is essentially a
no-op, but it remains useful for files opened in append mode with
reading enabled (mode 'a+'). If the file is opened in text mode using 't',
only offsets returned by tell() are legal. Use of other offsets causes
undefined behavior.
Note that not all file objects are seekable.
fo = open("e:\demo1.txt", "r")
print( "Name of the file: ", fo.name)
line = fo.readline()
print ("Read Line: ",line)
# Again set the pointer to the beginning
fo.seek(0, 0)
line = fo.readline()
print ("Read Line: ",line)
fo.close()
file.tell()
The method tell() returns the current position of the file read/write pointer
within the file.
Syntax
Following is the syntax for tell() method:
fileObject.tell()
fo = open("e:\demo1.txt", "r")
print( "Name of the file: ", fo.name)
line = fo.readline()
print ("Read Line: ",line)
# Get the current position of the file.
pos = fo.tell()
print ("Current Position: ",pos)
fo.seek(0,2)
pos = fo.tell()
print ("Current Position: ",pos)
# Close opend file
fo.close()
file.writelines(sequence)
The method write lines() writes a sequence of strings to the file. The
sequence can be any iterable object producing strings, typically a list of
strings. There is no return value.
Syntax
Following is the syntax for writelines() method:
fileObject.writelines( sequence )
import io
fo = open("e:\demo1.txt", "r+")
print( "Name of the file: ", fo.name)
seq = ["This is 6th line\n", "This is 7th line"]
fo.seek(0, 2)
fo.writelines(seq)
fo.seek(0,0)
for index in range(7):
line = fo.readline()
print(line)
# Close opend file
fo.close()
OOPS
=======
CLASS ,OBJECT
-> Data Abstraction/Data Hideing / Data Security
-> Data Encapsilation
-> Inheritnace
-> Polymarphysim
1)
class Emp:
def empData(self):
self.eno=111
self.ename="aaa"
self.esal=10000
print("Emp Number : ",self.eno)
print("Emp Name : ",self.ename)
print("Emp Salary : ",self.esal)
e = Emp()
e.empData()
2)
class Emp:
def getData(self):
self.eno=input("Enter Emp Number ")
self.ename=input("Enter Emp Name ")
self.esal=input("Enter Emp Salary ")
def dispData(self):
print("Emp Number : ",self.eno)
print("Emp Name : ",self.ename)
print("Emp Salary : ",self.esal)
e = Emp()
e.getData()
e.dispData()
3)
class Emp:
def getData(self):
self.eno=input("Enter Emp Number ")
self.ename=input("Enter Emp Name ")
self.esal=input("Enter Emp Salary ")
e = Emp()
e.getData()
print("Emp Number : ",e.eno)
print("Emp Name : ",e.ename)
print("Emp Salary : ",e.esal)
4)
class Demo:
__n=0
def disp(self):
self.__n=self.__n+1
print(self.__n)
class Two(Demo):
def disp2(self):
#print(Demo.__n)
print("Two")
d = Two()
d.disp()
d.disp2()
#print(d.__n)
5)
class Emp:
def getData(self):
self.__eno=input("Enter Emp Number ")
self.__ename=input("Enter Emp Name ")
self.__esal=input("Enter Emp Salary ")
def dispData(self):
print("Emp Number : ",self.__eno)
print("Emp Name : ",self.__ename)
print("Emp Salary : ",self.__esal)
e = Emp()
e.getData()
e.dispData()
6)
class Emp:
def getEmp(self,eno,ename,esal):
self.__eno=eno
self.__ename=ename
self.__esal=esal
def dispEmp(self):
print("Emp Number ",self.__eno)
print("Emp Name ",self.__ename)
print("Emp Salary ",self.__esal)
e1 = Emp()
e2 = Emp()
e3 = Emp()
e1.getEmp(111,"aaaa",1234)
e2.getEmp(222,"bbbb",22222)
e3.getEmp(333,"cccc",33333)
e1.dispEmp()
e2.dispEmp()
e3.dispEmp()
7)
class Demo:
def getData(self):
self.n=input("Enter Value of N ")
def dispData(self):
print("Value of N is ",self.n)
d1 = Demo()
d2 = Demo()
d3 = Demo()
d1.getData()
d2.getData()
d3.getData()
d1.dispData()
d2.dispData()
d3.dispData()
d1.getData()
d2.getData()
d1.dispData()
d2.dispData()
d3.sum(d1,d2)
d3.dispData()
9) passing and Returning the Objects
class Demo:
def getData(self):
self.n=input("Enter Value of N ")
def dispData(self):
print("Value of N is ",self.n)
def sum(self,d2):
d3 = Demo()
d3.n = int(self.n) + int(d2.n)
return d3
d1 = Demo()
d2 = Demo()
d3 = Demo()
d1.getData()
d2.getData()
d1.dispData()
d2.dispData()
d3 = d1.sum(d2)
d3.dispData()
def dispData(self):
print(Demo.n)
d1 = Demo()
d2 = Demo()
d3 = Demo()
d1.getData()
d2.getData()
d3.getData()
d1.dispData()
d2.dispData()
d3.dispData()
11)Constructors
class Demo:
def __init__(self):
print("This is Constructor ")
d = Demo()
10)
class Demo:
def __init__(self):
self.n=10
def dispData(self):
print("Value of N is ",self.n)
d = Demo()
d.dispData()
12)
class Emp:
def __init__(self,no,name,sal):
self.eno=no
self.ename=name
self.esal=sal
def dispData(self):
print("Emp Number ",self.eno)
print("Emp Name ",self.ename)
print("Emp Salary ",self.esal)
e1 = Emp(111,"aaa",10000)
e2 = Emp(222,"bbb",20000)
e3 = Emp(333,"ccc",30000)
e1.dispData()
e2.dispData()
e3.dispData()
13) Destructor
class Vehicle:
def __init__(self):
print('Vehicle created.')
def __del__(self):
print('Destructor called, vehicle deleted.')
car = Vehicle()
del car
14)
class Demo:
def __init__(self):
self.n=10
print("Value of N is ",self.n)
def __del__(self):
self.n=0
print("Value of N is ",self.n)
d = Demo()
del d
15)
class Demo:
n=10
def __init__(self):
print("Value of N is ",Demo.n)
Demo.n+=1
def __del__(self):
Demo.n-=1
print("Value of N is ",Demo.n)
d1 = Demo()
d2 = Demo();
d3= Demo();
del d1
del d2
del d3
16)
class Spaceship(object):
@staticmethod
def start():
print('start')
Spaceship.start()
This calls the method without creating an object. Unlike normal class
methods, they do not have access to objects variables. This may be odd,
as it seems counter to the concept of object orientated programming. In
most of the computer software you’ll find regular class methods. Static
methods are usually used as helpers.
1)
class Deg:
def degData(self):
print("This is Deg Class Method ")
class Pg(Deg):
def pgData(self):
print("This is Pg Class Method ")
p = Pg()
p.degData()
p.pgData()
2)
# Single Inheritance
class Stud(object):
def getStud(self):
self.sno=input("Enter Student Number ")
self.sname=input("Enter Student Name ")
def dispStud(self):
print("STUDENT NUMBER ",self.sno)
print("STUDNET NAME ",self.sname)
class Marks(Stud):
def getMarks(self):
self.getStud()
self.m1 = int(input("Enter Marks in Paper I "))
self.m2 = int(input("Enter Marks in Paper II "))
def dispMarks(self):
self.dispStud()
print("MARKS IN PAPER I ",self.m1)
print("MARKS IN PAPER II ",self.m2)
m = Marks()
m.getMarks()
m.dispMarks()
3)
class Marks(Stud):
def getMarks(self):
self.getStud()
self._m1 = int(input("Enter Marks in Paper I "))
self._m2 = int(input("Enter Marks in Paper II "))
def dispMarks(self):
self.dispStud()
print("MARKS IN PAPER I ",self._m1)
print("MARKS IN PAPER II ",self._m2)
class Result(Marks):
def getResult(self):
self.getMarks()
self.__tot = self._m1 + self._m2
self.__avg = self.__tot/2
def dispResult(self):
self.dispMarks()
print("TOTAL MARKS ",self.__tot)
print("AVERAGE MARKS ",self.__avg)
r = Result()
r.getResult()
r.dispResult()
4)
Hirachical Inheritnace
Base
STUD
class Emp(object):
def getEmp(self):
self.eid = int(input("Enter Emp Id "))
self.esal = float(input("Enter Emp Slary "))
def dispEmp(self):
print("EMP ID ",self.eid)
print("EMP SALARY ",self.esal)
class Person(Stud,Emp):
def getPerson(self):
self.getStud()
self.getEmp()
def dispPerson(self):
self.dispStud()
self.dispEmp()
p = Person()
p.getPerson()
p.dispPerson()
Hybrad Inheritance
================
Stud, Theory, Practical, Result
# Hybrad
class Stud(object):
def getStud(self):
self.sno=input("Enter Student Number ")
self.sname=input("Enter Student Name ")
def dispStud(self):
print("STUDENT NUMBER ",self.sno)
print("STUDNET NAME ",self.sname)
class Theory(Stud):
def getTheory(self):
self.th1=int(input("Enter Theory Paper Marks "))
def dispTheory(self):
print("THEORY PAPER MARKS ",self.th1)
class Practical(Stud):
def getPractical(self):
self.p1=int(input("Enter Practical Paper Marks "))
def dispPractical(self):
print("PRACTICAL PAPER MARKS ",self.p1)
class Result(Theory,Practical):
def getResult(self):
self.getStud()
self.getTheory()
self.getPractical()
self.tot = self.th1 + self.p1
self.avg = self.tot/2
def dispResult(self):
self.dispStud()
self.dispTheory()
self.dispPractical()
print("TOTAL MARKS ",self.tot)
print("AVERAGE MARKS ",self.avg)
r = Result()
r.getResult()
r.dispResult()
class Three(Two):
def __init__(self):
Two.__init__(self)
print("This is Class Three Constructor ")
def __del__(self):
print("This is Class Three Destructor ")
Two.__del__(self)
t1 = Three()
del t1
POLYMARPHISM
===============
What is the Polymarphism : One Object Many Interfaces
One object ---------------> One Rupee
Mobile --------> many usages
Compiletime Runtime
Static Binding Dynamic Binding
Eary Binding Late Binding
========== ===========
Function Overloading Virtual Functions
Operator Overloading Abstract Methods and Abstact Class
Function Overloading
-------------------------------
disp()
disp(10)
disp('X')
disp(20.3)
disp("BDPS")
The Multipul Functions with the same Name but the Number of
Paramters of Data type shoud be diffenent
Python
======
def disp(st="welcome"):
print(st)
Operator Overlaoding
================
+ = ==
+
a=10 b=20 c=a+b
a="Ravi" b="Babu" c=a+b C not posi strcat(a,b)
c++ no by default , but we can provide the future java,.net,python By
default is avail
================================================
==
Runtime Polymarphsim
===================
class One:
def disp(self):
print("Welcome ")
class Two(One):
def disp(self):
print("Thank You")
t = Two()
t.disp()
Ho Income()=0;
Branch1(Ho) Branch2 Brnach3
Income() Income() Income()
show()
h = Ho()
b1 = Branch1()
b2=Branch2()
b3=Branch3()
h.Income()
b1.Income()
b2.Income()
b3.Income()
x=b1
x.Income() c++,c#,java ----> It displays the Ho class Method
Python -----> It displays the Branch1 class Method
y=Ho()
y.Income()
Abstract Methods
===========
The Abstract method has only the signature, there is no
Implication. The Abstract method must has to implement in Derived Class
Abstract Class
===========
Whic class has one or More Abstract Methods that class is knows as
Abstract class
The Abstract class con't be declared any Object
Examples
=======
1)
class One(object):
def show(self):
print("This is Class One Show Method ")
class Two(One):
def show(self):
One.show(self)
print("This is class Two Show Method ")
t = Two()
t.show()
2)
class One(object):
def show(self):
print("This is Class One Show Method ")
class Two(object):
def show(self):
print("This is class Two Show Method ")
o = One()
t = Two()
o.show()
t.show()
for x in o,t:
x.show()
3)
class emp(object):
def __init__(self,no,name,amt):
self.no=no
self.name=name
self.amt=amt
def show(self):
print("Emp Number ",self.no)
print("Emp Name ",self.name)
print("Emp Salary ",self.amt)
class stud(emp):
def show(self):
print("Student Number ",self.no)
print("Student Name ",self.name)
print("Student Fee ",self.amt)
e = emp(111,"aaa",10000)
s = stud(222,"bbbb",20000)
e.show()
s.show()
4)
class Base:
def hello(self):
print("This is Base class Ho Method ")
self.hello_virtual()
def hello_virtual(self):
print("This is Base class virtual Method ")
class Derived(Base):
def hello_virtual(self):
print("This is dervid class virtual Method ")
d = Derived()
d.hello()
#d.hello_virtual()
4)
class Ho(object):
def income(self):
print("This is Ho Class Income Method ")
class Branch1(object):
def income(self):
print("This is Branch1 Class Income Method ")
class Branch2(object):
def income(self):
print("This is Branch2 Class Income Method ")
class Branch3(object):
def income(self):
print("This is Branch3 Class Income Method ")
h = Ho()
b1 =Branch1()
b2 =Branch2()
b3=Branch3()
"""
h.income()
b1.income()
b2.income()
b3.income()
"""
h.income()
h=b1
h.income()
h=b2
h.income()
h=b3
h.income()
Python on its own doesn't provide abstract classes. Yet, Python comes
with a module which provides the infrastructure for defining Abstract Base
Classes (ABCs). This module is called - for obvious reasons - abc.
1)
from abc import ABC, abstractmethod
class Abstractclass(ABC):
@abstractmethod
def do_something(self):
pass
class One(Abstractclass):
def do_something(self):
print("This is Class One Abstract Method ")
o = One()
o.do_something()
2)
class One(Abstractclass):
def do_something(self):
super().do_something()
print("This is Class One Abstract Method ")
o = One()
o.do_something()
Fun
===
def foo(arg):
x=1
#print (locals()) #1
#locals()["x"] = 2 #2
print ("x=",x) #3
z=7
print ("z=",z)
foo(z)
globals()["z"] = 8 #4
print ("z=",z) #5
Syn :
try:
some statements here
except:
exception handling
1)
try:
a=int(input("Enter Value of A "))
b=int(input("Enter VAue of B "))
c=a/b
print("Result ",c)
except ZeroDivisionError:
print("Con't Division by Zero ")
1a)
try:
a=int(input("Enter Value of A "))
b=int(input("Enter VAue of B "))
c=a/b
except ZeroDivisionError as err:
print(err)
else:
print("Result is ",c)
1b)
try:
a=input("Enter Value of A ")
b=input("Enter VAue of B ")
c=a/b
except TypeError as err:
print(err)
else:
print("Result is ",c)
2)
try:
a=int(input("Enter Value of A "))
b=int(input("Enter VAue of B "))
c=a/b
print("Result ",c)
except ZeroDivisionError as err:
print(err)
3)
try:
a=int(input("Enter Value of A "))
b=int(input("Enter VAue of B "))
c=a/b
print("Result ",c)
except ValueError as err:
print(err)
4)
try:
f=open("emp.txt","r")
content=f.readlines()
print(content)
f.close()
except FileNotFoundError as err:
print(err)
5)
try:
a=int(input("Enter Value of A "))
b=int(input("Enter VAue of B "))
c=a/b
print("Result ",c)
except ValueError as err:
print(err)
except ZeroDivisionError as err:
print(err)
6)
try:
a=int(input("Enter Value of A "))
b=int(input("Enter VAue of B "))
c=a/b
print("Result ",c)
except (ValueError,ZeroDivisionError ) as err:
print(err)
7)
try:
a=int(input("Enter Value of A "))
b=int(input("Enter VAue of B "))
c=a/b
print("Result ",c)
except ValueError as err:
print(err)
except ZeroDivisionError as err:
print(err)
except :
print("Invalid Error ")
8a)
try:
amt=int(input("Enter Withdrawl amout "))
if( amt>10000):
raise ValueError("Amout must be <=10000")
print("Amount is ",amt)
except ValueError as err:
print(err)
8)
def enterage(age):
if age < 0:
raise ValueError("Only positive integers are allowed")
if age % 2 == 0:
print("age is even")
else:
print("age is odd")
try:
num = int(input("Enter your age: "))
enterage(num)
except ValueError:
print("Only positive integers are allowed")
except:
print("something is wrong")
User Defined exception
==================
class NegativeAgeException(RuntimeError):
def __init__(self, age):
super().__init__()
self.age = age
def enterage(age):
if age < 0:
raise NegativeAgeException("Only positive integers are allowed")
if age % 2 == 0:
print("age is even")
else:
print("age is odd")
try:
num = int(input("Enter your age: "))
enterage(num)
except NegativeAgeException:
print("Only positive integers are allowed")
except:
print("something is wrong")
2)
class Myexception(Exception ):
def __init__(self, age):
super().__init__()
self.age = age
def enterage(age):
if age < 0:
raise Myexception("Value must be Positive Value ")
if age % 2 == 0:
print("age is even")
else:
print("age is odd")
try:
num = int(input("Enter your age: "))
enterage(num)
except Exception as err:
print(err)
except:
print("something is wrong")
DATABASE
==========
set of Tables
set of Colums
To store data
Files vs Databse
Flex not
Start -> All Programs -> Oralce -> App -> Sql Plus
Uid : scott
pwd : tiger
Creatin of Table
-------------------
SQL> CREATE TABLE MYEMP(ENO NUMBER,ENAME VARCHAR2(20),ESAL
NUMBER(10,2));
Table created.
no rows selected
Insrt a Records
------------------
SQL> INSERT INTO MYEMP VALUES(111,'AAA',100000);
1 row created.
1 row created.
1 row created.
1 row updated.
1 row deleted.
Save Data
-----------------
SQL> COMMIT;
# Creation of Connection
import pymysql
conn=pymysql.connect(host="localhost",user="root",password="root",db
="collage")
print("o.k")
conn.close()
2)
import pymysql
conn=pymysql.connect(host="localhost",user="root",password="root",da
tabase="collage")
cur=conn.cursor()
print(col,end=' ')
print('\n')
cur.close()
conn.close()
3)
Insert a Record to database from a Python
===========================
import pymysql
conn=pymysql.connect(host="localhost",user="root",password="root",da
tabase="collage")
cur= conn.cursor()
conn.commit()
print("Inserted ")
cur.close()
conn.close()
4) Update a Record
============
import pymysql
conn=pymysql.connect(host="localhost",user="root",password="root",da
tabase="collage")
cur= conn.cursor()
cur.execute("update emp set esal=99999 where eno=234")
conn.commit()
print("Updated ")
cur.close()
conn.close()
5) Delete a Record
=================
import pymysql
conn=pymysql.connect(host="localhost",user="root",password="root",da
tabase="collage")
cur= conn.cursor()
cur.execute("delete from emp where eno=234")
conn.commit()
print("Deleted")
cur.close()
conn.close()
6) Search a Record
----------------------------
import pymysql
conn=pymysql.connect(host="localhost",user="root",password="root",da
tabase="collage")
cur= conn.cursor()
cur.execute("select * from emp where eno=333")
for row in cur:
for col in row:
print(col,end=' ')
print("\n")
cur.close()
conn.close()
Paramter Passing
============
search a Record
---------------------
import pymysql
conn=pymysql.connect(host="localhost",user="root",password="root",da
tabase="collage")
cur= conn.cursor()
no=input("Enter Number for Search ")
cur.execute("select * from emp where eno= " + no)
for row in cur:
for col in row:
print(col,end=' ')
print("\n")
cur.close()
conn.close()
2) Insert a Record
---------------------------
import pymysql
conn=pymysql.connect(host="localhost",user="root",password="root",da
tabase="collage")
cur= conn.cursor()
ch='y'
while(ch!='n'):
no=input("Enter Emp Number ")
name=input("Enter Emp Name ")
sal=input("Enter Emp Salary ")
cur.execute("insert into emp values(" + no + ",' " + name + " ',"
+ sal +")")
conn.commit()
print("Inserted ")
ch=input("Any More..... [y/n] ")
cur.close()
conn.close()
3) Update a Record
----------------------------
import pymysql
conn=pymysql.connect(host="localhost",user="root",password="root",db
="collage")
cur = conn.cursor()
ch='y'
while(ch!='n'):
no=input("Enter Number for Search ")
sal=input("Enter Emp salary for Updation ")
cur.execute("update emp set esal=" + sal + " where eno=" + no)
conn.commit()
print("Updated ")
ch=input("Any More......[y/n] ")
cur.close()
conn.close()
4) Delete a Record
--------------------------
import pymysql
conn=pymysql.connect(host="localhost",user="root",password="root",db
="collage")
cur = conn.cursor()
ch='y'
while(ch!='n'):
conn.commit()
print("Deleted ")
conn.close()
---------------------------------------------------------------------------------
CONNECTION WITH SQLSERVER
======================
pip install pyodbc
1)
import pyodbc
conn=pyodbc.connect('Driver={SQL Server};'
'Server=OFFICE-PC;'
'Database=collage;'
'Trusted-dbo.emp;')
print('ok')
conn.close
import pyodbc
conn=pyodbc.connect('Driver={SQL Server};'
'Server=OFFICE-PC;'
'Database=collage;'
'Trusted-dbo.emp;')
cursor = conn.cursor()
print('\n')
3) Search a Record
import pyodbc
conn=pyodbc.connect('Driver={SQL Server};'
'Server=DESKTOP-AS5OQVJ;'
'Database=collage;'
'Trusted-dbo.emp;')
cur = conn.cursor()
ch='y'
while(ch!='n'):
no=input("Enter Number for Search ")
cur.execute("select * from emp where eno=" + no)
for row in cur:
for col in row:
print(col,end=' ')
print("\n")
ch=input("Any More...[y/n] ")
cur.close()
conn.close()
--> Insert a Record
--> Update a Record
--> Delete a Record
-> Enter the main event loop to take action against each event
triggered by the user.
import tkinter
top=tkinter.Tk()
top.mainloop()
or
top.mainloop()
2) Creation of Label
top.mainloop()
3) Creation of TextBox
from tkinter import *
top=Tk()
top.title("Sample Application")
top.geometry("400x400+300+200")
t1= Entry(top,width=20)
t1.pack()
top.mainloop()
4) Creation of Button
b1= Button(top,text="Submit",width=20)
b1.pack()
top.mainloop()
5) Login form
def valid():
uid=t1.get()
pwd=t2.get()
if( uid=="hari" and pwd=="bdps"):
messagebox.showinfo("Conformation","Ok")
else:
messagebox.showinfo("Conformation","Invalid User id/Password")
t1.delete(0,15)
t2.delete(0,15)
t1.focus()
top=Tk()
top.title("Login Form")
top.geometry("400x300+300+100")
top.configure(bg="black")
t2= Entry(top,width=15,show='*')
t2.place(x=250,y=170)
b1= Button(top,text="Ok",width=10,command=valid)
b1.place(x=100,y=220)
b2= Button(top,text="Cancel",width=10,command=cancel)
b2.place(x=230,y=220)
t1.focus()
top.mainloop()
2)
def add():
t3.delete(0,15)
c=int(t1.get()) + int(t2.get())
t3.insert(0,c)
def sub():
t3.delete(0,15)
c=int(t1.get()) - int(t2.get())
t3.insert(0,c)
def mul():
t3.delete(0,15)
c=int(t1.get()) * int(t2.get())
t3.insert(0,c)
def div():
t3.delete(0,15)
c=int(t1.get()) / int(t2.get())
t3.insert(0,c)
def cancel():
top.destroy()
top = Tk()
top.title("Sample Programm")
top.geometry("400x300+300+100")
l1=Label(top,text="Enter Value of A ",font=("Arial Bold",12))
l1.place(x=60,y=50)
l2=Label(top,text="Enter Value of B ",font=("Arial Bold",12))
l2.place(x=60,y=100)
l3=Label(top,text="Result ",font=("Arial Bold",12))
l3.place(x=60,y=150)
t1=Entry(top,width=20)
t1.place(x=230,y=50)
t2=Entry(top,width=20)
t2.place(x=230,y=100)
t3=Entry(top,width=20)
t3.place(x=230,y=150)
b1= Button(top,text="Add",width=10,command=add)
b1.place(x=80,y=200)
b2= Button(top,text="Sub",width=10,command=sub)
b2.place(x=180,y=200)
b3= Button(top,text="Mul",width=10,command=mul)
b3.place(x=280,y=200)
b4= Button(top,text="Div",width=10,command=div)
b4.place(x=120,y=250)
b5= Button(top,text="Exit",width=10,command=cancel)
b5.place(x=220,y=250)
t1.focus()
top.mainloop()
3) Student form
import tkinter
from tkinter import messagebox
def cancel():
t1.delete (0,20)
t2.delete (0,last=20)
t3.delete (0,last=20)
t4.delete (0,last=20)
t5.delete (0,last=20)
t6.delete (0,last=20)
t7.delete (0,last=20)
t8.delete (0,last=20)
t1.focus()
def res():
tot = int(t3.get()) + int(t4.get())
t5.insert(0,tot)
avg = int(tot)/2
t6.insert(0,avg)
t1 = tkinter.Entry(root,width=20)
t1.place(x=300, y=100)
t2 = tkinter.Entry(root,width=20)
t2.place(x=600, y=100)
t3 = tkinter.Entry(root,width=20)
t3.place(x=300, y=150)
t4 = tkinter.Entry(root,width=20)
t4.place(x=600, y=150)
t5 = tkinter.Entry(root,width=20)
t5.place(x=300, y=200)
t6 = tkinter.Entry(root,width=20)
t6.place(x=600, y=200)
t7 = tkinter.Entry(root,width=20)
t7.place(x=300, y=250)
t8 = tkinter.Entry(root,width=20)
t8.place(x=600, y=250)
b1 = tkinter.Button(root, text="Ok",width=15,height=2,command=res)
b1.place(x=250, y=300)
b2 = tkinter.Button(root, text="Cancel",
width=15,height=2,command=cancel)
b2.place(x=500, y=300)
t1.focus()
root.mainloop()
=====================================
Installation of Pymysql database Drivers
-----------------------------------------------------------
e:\>pip install pymysql
Emp form
---------------
from tkinter import *
import pymysql
conn =
pymysql.connect(host="localhost",user='root',password='root',database=
"collage")
def save():
cur=conn.cursor()
cur.execute("insert into emp values(" + t1.get() + ",'" + t2.get() + "',"
+ t3.get() + ")")
conn.commit()
cur.close()
messagebox.showinfo("conf","Saved")
def new():
t1.delete(0,20)
t2.delete(0,20)
t3.delete(0,20)
t1.focus()
def find():
try:
cur=conn.cursor()
def update():
cur=conn.cursor()
cur.execute("update emp set esal=" + t3.get() + " where eno=" +
t1.get())
conn.commit()
cur.close()
messagebox.showinfo("Conf","Updated")
def dele():
cur=conn.cursor()
cur.execute("delete from emp where eno=" + t1.get())
conn.commit()
cur.close()
messagebox.showinfo("Conf","Deleted")
new()
def cancel():
top.destroy()
top = Tk()
top.title("Sample Programm")
top.geometry("430x330+300+100")
t1=Entry(top,width=20)
t1.place(x=230,y=50)
t2=Entry(top,width=20)
t2.place(x=230,y=100)
t3=Entry(top,width=20)
t3.place(x=230,y=150)
b1= Button(top,text="New",width=10,command=new)
b1.place(x=80,y=200)
b2= Button(top,text="Save",width=10,command=save)
b2.place(x=180,y=200)
b3= Button(top,text="Find",width=10,command=find)
b3.place(x=280,y=200)
b4= Button(top,text="Update",width=10,command=update)
b4.place(x=80,y=250)
b5= Button(top,text="Delete",width=10,command=dele)
b5.place(x=180,y=250)
b6= Button(top,text="Exit",width=10,command=cancel)
b6.place(x=280,y=250)
t1.focus()
top.mainloop()
conn.close()