0% found this document useful (0 votes)
12 views120 pages

Python Full Notes

Python is a high-level, interpreted programming language created by Guido van Rossum between 1985 and 1990, named after 'Monty Python's Flying Circus'. It features an easy-to-learn syntax, supports multiple programming paradigms including object-oriented programming, and is available on various platforms. The document also covers Python's data types, operators, and environment setup, making it suitable for beginners and versatile for various applications.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views120 pages

Python Full Notes

Python is a high-level, interpreted programming language created by Guido van Rossum between 1985 and 1990, named after 'Monty Python's Flying Circus'. It features an easy-to-learn syntax, supports multiple programming paradigms including object-oriented programming, and is available on various platforms. The document also covers Python's data types, operators, and environment setup, making it suitable for beginners and versatile for various applications.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 120

PYTHON

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).

Why the name Python?


It wasn't named a dangerous snake. Rossum was fan of a comedy series from
late seventies. The name "Python" was adopted from the same series "Monty
Python's Flying Circus".

Python is Interpreted: Python is processed at runtime by the interpreter. You


do not need to compile your program before executing it. This is similar to PERL
and PHP.

Python is Interactive: You can actually sit at a Python prompt and interact
with the interpreter directly to write your programs.

Python is Object-Oriented: Python supports Object-Oriented style or


technique of programming that encapsulates code within objects.

Python is a Beginner's Language: Python is a great language for the


beginner-level programmers and supports the development of a wide range of
applications from simple text processing to WWW browsers to games.

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.

Easy-to-maintain: Python's source code is fairly easy-to-maintain.

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.

Databases: Python provides interfaces to all major commercial databases.

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.

Local Environment Setup


Open a terminal window and type "python" to find out if it is already installed
and which version is installed.

 Unix (Solaris, Linux, FreeBSD, AIX, HP/UX, SunOS, IRIX, etc.)


 Win 9x/NT/2000
 Macintosh (Intel, PPC, 68K)
 OS/2
 DOS (multiple versions)
 PalmOS
 Nokia mobile phones
 Windows CE
 Acorn/RISC OS
 BeOS
 Amiga
 VMS/OpenVMS
 QNX
 VxWorks
 Psion
 Python has also been ported to the Java and .NET virtual machines

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

Here are the steps to install Python on Windows machine.


Open a Web browser and go to http://www.python.org/download/

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.

Unix: IDLE is the very first Unix IDE for 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

keywords contain lowercase letters only.

and exec not


assert finally or
break for pass
class from print
continue global raise
def if return
del import try
elif in while
else is with
except lambda yield

Lines and Indentation


Python provides no braces to indicate blocks of code for class and function
definitions or flow control. Blocks of code are denoted by line indentation, which
is rigidly enforced.
The number of spaces in the indentation is variable, but all statements within the
block must be indented the same amount.

Standard Data Types

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]]]]

Python supports four different numerical types:

 int (signed integers)


 long (long integers, they can also be represented in octal
and hexadecimal)
 float (floating point real values)
 complex (complex numbers)

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.

str = 'Hello World!'

print (str) # Prints complete string


print (str[0]) # Prints first character of the string
print (str[2:5]) # Prints characters starting from 3rd to 5th
print (str[2:]) # Prints string starting from 3rd character
print (str * 2) # Prints string two times
print (str + "TEST") # Prints concatenated string

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.

list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]


tinylist = [123, 'john']

print (list) # Prints complete list


print (list[0]) # Prints first element of the list
print (list[1:3]) # Prints elements starting from 2nd till 3rd
print (list[2:]) # Prints elements starting from 3rd element
print (tinylist * 2) # Prints list two times
print (list + tinylist) # Prints concatenated lists
Python Tuples
A tuple is another sequence data type that is similar to the list. A tuple
consists of a number of values separated by commas. Unlike lists,
however, tuples are enclosed within parentheses () . The parentheses are
optional but is a good practice to write it.

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)

tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )


tinytuple = (123, 'john')

print (tuple) # Prints complete tuple


print (tuple[0]) # Prints first element of the tuple
print (tuple[1:3]) # Prints elements starting from 2nd till 3rd
print (tuple[2:]) # Prints elements starting from 3rd element
print (tinytuple * 2) # Prints tuple two times
print (tuple + tinytuple) # Prints concatenated tuple

The following code is invalid with tuple, because we attempted to update


a tuple, which is not allowed. Similar case is possible with lists −
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tuple[2] = 1000 # Invalid syntax with tuple
list[2] = 1000 # Valid syntax with list
Python Dictionary
Python's dictionaries are kind of hash table type. They work like
associative arrays or hashes found in Perl and consist of key-value pairs.
A dictionary key can be almost any Python type, but are usually numbers
or strings. Values, on the other hand, can be any arbitrary Python object.

Dictionaries are enclosed by curly braces ({ }) and values can be


assigned and accessed using square braces ([]). For example −

dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"

tinydict = {'name': 'john','code':6734, 'dept': 'sales'}

print (dict['one']) # Prints value for 'one' key


print (dict[2]) # Prints value for 2 key
print (tinydict) # Prints complete dictionary
print (tinydict.keys()) # Prints all the keys
print (tinydict.values()) # Prints all the values

Dictionaries have no concept of order among elements. It is incorrect to


say that the elements are "out of order"; they are simply unordered.

# nested tuple
# Output: ("mouse", [8, 4, 6], (1, 2, 3))
my_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
print(my_tuple)

# tuple can be created without parentheses


# also called tuple packing
# Output: 3, 4.6, "dog"
my_tuple = 3, 4.6, "dog"
print(my_tuple)

# tuple unpacking is also possible


# Output:
# 3
# 4.6
# dog
a, b, c = my_tuple
print(a)
print(b)
print(c)

# 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])

Data Type Conversion


Sometimes, you may need to perform conversions between the built-in
types. To convert between types, you simply use the type name as a
function.
There are several built-in functions to perform conversion from one data
type to another. These functions return a new object representing the
converted value.

Function Description

int(x [,base]) Converts x to an integer. base specifies the base if x is a string.

float(x) Converts x to a floating-point number.

complex(real [,imag]) Creates a complex number.

str(x) Converts object x to a string representation.

repr(x) Converts object x to an expression string.

eval(str) Evaluates a string and returns an object.


tuple(s) Converts s to a tuple.

list(s) Converts s to a list.

dict(d) Creates a dictionary. d must be a sequence of (key,value) tuples.

chr(x) Converts an integer to a character.

unichr(x) Converts an integer to a Unicode character.

ord(x) Converts a single character to its integer value.

hex(x) Converts an integer to a hexadecimal string.

oct(x) Converts an integer to an octal string.

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

and both the operands are true


or either of the operands is true
not operand is false

Assignment operators
= += -= *= /= %= //= **=

Special Operators
1.Identity
2.Membership

Identity Operators Meaning


Operator
is True if the operands are
identical (refer to the same
object)

is not True if the operands are not


identical (do not refer to the
same object)

x1 = 5 y1 = 5
x2 = 'Hello' y2 = 'Hello'
x3 = [1,2,3] y3 = [1,2,3]

print(x1 is not y1)


print(x2 is y2)
print(x3 is y3)

Output:
False
True
False

In above example x1 and y1 are integers of same values, so they are


equal as well as identical. Same is the case with x2 and y2 (strings). But
x3 and y3 are list. They are equal but not identical. Since list are mutable
(can be changed), interpreter locates them separately in memory
although they are equal.

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

not in True if value/variable is


not found in the sequence
Example: in and not in
x = 'Hello world'
y = {1:'a',2:'b'}
print('H' in x)
print('hello' not in x)
print(1 in y)
print('a' in y)
output:
True
True
True
False

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)

This is explicit line continuation. In Python, line continuation is implied


inside parentheses ( ), brackets [ ] and braces { }. For instance, we can
implement the above multi-line statement as

a = (1 + 2 + 3 +
4+5+6+
7 + 8 + 9)
print(a)
colors = ['red',
'blue',
'green']

We could also put multiple statements in a single line using


semicolons, as follows
a = 1; b = 2; c = 3

Python Single - Line Comments


#This is a comment
#print out Hello

Python Multi – Line Comments


“”” three time double quotes.

"""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")

Print an object without a trailing newline

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()

input() is used to input numeric type data.


x = input('Enter any value ')

Control Flow Statements :


Sinple if statement

It is a Conditional control statement in Python

The general form of the if statement is:

if condition :

block

• The reserved word if begins a if statement.

• The condition is a Boolean expression . A colon (:) must

follow the condition.

• The block is a block of one or more statements to be executed

if the condition is true.

- To find maximum value of given to values using simple if

If.py

print ("Enter any two values")

a=int(input())

b=int(input())

max=a

if max < b :

max=b

print("Maximum value :",max)

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

The condition is a Boolean expression, if it is true then if block will be


executed otherwise else block will be executed.
- To find maximum value of given to values using simple if-else

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)

- To check whether the given number is even or odd

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

In this statement, the conditions are evaluated from top to bottom, if


the condition is true then the statements associated that block is
executed and the control transfers to the next statement. Otherwise when
all conditions are false then the final else block statements will be
executed.
- Find maximum of 3 values using if-elif-else

If-elif.py

print("Enter any 3 values ")


a=int(input())
b=int(input())
c=int(input())
if a>b and a>c :
max=a
elif b>c :
max=b
else :
max=c
print("Maximum value :",max)

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

print("Enter any character : ",end='')


ch=ord(input())
if (ch>=65 and ch<=90) or (ch>=97 and ch<=122) :
print("Given character is a alphabet")
elif (ch>=48 and ch<=57) :
print("Given character is a digit")
else :
print("Given character is a special character")

Loop control statements :


loop:
The process of repeatedly executing a block of statement up to
specified number of times is called as loop.
Python supports 2 types of looping statements. They are :
1) while loop
2) for loop

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.

#To Display natural numbers from 1 to given number


print("Enter a number : ",end='')
n=int(input())
print("Natural number from 1 to %d" %(n))
i=1
while i<=n :
print("%d\t"%(i),end='')
i=i+1
#To Display Even and Odd numbers from 1 to given number

print("Enter any Number : ",end='')


n=int(input())
print("\nEven number from 1 to %d" %(n))
i=1
while i<=n :
if i%2==0 :
print("%d\t"%(i),end='')
i=i+1
print("\n\nOdd number from 1 to %d" %(n))
i=1
while i<=n :
if i%2!=0 :
print("%d\t"%(i),end='')
i=i+1
#To Display factors of given number
print("Enter any Number : ",end='')
n=int(input())
print("\nFactors of %d" %(n))
i=1
while i<=n :
if n%i==0 :
print("%d\t"%(i),end='')
i=i+1
#To check whether the given number is prime or not
print("Enter any Number : ",end='')
n=int(input())
count=0
i=1
while i<=n :
if n%i==0 :
count=count+1
i=i+1
if count==2 :
print("Given Number is Prime")
else :
print("Given Number is Not Prime")

#To calculate and display factorial of given number

print("Enter any Number : ",end='')


n=int(input())
fact=1
while n>=1 :
fact=fact*n
n=n-1
print("Factorial of Given Number :",fact)

#To calculate and display Reverse of given number

print("Enter any Number : ",end='')


n=int(input())
rev=0
while n>0 :
rev=(rev*10)+(n%10)
n=int(n/10)
print("Reverse Number :",rev)

#To display Fibonacci series of first n terms


print("Enter any Number : ",end='')
n=int(input())
i,a,b,c=1,1,0,0
print("Fibonacci Series :",end='')
while i<=n :
print("%d\t"%(c),end="")
c=a+b
a=b
b=c
i=i+1

The range () Function


The range() function generates and returns a sequence of integers and is
very commonly used in for loop statement. There are 3 variations of the
range() function, depending on the number of parameters passed to it.

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.

Note: When step is not specified, its default value is 1.


• range(10) -> 0,1,2,3,4,5,6,7,8,9
• range(1, 10) -> 1,2,3,4,5,6,7,8,9
• range(1, 10, 2) -> 1,3,5,7,9
• range(10, 0, -1) -> 10,9,8,7,6,5,4,3,2,1
• range(10, 0, -2) -> 10,8,6,4,2
• range(2, 11, 2) -> 2,4,6,8,10
• range(-5, 5) -> −5,−4,−3,−2,−1,0,1,2,3,4

The for Loop


The for loop iterates over a range of values. These values can be a
numeric range, or, elements of a data structure like a string, list, or tuple.
Syntax:
for iterating_var in sequence:
statements

# To displays numbers from 1 to Given Number


Printf(“Enter any Number :”)
n=int(intput())
print(“Natural Number from 1 to”,n)
for i in range(1,n+1):
print (i)
#To Display Even and Odd numbers from 1 to given number using for loop
print("Enter any Number : ",end='')
n=int(input())
print("\nEven number from 1 to",n)
for i in range(2,n+1,2):
print(i,end='\t')
print("\n\nOdd number from 1 to",n)
for i in range(1,n+1,2):
print(i,end='\t')

The break statement


The break statement terminates and exits from the current loop. It is
typically used in an infinite loop.
Syntax:
break
Infinite Loops
An infinite loop is a loop that executes its block of statements
repeatedly until the user forces the loop to quit.
break.py
k=1
while 1 :
print (k,”\t”,end=’’)
k=k+1
if(k>10):
break
Output:
1 2 3 4 5 6 7 8 9 10

The continue Statement


The continue statement stops execution of the current iteration by
skipping the rest of the loop and continuing to execute the loop with the
next iterative value.

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

The pass Statement


The pass statement is used in Python to indicate an empty block of
statements.

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

Using a loop statement within another loop is called as nested loops.

#To display Prime Numbers from 1 to given number .


Prime1.py
print("Enter any Number : ",end='')
n=int(input())
for i in range(1,n+1) :
count=0
j=1
while j<=i :
if i%j==0 :
count=count+1
j=j+1
if count==2 :
print(i,"\t",end='')

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]

Access Elements from a list


There are various ways in which we can access the elements of a list.

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:

>>> my_list = ['P','Y','T','H','O','N']


>>> my_list
['P', 'Y', 'T', 'H', 'O', 'N']
>>> print(my_list[2])
T
>>> print(my_list[5])
N
Sub lists
>>> num_list=[[1,2,3],[100,200,300]]
>>> num_list
[[1, 2, 3], [100, 200, 300]]
>>> print(num_list[0][1])
2
>>> print(num_list[1][2])
300
Negative indexing
Python allows negative indexing . The index of -1 refers to the last item, -
2 to the second last item and so on.
>>> my_list = ['P','Y','T','H','O','N']
>>> print(my_list[-1])
N
>>> print(my_list[-6])
P

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]

# elements 6th to end


>>> print(my_list[5:])
[60, 70, 80, 90, 100]
# elements beginning to end
>>> print(my_list[:])
[10,20,30,40,50,60,70,80,90,100]

change elements in a list


List is mutable, means their elements can be changed .We can use
Assignment operator (=) to change an item or a range of items.
Eg:
>>> my_list=[2,5,7,8,10]
>>> my_list
[2, 5, 7, 8, 10]
# change the 1st item
>>> my_list[0]=1
>>> my_list
[1, 5, 7, 8, 10]
# change 2nd to 5th items
>>> my_list[1:5]=[2,3,4,5]
>>> my_list
[1, 2, 3, 4, 5]

Delete Elements from a List


We can delete one or more items from a list using the keyword del .
Eg:
>>> my_list=[1,2,3,4,5]
>>> my_list
[1, 2, 3, 4, 5]
>>> del my_list[1]
>>> my_list
[1, 3, 4, 5]
>>> my_list=['P','Y','T', 'H','O','N']
>>> my_list
['P', 'Y', 'T', 'H', 'O', 'N']
>>> del my_list[1:3]
>>> my_list
['P', 'H', 'O', 'N']
>>> del my_list
>>> my_list
NameError: name 'my_list' is not defined
List Methods
Some Methods are available with list object in Python programming They are
accessed as listobject .method()
1)append

Add an element to the end of the list


Syntax:
append(x)
x - element
Eg:
>>> my_list=[1,2,3]
>>> my_list
[1, 2, 3]
>>> my_list.append(4)
>>> my_list
[1, 2, 3, 4]

#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]

#To accept a group of elements and display in Ascending order


List_sort.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)
a.sort()
print("Given Elements in Ascending order :",a)

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.

Note: parentheses brackets are optional for Tuples


Syntax:
Tuple_name=(item-1,item-2,…,iem-n)
Eg:
>>> tup1=('hari','ravi',100,200)
>>> tup1
('hari', 'ravi', 100, 200)
>>> tup2=(1,2,3,4,5)
>>> tup2
(1, 2, 3, 4, 5)
>>> tup3 = "a", "b", "c", "d"
>>> tup3
('a', 'b', 'c', 'd')
>>> t=tuple('PYTHON')
>>> t
('P', 'Y', 'T', 'H', 'O', 'N')
>>> print(t[0])
P
>>> print(t[1:3])
('Y', 'T')
>>> a=(1,2,3)
>>> b=(4,5,6)
>>> c=a+b
>>> c
(1, 2, 3, 4, 5, 6)

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}

Python Set Operations

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.

Union is performed using | operator. Same can be accomplished using the


method union().

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}

Set Symmetric Difference


Symmetric Difference of A and B is a set of elements in both A and B
except those that are common in both.
Symmetric difference is performed using ^ operator. Same can be
accomplished using the method symmetric_difference() .
Sdiff.py
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
print(A ^ B)
Output: {1, 2, 3, 6, 7, 8}

Eg:
>>> A.symmetric_difference(B)
{1, 2, 3, 6, 7, 8}
>>> B.symmetric_difference(A)
{1, 2, 3, 6, 7, 8}

Python Set Methods


1) add
Add an element to a set
Syntax :
add(element)
Eg:
>>> A={1,2,3,4}
>>> A
{1, 2, 3, 4}
>>> A.add(5)
>>> A
{1, 2, 3, 4, 5}

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'}

Built-in Dictionary Functions & Methods


Python includes the following dictionary functions−
Sr.No. Function with Description

1 len(dict)

Gives the total length of the dictionary.


2 str(dict)

Produces a string representation of a dictionary

Python includes following dictionary methods


Sr.No. Methods with Description

1 clear()

Removes all elements of dictionary dict


2 items()

Returns a list of dict's (key, value) tuple pairs


3 keys()

Returns list of dictionary dict's keys


4 values()
Returns list of dictionary dict's values

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

sum = lambda arg1, arg2: arg1 + arg2;


# Now you can call sum as a function
print ("Value of total : ", sum( 10, 20 ))
print ("Value of total : ", sum( 20, 20 ))

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;

# Now you can call printinfo function


printinfo( age=35, name="Kumar" )
printinfo(45,"sri")
printinfo("aaa",50)

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;

# Now you can call printinfo function


printinfo( 10 )
printinfo( 70, 60, 50 )

5)
def add(a, b):
print ("ADDING %d + %d" % (a, b))
return a + b

def subtract(a, b):


print ("SUBTRACTING %d - %d" % (a, b))
return a - b

def multiply(a, b):


print ("MULTIPLYING %d * %d" % (a, b))
return a * b

def divide(a, b):


print ("DIVIDING %d / %d" % (a, b))
return a / b

print ("Let's do some math with just functions!")


age = add(30, 5)
height = subtract(78, 4)
weight = multiply(90, 2)
iq = divide(100, 2)
print ("Age: %d, Height: %d, Weight: %d, IQ: %d" % (age, height, weight,
iq))

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.

1)The import Statement


You can use any Python source file as a module by executing an import
statement in some other Python source file. The import has the following

syntax:
import module1[, module2[,... moduleN]
import <file_name1, file_name2,...file_name(n)="">

2) Using from.. import statement:


from..import statement is used to import particular attribute from a
module. In case you do not want whole of the module to be imported then
you can use from ?import statement.
Syntax:
from <module_name> import
<attribute1,attribute2,attribute3,...attributen>

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)
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

Procedure for creation of Package


step 1 : Creat a folder with the name of e:\mypack
step 2 : Creat a file with the name of mymod1.py save this file in mypack
folder the write the following code in a file

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

from mymod1 import *


from mymod2 import *
from mymod3 import *

Importing the Package


====================
import mypack
mypack.mymod1_fun()
mypack.mymod2_fun()
mypack.mymod3_fun()

Note : set the env variable the folder location


Python ─ Files I/O
Opening and Closing Files
Until now, you have been reading and writing to the standard input and
output. Now, we will see how to use actual data files.
Python provides basic functions and methods necessary to manipulate
files by
default. You can do your most of the file manipulation using a file object

The open Function


Before you can read or write a file, you have to open it using Python's
builtin open()function. This function creates a file object, which would be
utilized to call other support methods associated with it.

Syntax: file object = open(file_name [, access_mode])


Here are parameter details:
file_name: The file_name argument is a string value that contains the
name of the file that you want to access.
access_mode: The access_mode determines the mode in which the file
has to be opened, i.e., read, write, append, etc. A complete list of possible
values is given below in the table. This is optional parameter and the
default file access mode is read (r).

Here is a list of the different modes of opening 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.

The file Object Attributes


Once a file is opened and you have one file object, you can get various
information related to that file. Here is a list of all attributes related to file
object:
Attribute Description
file.closed Returns true if file is closed, false otherwise.
file.mode Returns access mode with which file was pened.
file.name Returns name of the file.
fo=open("one.txt","w")
print("File Name ",fo.name)
print("File Open Mode ",fo.mode)
print("File Close or Not ",fo.closed)

Reading and Writing Files


The file object provides a set of access methods to make our lives easier. We
would see how to use read() and write() methods to read and write files.

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" )

The remove() Method


You can use the remove() method to delete files by supplying the name of
the file to be deleted as the argument.
Syntax
os.remove(file_name)
os.remove("text2.txt")

The mkdir() Method


You can use the mkdir() method of the os module to create directories in the
current directory. You need to supply an argument to this method which contains
the name of the directory to be created.

Syntax
os.mkdir("newdir")

The chdir() Method


You can use the chdir() method to change the current directory. The
chdir() method takes an argument, which is the name of the directory that
you want to make the current directory.
Syntax
os.chdir("newdir")

The getcwd() Method


The getcwd() method displays the current working directory.
Syntax
os.getcwd()

The rmdir() Method


The rmdir() method deletes the directory, which is passed as an argument in the
method. Before removing a directory, all the contents in it should be removed.

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()

8) Passing the Objects as a Argumnets


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,d1,d2):
self.n = int(d1.n) + int(d2.n)
d1 = Demo()
d2 = Demo()
d3 = Demo()

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()

10) class Variabales


class Demo:
n=0
def getData(self):
Demo.n=input("Enter Value of N ")

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

class method vs static method in Python


===============================
class Spaceship(object):
@staticmethod
def start():
print('start')
Spaceship.start()

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)

# Multy Lavel 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)
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

Der1 Der2 Der3 .........


ECE CSE IT

# Multy Lavel 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 Ece(Stud):
def getEce(self):
self.getStud()
self._ec1 = int(input("Enter Marks in ECE Paper I "))
self._ec2 = int(input("Enter Marks in ECE Paper II "))
def dispEce(self):
self.dispStud()
print("MARKS IN ECE PAPER I ",self._ec1)
print("MARKS IN ECE PAPER II ",self._ec2)
class Cse(Stud):
def getCse(self):
self.getStud()
self._cs1 = int(input("Enter Marks in CSE Paper I "))
self._cs2 = int(input("Enter Marks in CSE Paper II "))
def dispCse(self):
self.dispStud()
print("MARKS IN CSE PAPER I ",self._cs1)
print("MARKS IN CSE PAPER II ",self._cs2)
ch=0
while(ch!=3):
print("[1] ECE ")
print("[2] CSE ")
print("[3] EXIT ")
ch=int(input("Enter Your Choice... "))
if(ch==1):
e = Ece()
e.getEce()
e.dispEce()
elif(ch==2):
c = Cse()
c.getCse()
c.dispCse()
5) Multipul Inheritnace
Base1 Base2 ....
Der
# Multipul 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 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()

Constructors fireing in Inheritnace


==========================
class One(object):
def __init__(self):
print("This is Class One Constructor ")
class Two(One):
def __init__(self):
One.__init__(self)
print("This is Class Two Constructor ")
class Three(Two):
def __init__(self):
Two.__init__(self)
print("This is Class Three Constructor ")
t1 = Three()
--> Destructors Fireing in Inheritance
class One(object):
def __init__(self):
print("This is Class One Constructor ")
def __del__(self):
print("This is Class One Destructor ")
class Two(One):
def __init__(self):
One.__init__(self)
print("This is Class Two Constructor ")
def __del__(self):
print("This is Class Two Destructor ")
One.__del__(self)

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")

void disp(int) Not Posibul in C because all the functions


names is same
void disp(char)
void disp(float) It can posibul in C++,C# and Java
void disp(char [])
int sum(int,int)
int sum(int,int,int)
int sum(int,int,int,int,int,int) def sum(a,*b)

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=Ho Ho x = New Ho(); Object


b1=Branch1 Ho y; Variable
b2=Branch2
b3=Branch3

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()

Abstract Methods and Abstract Class


===========================
Abstract Classes
Abstract classes are classes that contain one or more abstract methods.
An abstract method is a method that is declared, but contains no
implementation. Abstract classes may not be instantiated, and require
subclasses to provide implementations for the abstract methods.
Subclasses of an abstract class in Python are not required to implement
abstract methods of the parent class.

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)

from abc import ABC, abstractmethod


class Abstractclass(ABC):
@abstractmethod
def do_something(self):
print("Abstract Method ")

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

Exception Handling in Python


======================
What is an Exception?
An exception is an error that happens during execution of a program.
When that error occurs, Python generate an exception that can be
handled, which avoids your program to crash.

Why use Exceptions?


Exceptions are convenient in many ways for handling errors and special
conditions in a program. When you think that you have a code which can
produce an error then you can use exception handling.

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
==========

What is the Dtabase :

set of Tables

What is the Table :

set of Rows and Cols

What is the Row

set of Colums

What is the Purpus :

To store data

Files vs Databse

Flex not

No security Will Secured

Small Data Large Data can store

Single user Multy User can access at a time

Front End Back End


======== =======
c#/vb/php Ms Access ( Single User )
Java My Sql ( Free licance)
Python Ms Sal Gui
Oracle Cui
server (Databse)
clinet1 cleint2 Client3.....
Python Java C# ...

How to access the Databse


==================
If we want to access the database we need a SQL

Login into Oracle


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

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.

Display the Structure


------------------------
SQL> DESC MYEMP;
Name Null? Type
----------------------------------------- -------- ----------------------------
ENO NUMBER
ENAME VARCHAR2(20)
ESAL NUMBER(10,2)

SQL> SELECT * FROM MYEMP;

no rows selected
Insrt a Records
------------------
SQL> INSERT INTO MYEMP VALUES(111,'AAA',100000);

1 row created.

SQL> INSERT INTO MYEMP VALUES(222,'BBB',20000);

1 row created.

SQL> INSERT INTO MYEMP VALUES(333,'CCC',30000);

1 row created.

SQL> SELECT * FROM MYEMP;

ENO ENAME ESAL


---------- -------------------- ----------
111 AAA 100000
222 BBB 20000
333 CCC 30000

Updating an Exisitng Data


-------------------------------------
SQL> UPDATE MYEMP SET ESAL = 9999 WHERE ENO=222;

1 row updated.

SQL> SELECT * FROM MYEMP;

ENO ENAME ESAL


---------- -------------------- ----------
111 AAA 100000
222 BBB 9999
333 CCC 30000

Find a Specific Record from Database


-----------------------------------------------------
SQL> SELECT * FROM MYEMP WHERE ENO=222;

ENO ENAME ESAL


---------- -------------------- ----------
222 BBB 9999

Delete a Record from Datbase


-------------------------------------------
SQL> DELETE FROM MYEMP WHERE ENO=222;

1 row deleted.

SQL> SELECT * FROM MYEMP;

ENO ENAME ESAL


---------- -------------------- -------------
111 AAA 100000
333 CCC 30000

Save Data
-----------------
SQL> COMMIT;

Save and Exit


--------------------
SQL>exit()

Login into Mysql


=============
Start-> All Programs -> Mysql Front -> Mysql Front
Local Host Open

-> Creation of Databse

-> Creation of Table

-> Cretion of fields

-> Insert a Rows

-> Update a Rows

-> Delete a Rows

MySql Database Connection with Python


===========================
1)

# Creation of Connection

import pymysql

conn=pymysql.connect(host="localhost",user="root",password="root",db
="collage")

print("o.k")

conn.close()

2)

# Diplays all the Records

import pymysql

conn=pymysql.connect(host="localhost",user="root",password="root",da
tabase="collage")

cur=conn.cursor()

cur.execute("select * from emp")

for row in cur:

for col in row:

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()

cur.execute("insert into emp values(234,'you',30000)")

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'):

no=input("Enter Number for Deletion ")

cur.execute("delete from emp where eno=" +no)

conn.commit()

print("Deleted ")

ch=input("Any More......[y/n] ")


cur.close()

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

2) Display all records

import pyodbc

conn=pyodbc.connect('Driver={SQL Server};'

'Server=OFFICE-PC;'

'Database=collage;'

'Trusted-dbo.emp;')

cursor = conn.cursor()

cursor.execute('SELECT * FROM collage.dbo.emp')

for row in cursor:

for col in row:


print(col,end='\t')

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

GUI (Graphical User Interface) Applications


============================
Tkinter Programming
=================
Tkinter is the standard GUI library for Python. Python when combined with
Tkinter provides a fast and easy way to create GUI applications.
Creating a GUI application using Tkinter is an easy task. All you need to do
is perform the following steps −

-> Import the Tkinter module.

-> Create the GUI application main window.

-> Add one or more of the above-mentioned widgets

-> Enter the main event loop to take action against each event
triggered by the user.

1) Creation of Form or Continar

import tkinter
top=tkinter.Tk()

top.mainloop()

or

from tkinter import *


top= Tk()

top.mainloop()

2) Creation of Label

from tkinter import *


top=Tk()
top.title("Sample Application")
top.geometry("400x400+300+200")

l1=Label(top,text="BDPS Computer Education",font=("Arial


Bold",15),fg="red")
l1.pack()

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

from tkinter import *


top=Tk()
top.title("Sample Application")
top.geometry("400x400+300+200")

b1= Button(top,text="Submit",width=20)
b1.pack()

top.mainloop()

5) Login form

from tkinter import *


from tkinter import messagebox
def cancel():
top.destroy()

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")

l1= Label(top,text="Login Form ",font=("Arial


Bold",25),fg="white",bg="black")
l1.place(x=100,y=50)

l2= Label(top,text="Enter User Id ",font=("Arial


Bold",15),fg="white",bg="black")
l2.place(x=50,y=120)

l3= Label(top,text="Enter Password ",font=("Arial


Bold",15),fg="white",bg="black")
l3.place(x=50,y=170)
t1= Entry(top,width=15)
t1.place(x=250,y=120)

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)

from tkinter import *


from tkinter import messagebox

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)

if( int(t3.get())>=35 and int(t4.get())>=35):


res="pass"
if(int(avg)>=60):
div="First"
elif(int(avg)>=50):
div="Second"
else:
div="Third"
else:
res="Fail"
div="No div"
t7.insert(0,res)
t8.insert(0,div)
root = tkinter.Tk()
root.title("Student Form")
w=800
h=400
x=50
y=100
root.geometry("%dx%d+%d+%d" % (w,h,x,y))

l1= tkinter.Label(root,text="STUDENT DATA FORM")


l1.place(x=300,y=30)

l2= tkinter.Label(root,text="Student Number ")


l2.place(x=150,y=100)

l3= tkinter.Label(root,text="Student Name ")


l3.place(x=500,y=100)

l4= tkinter.Label(root,text="Marks in Paper I ")


l4.place(x=150,y=150)

l5= tkinter.Label(root,text="Marks in Paper II ")


l5.place(x=500,y=150)

l6= tkinter.Label(root,text="Total Marks ")


l6.place(x=150,y=200)

l7= tkinter.Label(root,text="Average Marks ")


l7.place(x=500,y=200)

l8= tkinter.Label(root,text="Result ")


l8.place(x=150,y=250)

l9= tkinter.Label(root,text="Divison ")


l9.place(x=500,y=250)

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 *

from tkinter import messagebox

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()

cur.execute("select * from emp where eno="+ t1.get())


r=cur.fetchall()
#t1.insert(0,r[0][0])
t2.insert(0,r[0][1])
t3.insert(0,r[0][2])
except Exception as e:
messagebox.showerror("Error","Invalid Number")

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")

l1=Label(top,text="Enter Emp Number ",font=("Arial Bold",12))


l1.place(x=60,y=50)
l2=Label(top,text="Enter Emp Name ",font=("Arial Bold",12))
l2.place(x=60,y=100)
l3=Label(top,text="Enter Emp Salary ",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="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()

You might also like