Basic Python

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 113

Installation of python

www.python.org

python 2 vs python 3

both are independent languages

from 2020 there is no support of python2

recommended to use python3


Python is repl tool:

Repl(read evaluate print loop)

>>> print("hi")

hi

>>> print("jain")

jain

>>> 100+200

300

>>>

Another way to run python programs


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

n=int(input("enter number"))

for i in range(n):

print("hello ")

n=int(input("enter number"))

m=int(input("enter number"))

print(n+m)

print(n*m)

print(n-m)

print(n/m)

C:\>cd del

C:\del>py demo1.py

enter number3
enter number4

12

-1

0.75

C:\del>python demo1.py

enter number4

enter number5

20

-1

0.8

Python editors:
Editplus

Notepad++

Python shell

Python ides

• Pycharm
• Eclipse
• Spyder
• jupyter notebook
• anaconda python
Python 3.7.1 (v3.7.1:260ec2c36a, Oct 20 2018, 14:05:16) [MSC v.1915 32 bit
(Intel)] on win32

Type "help", "copyright", "credits" or "license()" for more information.

>>> print("welcome to python")

welcome to python

>>> print("stravan")

stravan

>>>
>>> 100+200

300

>>> 100<200

True

Introduction to python

Python is a general purpose high level programming language

Why is python

Guido van rossam>>father of python<<1989 NRI(national research institute


)netherlands

DOB:Feb 20th 1991

Note :in java from 1.9 version onwards jshell introduced

C:\Users\srikanth>CD\

C:\>javac -version
javac 11.0.2

C:\>java -version

java version "11.0.2" 2019-01-15 LTS

Java(TM) SE Runtime Environment 18.9 (build 11.0.2+9-LTS)

Java HotSpot(TM) 64-Bit Server VM 18.9 (build 11.0.2+9-LTS, mixed mode)

C:\>jshell

| Welcome to JShell -- Version 11.0.2

| For an introduction type: /help intro

jshell> System.out.println("hi");

hi

jshell> int a=20,b=20,c;

a ==> 20

b ==> 20

c ==> 0

jshell> System.out.println(a+b);

40

C,java is statically typed programming:

Python is dynamically typed programming

>>> a=10

>>> type(a)
<class 'int'>

In java

int a=10;

a=true;

above code is not valid we will get compile time error saying

incomparable type

in python:

>>> a=10

>>> type(a)

<class 'int'>

>>> a=True

>>> type(a)

<class 'bool'>

Hadoop: symbol: yellow cap elephant<<doug cutting and mike cafarella

Popular fun tv show in BBC

Monty

Python’s

Circus

1969 to 1974
Gudio barrowed all the features from

1.functional programming from c

2.oop from c++

3.scripting languages features from perl and shell script

4.modula programming features from modula-3

Syntax from c and abc

Where we can use python:

1)Desktop application

2)web application(DJango framework,

3)database applications

4)for networking application

5)games

6)data analysis
7)machine learning

8)AI

9)for IOT applications

Which companies
Major companies python

Features of python:

1)simple and easy to learn

Ex1:

>>> a,b=10,20

>>> print(a+b)

30

Ex2:

for i in range(10):

print(i)

x=10 if a>b else 20

2.Free ware and opensource

Ex of opensource:

Python…jython(it is customized version of python)

3.High level programming language(human understanding language)

4.platform independent

5.portability

6.dynamically typed

7.both procedure oriented and object oriented

8.interpreted

9.extensible
10.embedded

11.extensive library

Ex:

import math

print(math.sqrt(4))

output

C:\del>python myfile.py

2.0

To print random numbers

from random import *

print(randint(0,9))

output:

C:\del>python myfile.py

C:\del>python myfile.py

C:\del>python myfile.py

from random import *


print(randint(0,9),randint(0,9))

output:

C:\del>python myfile.py

70

C:\del>python myfile.py

58

To remove the spaces between above two numbers

from random import *

print(randint(0,9),randint(0,9),sep="")

output:

C:\del>python myfile.py

31

C:\del>python myfile.py

25

C:\del>python myfile.py

18

from random import *

for i in range(5):

print(randint(0,9),randint(0,9),sep="")
output:

C:\del>python myfile.py

19

09

13

62

50

Limitations of python:

1.performance (because interpreted)

2.mobile applications

3.Myth:python is not suitable for large scale enterprise Applications.

4.it is not pure oops

Flavors of python:

1)Jython or JPython

2)Cpython

3)Iron Python(C#)

4)Pypy(pvm -----jit)

5)Rubypython

6)AnacondaPython(Bigdata)---(large data processing)

7)stackless(python for concurrency)

Python versions:

Python1.0 introduced jan1994

Python2.0 introduced oct2000

Python3.0 introduced dec 2008


Python 3 not supports python2 all features

print “hello” valid in python2 not in python3

print(“hello”)

long datatype➔ python2 valid not in python3

Identifiers:

1)a-z A-Z 0 to 9 _(underscore)

2)should not start with digit

3)case sensitive

4)reserved letters not allowed

5)no length limit

6) _x➔private

7) _ _x→strongly private

8)_ _name_ _(python specified keyword)

(we can use not recommended)

Reserved words:

33 reserved words

True,False,None

and,or ,not ,is

if,else,elif

while,for,break,continue,return,in,yield

try, except,finally,raise,assert

import,from,as,class,def,pass,global,nonlocal,lambda,del,with

Note:
Only alphabets

Lower case (except first 3)

>>> import keyword

>>> keyword.kwlist

['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue',
'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is',
'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']

Data type:

int

long(only inpython 2.0)

float

complex (10+3j)

bool

str

bytes

bytearray

range

list

tuple

set

frozenset

dict
None

Note:in python everything is object.

Python provides some inbuilt functions:

print()

type()

id()

1.int:

Integral values

1.decimal form

2.binaryform

3.octal form

4.hexa decimal

1.decimal form:
Base-10

0 to 9

A=6754

2.binaryform

Base-2

0and 1

a=1111

a=0b1111 or 0B1111

a=-0b1111 or -0B1111

3.octal form

Base -8

0 to 7

a=0o1111 or 0O1111

4.hexa decimal:

Base-16

0to9,a to f,A to F

0x or 0X

Ex:

a=10

b=0b10

c=0o10
d=0X10

only in decimal

print(a)//10

b//2

c//8

d//16

what is the range for data type?

note :there is no range for data type in python. because everything is an object.

Class Test{

Psvm

{int x=10;//4 bytes

Test t=new Test();//object no limit

Base Conversions:

bin()

oct()

hex()

ex:

bin(10)

>>> a=10

>>> bin(a)

'0b1010'

bin(0o777)

bin(0x1234)
>>> oct(123)

'0o173'

>>> oct(0xFace)

'0o175316'

>>> oct(0xFace)

'0o175316'

>>> hex(10)

'0xa'

>>> hex(11)

'0xb'

floatdata type:

f=123.456

f=0x123.456

f=0o123.456

the allowed only decimals only

>>> f=123.456

>>> f

123.456

>>> f=0x123.456

File "<stdin>", line 1

f=0x123.456

SyntaxError: invalid syntax


Exponential form: is allowed

1.2e3=1.2*1000=1200.0

>>> x=1.2e3

>>> x

1200.0

Complex data type:

a+bj

a=real part

b=imaginary part

j=sqrt(-1)

j*j=-1

note:a,b are can be int or float values

>>> x=10+20j

>>> x

(10+20j)

>>> type(x)

<class 'complex'>

>>> y=10.5+2.3j

>>> y

(10.5+2.3j)

X=10+j20

Above code is not valid

Note:a (real part)can be any values oct,bin,hex

B (imaginary part)must be decimal only


>>> x=10+20

>>> a=10+20j

>>> b=20+30j

>>> a+b

(30+50j)

bool:

True and False

>>> x=True

>>> x

True

>>> x=true

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

NameError: name 'true' is not defined

b=true

above code is not valid

it is not going to take like string datatype

bez we need to put single code.

>>> a='true'

>>> a

'true'
>>> True+True

>>> True+False

>>> False+False

True=1

False=0

str:

>>> x='rajesh' //recommended

>>> x

'rajesh'

>>> x="rajesh"

>>> x

'rajesh'

“jain

university”

multyline sting:

“””jain

University”””

>>> x='''jain
... university'''

>>> x

'jain\nuniversity'

>>> '''jain

... "python" university'''

'jain\n"python" university'

Note:there is no default values in python

Ex:

>>> x

Traceback (most recent call last):

File "<pyshell#0>", line 1, in <module>

NameError: name 'x' is not defined

Slice operator(substring)

‘jain’

>>> s='jain'

>>> s[0]

'j'

>>> s[1]
'a'

>>> s[3]

'n'

>>> s[5]

Traceback (most recent call last):

File "<pyshell#5>", line 1, in <module>

s[5]

IndexError: string index out of range

>>> s='jain'

>>> s[-1]

'n'

>>> s[-3]

'a'

Note:-ve index to provide flexible to developer

Slice syntax:

s[begin:end]

//return substring from begin index to end-1 index


>>> s[1:4]

'ain'

>>> s[0:3]

'jai'

>>> s[0:6]

'jain'

>>> s[1:]

'ain'

>>> s='jain'

>>> s[:3]

'jai'

>>> s[:]

'jain'

>>> s[-1:-3]

''

>>> s[-3:-1]

'ai'

s[begin:end:step]

>>> s='jainuniversity'

>>> s[1:8:2]
'annv'

>>> s='jain'

>>> s*10

'jainjainjainjainjainjainjainjainjainjain'

Python fundamental data types(5):int,float,complex,bool,str

char ----str

long—python2 only

typecasting:or type coercion

int()

float()

complex()

bool()

str()

>>> x=10

>>> type(x)

<class 'int'>

>>> int(x)

10

>>> float(x)

10.0

>>> complex(x)

(10+0j)

>>> bool(x)

True
>>> str(x)

'10'

>>> int(123.435)

123

>>> int(10+20j)

Traceback (most recent call last):

File "<pyshell#10>", line 1, in <module>

int(10+20j)

TypeError: can't convert complex to int

>>> int(True)

>>> int('10.5')

Traceback (most recent call last):

File "<pyshell#12>", line 1, in <module>

int('10.5')

ValueError: invalid literal for int() with base 10: '10.5'


float():

float(10)=10.0

float(10+20j)=Type error

float(True)=1.0

float(False)=0.0

float(‘10’)=10.0

float(“10.5”)=10.5

float(“10”)=10

float(“ten”)=valueerror

complex()

othertype to complex type

Form1:complex(x)===x+0j

Form2:complex(x,y)===x+yj

>>> complex(10)

(10+0j)

>>> complex(10.5)

(10.5+0j)

>>> complex(10,20)

(10+20j)

>>> complex(10,20.5)

(10+20.5j)

>>> complex(True)
(1+0j)

>>> complex(False)

0j

>>> complex('10')

(10+0j)

>>> complex('rajesh')

Traceback (most recent call last):

File "<pyshell#7>", line 1, in <module>

complex('rajesh')

ValueError: complex() arg is a malformed string

>>> complex('10.4')

(10.4+0j)

>>> complex('ob1111')

Traceback (most recent call last):

File "<pyshell#9>", line 1, in <module>

complex('ob1111')

ValueError: complex() arg is a malformed string

>>> complex("10","12")

Traceback (most recent call last):

File "<pyshell#10>", line 1, in <module>

complex("10","12")

TypeError: complex() can't take second arg if first is a string

bool()

>>> bool(0)

False
>>> bool(10)

True

>>> bool(-10)

True

>>> bool(0.0)

False

>>> bool(10.0)

True

>>> bool(10+20j)

True

>>> bool(0+0j) //imag part 0 means false or true

False

>>> bool(0+1j)

True

>>> bool('') //string is empty then false or true

False

>>> bool("raj")

True

>>> bool(' ')

True

>>> str(10)

'10'
>>> str(10.5)

'10.5'

>>> str(True)

'True'

>>> str(10+20j)

'(10+20j)'

Immutable vs fundamental data types

All fundamental data types are immutable

Mutable===changable
Immutable===non changable

X=10

Y=10

Advantage above approach is

No memory wastage
Reusing the object

V1=”bang”

V2=”bang”

V3=”bang”

V10000=”bang”

id(v1)

id(v2)

v3=”mysore”

Note:list is not immutable remaining all immutable

Is

X=10

Y=10

>>>x is y

True

>>>yis x
True

X=True

Y=True

Z=True

Xis y----True

Y is z-----True

Z is x-----True

X=256

Y=256

X is y-

True

X=257

Y=257

X is y

False

Reusing same object range is 0-256 only

Float

X=10.0

Y=10.0

Xis y

False
Note:for float no reusing concept

Is will get either true or false

X=10+20j

Y=10+20j

X is y

False

Note:for complex,floating reusing concept is not there.

Reusing following Range:

Int 0-256

Bool always

Str always

Float not there

Complex not there

At the time python interpreter starts

0-256 integer objects will be created at the beginning.

A=10

B=10

C=10

Float values between 0 to 1

0.1

0.01

0.11

….
Infinity

Complex numbers:10+20j we can use floating values

bytesDatatype:

>>> x=[10,20,30,40]

>>> b=bytes(x)

>>> type(b)

<class 'bytes'>

>>> b[0]

10

>>> b[1]

20

>>> b[-1]

40

>>> b[0:3]

b'\n\x14\x1e'

>>> for x in b:print(x)

10

20

30

40

Note:in the range 0-256

Bytes datatype immutable

>>> x=[10,20,256,258]

>>> b=bytes(x)
Traceback (most recent call last):

File "<pyshell#15>", line 1, in <module>

b=bytes(x)

ValueError: bytes must be in range(0, 256)

>>> x=[10,20,30,40]

>>> b=bytes(x)byteArray:is similar to bytes data type only it is mutable

>>>x=[10,20,30,40]

B=bytearray(x)

>>> b[0]

10

>>> b[0]=120

Traceback (most recent call last):

File "<pyshell#20>", line 1, in <module>

b[0]=120

TypeError: 'bytes' object does not support item assignment

bytes,bytearray-------mostly used for binary data like images,video files

List:insertion order preserved

Duplicates allowed

Hetrogenious allowed

None allowed

Growable

mutable

L=[]
Type(l)

<class ‘list’>

l.append(10)

l.append(20)

l.append(30)

l.append(10)

print(l)------------------------[10,20,30,10]

l.append(“jain”)

l.append(None)

print(l)---------------------------------[10,20,…,None]

>>> s=[10,'jain',True]

>>> s

[10, 'jain', True]

>>> s1=s*2

>>> s1

[10, 'jain', True, 10, 'jain', True]

>>> s2=s*s

Traceback (most recent call last):

File "<pyshell#4>", line 1, in <module>

s2=s*s

TypeError: can't multiply sequence by non-int of type 'list'

insertion order preserved

Duplicates allowed

Hetrogenious allowed
But required mutable

Then we need to go for tuple

>>> l=[10,20,30,40]

>>> type(l)

<class 'list'>

>>> t=(10,20,30,40)

>>> type(t)

<class 'tuple'>

>>> t

(10, 20, 30, 40)

>>> t[0]

10

>>> t[0:3]

(10, 20, 30)

>>> t[0]=100

Traceback (most recent call last):

File "<pyshell#12>", line 1, in <module>

t[0]=100

TypeError: 'tuple' object does not support item assignment

>>> t1=t*2

>>> t1

(10, 20, 30, 40, 10, 20, 30, 40)

>>> t=(10,20,[2,6])

>>> t
(10, 20, [2, 6])

range(): it is method and datatype

range data type represent a sequence of values immutable

form1:

>>> range(10)

range(0, 10)

>>> range(100)

range(0, 100)

>>> r=range(10)

>>> type(r)

<class 'range'>

>>> range(0,10)

range(0, 10)

>>> for i in r:print(i)

9
>>> r[0]

>>> r[4]

>>> r[0:3]

range(0, 3)

>>> r=range(10)

>>> r[0]=777

Traceback (most recent call last):

File "<pyshell#11>", line 1, in <module>

r[0]=777

TypeError: 'range' object does not support item assignment

Form 2: >>> range(100)

range(0, 100)

>>> range(10,30)

range(10, 30)

Form 3:

>>> range(10,50,5)

range(10, 50, 5)

>>> for i in range(10,50,5):print(i)

10

15

20

25
30

35

40

45

>>> range(10.5,20.6)

Traceback (most recent call last):

File "<pyshell#5>", line 1, in <module>

range(10.5,20.6)

TypeError: 'float' object cannot be interpreted as an integer

>>> range(10.5)

Traceback (most recent call last):

File "<pyshell#6>", line 1, in <module>

range(10.5)

TypeError: 'float' object cannot be interpreted as an integer

Set:{}

Duplicates not req

Insertion order not req

No index

Growable

No slice operator

Mutable

No append method

>>> s={10,20,30,10,20,30}

>>> type(s)

<class 'set'>
>>> s

{10, 20, 30}

>>> s[0]

Traceback (most recent call last):

File "<pyshell#3>", line 1, in <module>

s[0]

TypeError: 'set' object does not support indexing

>>> s={10,20,30}

>>> type (s)

<class 'set'>

>>> s.add('jain')

>>> s

{10, 20, 30, 'jain'}

>>> s.remove(20)

>>> s

{10, 30, 'jain'}

Frozenset:

Frozenset is similar to set except immutable

>>> s={10,20,30,40}

>>> fs=frozenset(s)

>>> type(fs)

<class 'frozenset'>

>>> fs

frozenset({40, 10, 20, 30})

>>> fs.add(50)
Traceback (most recent call last):

File "<pyshell#14>", line 1, in <module>

fs.add(50)

AttributeError: 'frozenset' object has no attribute 'add'

Dict:{ }

Key –value pair

Key can’t duplicate

Value can duplicate

Rollnumber-name

Mobilenumber-name

>>> d={100:'raju',200:'ramu',300:'raj'}

>>> type(d)

<class 'dict'>

>>> d

{100: 'raju', 200: 'ramu', 300: 'raj'}

>>> s=set()

>>> type(s)

<class 'set'>

Python Collections :

There are four collection data types in the Python programming language:

• List is a collection which is ordered and changeable. Allows duplicate


members.
• Tuple is a collection which is ordered and unchangeable. Allows duplicate
members.
• Set is a collection which is unordered and unindexed. No duplicate members.
• Dictionary is a collection which is unordered, changeable and indexed. No
duplicate members.
When choosing a collection type, it is useful to understand the properties of that
type. Choosing the right type for a particular data set could mean retention of
meaning, and, it could mean an increase in efficiency or security.

List

A list is a collection which is ordered and changeable. In Python lists are written
with square brackets.

thislist = ["apple", "banana", "cherry"]

print(thislist)

output:

C:\del>python myfile.py

['apple', 'banana', 'cherry']

thislist = ["apple", "banana", "cherry"]

print(thislist[1])

output:

C:\del>python myfile.py

Banana

thislist = ["apple", "banana", "cherry"]

thislist[1] = "blackcurrant"

print(thislist)

output:
C:\del>python myfile.py

['apple', 'blackcurrant', 'cherry']

thislist = ["apple", "banana", "cherry"]

thislist[3] = "blackcurrant"

print(thislist)

output:
error:

C:\del>python myfile.py

Traceback (most recent call last):

File "myfile.py", line 2, in <module>

thislist[3] = "blackcurrant"

IndexError: list assignment index out of range

thislist = ["apple", "banana", "cherry"]

for x in thislist:

print(x)

output:

C:\del>python myfile.py

apple

banana

cherry

Check if Item Exists


thislist = ["apple", "banana", "cherry"]

if "apple" in thislist:

print("Yes, 'apple' is in the fruits list")

output:

C:\del>python myfile.py

Yes, 'apple' is in the fruits list

List Length
thislist = ["apple", "banana", "cherry"]
print(len(thislist))

output:

Add Items

To add an item to the end of the list, use the append() method:

thislist = ["apple", "banana", "cherry"]

thislist.append("orange")

print(thislist)

To add an item at the specified index, use the insert() method:

thislist = ["apple", "banana", "cherry"]

thislist.insert(1, "orange")

print(thislist)

Remove Item

There are several methods to remove items from a list:

thislist = ["apple", "banana", "cherry"]

thislist.remove("banana")

print(thislist)

Example

The pop() method removes the specified index, (or the last item if index is not
specified):

thislist = ["apple", "banana", "cherry"]

thislist.pop()

print(thislist)

output:
C:\del>python myfile.py
['apple', 'banana']

Example

The del keyword removes the specified index:

thislist = ["apple", "banana", "cherry"]

del thislist[0]

print(thislist)

output:
C:\del>python myfile.py

['banana', 'cherry']

thislist = ["apple", "banana", "cherry"]

del thislist

print(thislist)

output:

C:\del>python myfile.py

Traceback (most recent call last):

File "myfile.py", line 3, in <module>

print(thislist) #this will cause an error because "thislist" no long

s.

NameError: name 'thislist' is not defined

Example

The clear() method empties the list:

thislist = ["apple", "banana", "cherry"]

thislist.clear()

print(thislist)

The list() Constructor


It is also possible to use the list() constructor to make a list.

thislist = list(("apple", "banana", "cherry"))

print(thislist)

Tuple

A tuple is a collection which is ordered and unchangeable. In Python tuples are


written with round brackets.

thistuple = ("apple", "banana", "cherry")

print(thistuple)

C:\del>python myfile.py

('apple', 'banana', 'cherry')

Access Tuple Items

You can access tuple items by referring to the index number, inside square
brackets:

thistuple = ("apple", "banana", "cherry")

print(thistuple[1])

output:

banana

Change Tuple Values

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

thistuple = ("apple", "banana", "cherry")

thistuple[1] = "blackcurrant"

# The values will remain the same:

print(thistuple)

output:

C:\del>python myfile.py
Traceback (most recent call last):

File "myfile.py", line 2, in <module>

thistuple[1] = "blackcurrant"

TypeError: 'tuple' object does not support item assignment

Loop Through a Tuple

You can loop through the tuple items by using a for loop.

thistuple = ("apple", "banana", "cherry")


for x in thistuple:
print(x)

thistuple = ("apple", "banana", "cherry")


if "apple" in thistuple:
print("Yes, 'apple' is in the fruits tuple")

thistuple = ("apple", "banana", "cherry")


print(len(thistuple))

thistuple = ("apple", "banana", "cherry")


thistuple[3] = "orange" # This will raise an error
print(thistuple)

thistuple = ("apple", "banana", "cherry")


del thistuple
print(thistuple) #this will raise an error because the tuple no longer exists

Set

A set is a collection which is unordered and unindexed. In Python sets are written
with curly brackets.

thisset = {"apple", "banana", "cherry"}

print(thisset)

output:

C:\del>python myfile.py

{'banana', 'cherry', 'apple'}


C:\del>python myfile.py

{'apple', 'banana', 'cherry'}

C:\del>python myfile.py

{'banana', 'cherry', 'apple'}

Note: Sets are unordered, so the items will appear in a random order.

Access Items:( for access items you will get unordered)


thisset = {"apple", "banana", "cherry"}

for x in thisset:

print(x)

output:

C:\del>python myfile.py

apple

cherry

banana

C:\del>python myfile.py

cherry

banana

apple

C:\del>python myfile.py

banana

cherry

apple

thisset = {"apple", "banana", "cherry"}


print("banana" in thisset)

output:

C:\del>python myfile.py

True

Change Items

Once a set is created, you cannot change its items, but you can add new items.

Add Items

To add one item to a set use the add() method.

To add more than one item to a set use the update() method.

thisset = {"apple", "banana", "cherry"}

thisset.add("orange")

print(thisset)

output:

C:\del>python myfile.py

{'apple', 'orange', 'banana', 'cherry'}

thisset = {"apple", "banana", "cherry"}

thisset.update(["orange", "mango", "grapes"])

print(thisset)

output:

C:\del>python myfile.py
{'mango', 'grapes', 'cherry', 'orange', 'apple', 'banana'}

thisset = {"apple", "banana", "cherry"}

print(len(thisset))

output:

Remove Item

To remove an item in a set, use the remove(), or the discard() method.

thisset = {"apple", "banana", "cherry"}

thisset.remove("banana")

print(thisset)

output:

C:\del>python myfile.py

{'apple', 'cherry'}

Note: If the item to remove does not exist, remove() will raise an error.

thisset = {"apple", "banana", "cherry"}

thisset.discard("banana1")

print(thisset)

Note: If the item to remove does not exist, discard() will NOT raise an error.
You can also use the pop(), method to remove an item, but this method will
remove the last item. Remember that sets are unordered, so you will not know
what item that gets removed.

thisset = {"apple", "banana", "cherry"}

x = thisset.pop()

print(x)

print(thisset)

output:

C:\del>python myfile.py

apple

{'banana', 'cherry'}

Note: Sets are unordered, so when using the pop() method, you will not know
which item that gets removed.

thisset = {"apple", "banana", "cherry"}

thisset.clear()

print(thisset)

output:

C:\del>python myfile.py

set()
The del keyword will delete the set completely:

thisset = {"apple", "banana", "cherry"}

del thisset

print(thisset)

The set() Constructor

It is also possible to use the set() constructor to make a set.

thisset = set(("apple", "banana", "cherry")) # note the double round-brackets

print(thisset)

Dictionary

A dictionary is a collection which is unordered, changeable and indexed. In Python


dictionaries are written with curly brackets, and they have keys and values.

thisdict = {

"brand": "Ford",

"model": "Mustang",

"year": 1964

print(thisdict)

output:

C:\del>python myfile.py

{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}

thisdict = {

"brand": "Ford",

"model": "Mustang",
"year": 1964

x = thisdict["model"]

print(x)

output:

C:\del>python myfile.py

Mustang

thisdict = {

"brand": "Ford",

"model": "Mustang",

"year": 1964

x = thisdict.get("model")

print(x)

Change Values

You can change the value of a specific item by referring to its key name:

thisdict = {

"brand": "Ford",

"model": "Mustang",

"year": 1964

thisdict["year"] = 2018

print(thisdict)
C:\del>python myfile.py

{'brand': 'Ford', 'model': 'Mustang', 'year': 2018}

thisdict = {

"brand": "Ford",

"model": "Mustang",

"year": 1964

for x in thisdict:

print(x)

output:

C:\del>python myfile.py

brand

model

year

thisdict = {

"brand": "Ford",

"model": "Mustang",

"year": 1964

for x in thisdict:

print(thisdict[x])

output:

C:\del>python myfile.py

Ford
Mustang

1964

You can also use the values() function to return values of a dictionary:

thisdict = {

"brand": "Ford",

"model": "Mustang",

"year": 1964

for x in thisdict.values():

print(x)

outuput:

C:\del>python myfile.py

Ford

Mustang

1964

Loop through both keys and values, by using the items() function:

thisdict = {

"brand": "Ford",

"model": "Mustang",

"year": 1964

for x, y in thisdict.items():

print(x, y)
output:

C:\del>python myfile.py

brand Ford

model Mustang

year 1964

Check if Key Exists

To determine if a specified key is present in a dictionary use the in keyword:

thisdict = {

"brand": "Ford",

"model": "Mustang",

"year": 1964

if "model" in thisdict:

print("Yes, 'model' is one of the keys in the thisdict dictionary")

output:

C:\del>python myfile.py

Yes, 'model' is one of the keys in the thisdict dictionary

Dictionary Length

To determine how many items (key-value pairs) a dictionary have, use


the len() method.

thisdict = {

"brand": "Ford",

"model": "Mustang",

"year": 1964
}

print(len(thisdict))

output:

Adding Items

Adding an item to the dictionary is done by using a new index key and assigning a
value to it:

thisdict = {

"brand": "Ford",

"model": "Mustang",

"year": 1964

thisdict["color"] = "red"

print(thisdict)

output:

C:\del>python myfile.py

{'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color': 'red'}

Removing Items

There are several methods to remove items from a dictionary:

thisdict = {

"brand": "Ford",

"model": "Mustang",
"year": 1964

thisdict.pop("model")

print(thisdict)

output:

C:\del>python myfile.py

{'brand': 'Ford', 'year': 1964}

The popitem() method removes the last inserted item (in versions before 3.7, a
random item is removed instead):

thisdict = {

"brand": "Ford",

"model": "Mustang",

"year": 1964

thisdict.popitem()

print(thisdict)

outuput:

C:\del>python myfile.py

{'brand': 'Ford', 'model': 'Mustang'}

The del keyword removes the item with the specified key name:

thisdict = {

"brand": "Ford",

"model": "Mustang",

"year": 1964

del thisdict["model"]
print(thisdict)

outuput:

C:\del>python myfile.py

{'brand': 'Ford', 'year': 1964}

The del keyword can also delete the dictionary completely:

thisdict = {

"brand": "Ford",

"model": "Mustang",

"year": 1964

del thisdict

print(thisdict) #this will cause an error because "thislist" no longer exists.

Output:

C:\del>python myfile.py

Traceback (most recent call last):

File "myfile.py", line 7, in <module>

print(thisdict) #this will cause an error because "thislist" no longer exist

s.

NameError: name 'thisdict' is not defined

The clear() keyword empties the dictionary:

thisdict = {

"brand": "Ford",

"model": "Mustang",

"year": 1964

}
thisdict.clear()

print(thisdict)

outuput:

C:\del>python myfile.py

{}

The dict() Constructor

It is also possible to use the dict() constructor to make a dictionary:

thisdict = dict(brand="Ford", model="Mustang", year=1964)

# note that keywords are not string literals

# note the use of equals rather than colon for the assignment

print(thisdict)

outuput:

C:\del>python myfile.py

{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}

Python If ... Else

a = 33

b = 200

if b > a:

print("b is greater than a")

outuput:

C:\del>python myfile.py

b is greater than a

Elif
a = 33
b = 33

if b > a:

print("b is greater than a")

elif a == b:

print("a and b are equal")

Else
a = 200

b = 33

if b > a:

print("b is greater than a")

elif a == b:

print("a and b are equal")

else:

print("a is greater than b")

output:

C:\del>python myfile.py

a is greater than b

a = 200

b = 33

if b > a:

print("b is greater than a")

else:

print("b is not greater than a")

output:

C:\del>python myfile.py
b is not greater than a

Short Hand If

If you have only one statement to execute, you can put it on the same line as the if
statement.

a = 200

b = 33

if a > b: print("a is greater than b")

C:\del>python myfile.py

a is greater than b

Python If ... Else

a = 33

b = 200

if b > a:

print("b is greater than a")

outuput:

C:\del>python myfile.py

b is greater than a

Elif
a = 33

b = 33

if b > a:

print("b is greater than a")

elif a == b:

print("a and b are equal")


Else
a = 200

b = 33

if b > a:

print("b is greater than a")

elif a == b:

print("a and b are equal")

else:

print("a is greater than b")

output:

C:\del>python myfile.py

a is greater than b

a = 200

b = 33

if b > a:

print("b is greater than a")

else:

print("b is not greater than a")

output:

C:\del>python myfile.py

b is not greater than a

Short Hand If

If you have only one statement to execute, you can put it on the same line as the if
statement.

a = 200

b = 33
if a > b: print("a is greater than b")

C:\del>python myfile.py

a is greater than b

ex2:

a = 330

b = 330

print("A") if a > b else print("=") if a == b else print("B")

output:

C:\del>python myfile.py

Python Loops

Python has two primitive loop commands:

• while loops
• for loops

The while Loop

With the while loop we can execute a set of statements as long as a condition is
true.

i=1

while i < 6:

print(i)

i += 1

output:

C:\del>python myfile.py
1

Note: remember to increment i, or else the loop will continue forever.

The break Statement

With the break statement we can stop the loop even if the while condition is true:

i=1

while i < 6:

print(i)

if (i == 3):

break

i += 1

output:

C:\del>python myfile.py

The continue Statement

With the continue statement we can stop the current iteration, and continue with
the next:

i=0

while i < 6:

i += 1
if i == 3:

continue

print(i)

output:

C:\del>python myfile.py

A for loop is used for iterating over a sequence (that is either a list, a tuple, a
dictionary, a set, or a string).

This is less like the for keyword in other programming language, and works more
like an iterator method as found in other object-orientated programming languages.

With the for loop we can execute a set of statements, once for each item in a list,
tuple, set etc.

fruits = ["apple", "banana", "cherry"]

for x in fruits:

print(x)

output:

C:\del>python myfile.py

apple

banana

cherry

The break Statement

With the break statement we can stop the loop before it has looped through all the
items:
fruits = ["apple", "banana", "cherry"]

for x in fruits:

print(x)

if x == "banana":

break

outuput:

C:\del>python myfile.py

apple

banana

Example

Exit the loop when x is "banana", but this time the break comes before the print:

fruits = ["apple", "banana", "cherry"]

for x in fruits:

if x == "banana":

break

print(x)

output:

C:\del>python myfile.py

Apple

The continue Statement

With the continue statement we can stop the current iteration of the loop, and
continue with the next:
fruits = ["apple", "banana", "cherry"]

for x in fruits:

if x == "banana":

continue

print(x)

output:

C:\del>python myfile.py

apple

cherry

The range() Function


To loop through a set of code a specified number of times, we can use
the range() function,

The range() function returns a sequence of numbers, starting from 0 by default,


and increments by 1 (by default), and ends at a specified number.

for x in range(6):

print(x)

output:

C:\del>python myfile.py

Note that range(6) is not the values of 0 to 6, but the values 0 to 5.


The range() function defaults to 0 as a starting value, however it is possible to
specify the starting value by adding a parameter: range(2, 6), which means values
from 2 to 6 (but not including 6):

for x in range(2, 6):

print(x)

C:\del>python myfile.py

The range() function defaults to increment the sequence by 1, however it is


possible to specify the increment value by adding a third parameter: range(2,
30, 3):

for x in range(2, 30, 3):

print(x)

output:

C:\del>python myfile.py

11

14

17

20
23

26

29

Else in For Loop

The else keyword in a for loop specifies a block of code to be executed when the
loop is finished:

for x in range(6):

print(x)

else:

print("Finally finished!")

outuput:

C:\del>python myfile.py

Finally finished!

Nested Loops

A nested loop is a loop inside a loop.

The "inner loop" will be executed one time for each iteration of the "outer loop":

adj = ["red", "big", "tasty"]

fruits = ["apple", "banana", "cherry"]


for x in adj:

for y in fruits:

print(x, y)

output:

C:\del>python myfile.py

red apple

red banana

red cherry

big apple

big banana

big cherry

tasty apple

tasty banana

tasty cherry

A function is a block of code which only runs when it is called.

You can pass data, known as parameters, into a function.

A function can return data as a result.

Creating a Function

In Python a function is defined using the def keyword:

def my_function():

print("Hello from a function")

output:

no output
Calling a Function

To call a function, use the function name followed by parenthesis:

def my_function():

print("Hello from a function")

my_function()

output:

C:\del>python myfile.py

Hello from a function

Parameters

Information can be passed to functions as parameter.

Parameters are specified after the function name, inside the parentheses. You can
add as many parameters as you want, just separate them with a comma.

The following example has a function with one parameter (fname). When the
function is called, we pass along a first name, which is used inside the function to
print the full name:

def my_function(fname):

print(fname + " Refsnes")

my_function("Emil")

my_function("Tobias")

my_function("Linus")

output;

C:\del>python myfile.py
Emil Refsnes

Tobias Refsnes

Linus Refsnes

Default Parameter Value

The following example shows how to use a default parameter value.

If we call the function without parameter, it uses the default value:

def my_function(country = "Norway"):

print("I am from " + country)

my_function("Sweden")

my_function("India")

my_function()

my_function("Brazil")

output:

C:\del>python myfile.py

I am from Sweden

I am from India

I am from Norway

I am from Brazil

Return Values

To let a function return a value, use the return statement:

def my_function(x):

return 5 * x

print(my_function(3))
print(my_function(5))

print(my_function(9))

output:

C:\del>python myfile.py

15

25

45

def hi():

print("hi")

hi()

output:

C:\del>python myfile.py

hi

Parameters in function

#defining the function

def displayname (name):

print("Hi ",name);

#calling the function

displayname("rajesh")

output:

C:\del>python myfile.py

Hi rajesh
#defining the function

def add (a,b):

return a+b;

#giving values from the user

a = int(input("Enter a: "))

b = int(input("Enter b: "))

#printing the sum of a and b

print("Sum = ",add(a,b))

output:

C:\del>python myfile.py

Enter a: 20

Enter b: 30

Sum = 50

#the function simple_interest accepts three arguments and returns the simple inter
est accordingly

def simple_interest(p,t,r):

return (p*t*r)/100

p = float(input("Enter the principle amount? "))

r = float(input("Enter the rate of interest? "))

t = float(input("Enter the time in years? "))

print("Simple Interest: ",simple_interest(p,r,t))

output:

C:\del>python myfile.py

Enter the principle amount? 1000


Enter the rate of interest? 2

Enter the time in years? 1

Simple Interest: 20.0

A lambda function is a small anonymous function.

A lambda function can take any number of arguments, but can only have one
expression.

Syntax
lambda arguments : expression

The expression is executed and the result is returned:

x = lambda a: a + 10

print(x(5))

output:

C:\del>python myfile.py

15

Lambda functions can take any number of arguments:

x = lambda a, b: a * b

print(x(5, 6))

outuput:

C:\del>python myfile.py

30

Example

A lambda function that sums argument a, b, and c and print the result:

x = lambda a, b, c: a + b + c

print(x(5, 6, 2))
C:\del>python myfile.py

13

Why Use Lambda Functions?

The power of lambda is better shown when you use them as an anonymous
function inside another function.

Say you have a function definition that takes one argument, and that argument will
be multiplied with an unknown number:

def myfunc(n):
return lambda a : a * n

Use that function definition to make a function that always doubles the number you
send in:

def myfunc(n):

return lambda a : a * n

mydoubler = myfunc(2)

print(mydoubler(11))

outuput:

C:\del>python myfile.py

22

Or, use the same function definition to make a function that always triples the
number you send in:

def myfunc(n):

return lambda a : a * n
mytripler = myfunc(3)

print(mytripler(11))

output:

C:\del>python myfile.py

33

Or, use the same function definition to make both functions, in the same program:

def myfunc(n):

return lambda a : a * n

mydoubler = myfunc(2)

mytripler = myfunc(3)

print(mydoubler(11))

print(mytripler(11))

output:

C:\del>python myfile.py

22

33

Use lambda functions when an anonymous function is required for a short period of
time.

Arrays
Syntax:

from array import *

arrayName = array(typecode, [Initializers])

Typecode Value

b Represents signed integer of size 1 byte/td>

B Represents unsigned integer of size 1 byte

c Represents character of size 1 byte

i Represents signed integer of size 2 bytes

I Represents unsigned integer of size 2 bytes

f Represents floating point of size 4 bytes

d Represents floating point of size 8 bytes

Write a Python program to create an array of 5 integers and display the array
items. Access individual element through indexes

from array import *

array_num = array('i', [10,20,30,40,50])

for i in array_num:

print(i)

print("Access first three items individually")


print(array_num[0])

print(array_num[1])

print(array_num[2])

C:\del>python exx.py

10

20

30

40

50

Access first three items individually

10

20

30

2 Write a Python program to append a new item to the end of the array.

from array import *

array_num = array('i', [10, 20, 30, 40, 50])

print("Original array: "+str(array_num))

print("Append 60 at the end of the array:")

array_num.append(60)

print("New array: "+str(array_num))

C:\del>python exx.py

Original array: array('i', [10, 20, 30, 40, 50])

Append 60 at the end of the array:

New array: array('i', [10, 20, 30, 40, 50, 60])


Pro3 Write a Python program to reverse the order of the items in the array

from array import *

array_num = array('i', [10, 20, 30, 40, 50, 60, 70, 80])

print("Original array: "+str(array_num))

array_num.reverse()

print("Reverse the order of the items:")

print(str(array_num))

C:\del>python exx.py

Original array: array('i', [10, 20, 30, 40, 50, 60, 70, 80])

Reverse the order of the items:

array('i', [80, 70, 60, 50, 40, 30, 20, 10])

pro4:Write a Python program to get the length in bytes of one array item in the
internal representation.

from array import *

array_num = array('i', [10, 20, 30, 40, 50])

print("Original array: "+str(array_num))

print("Length in bytes of one array item: "+str(array_num.itemsize))

C:\del>python exx.py

Original array: array('i', [10, 20, 30, 40, 50])

Length in bytes of one array item: 4

Pro5:Write a Python program to get the current memory address and the length in
elements of the buffer used to hold an array’s contents and also find the size of the
memory buffer in bytes.

from array import *

array_num = array('i', [10, 20, 30, 40, 50])


print("Original array: "+str(array_num))

print("Current memory address and the length in elements of the buffer:


"+str(array_num.buffer_info()))

print("The size of the memory buffer in bytes: "+str(array_num.buffer_info()[1] *


array_num.itemsize))

C:\del>python exx.py

Original array: array('i', [10, 20, 30, 40, 50])

Current memory address and the length in elements of the buffer: (3453384, 5)

The size of the memory buffer in bytes: 20

Pro6:Write a Python program to get the number of occurrences of a specified


element in an array.

from array import *

array_num = array('i', [10, 30, 30, 40, 30, 60, 30])

print("Original array: "+str(array_num))

print("Number of occurrences of the number 3 in the said array:


"+str(array_num.count(30)))

C:\del>python exx.py

Original array: array('i', [10, 30, 30, 40, 30, 60, 30])

Number of occurrences of the number 3 in the said array: 4

Pro7: Write a Python program to append items from inerrable to the end of the
array.

from array import *

array_num = array('i', [10, 20, 30, 40, 50])

print("Original array: "+str(array_num))

array_num.extend(array_num)
print("Extended array: "+str(array_num))

C:\del>python exx.py

Original array: array('i', [10, 20, 30, 40, 50])

Extended array: array('i', [10, 20, 30, 40, 50, 10, 20, 30, 40, 50])

Pro8: Write a Python program to insert a new item before the second element in an
existing array.

from array import *

array_num = array('i', [10, 20, 30, 40, 50])

print("Original array: "+str(array_num))

print("Insert new value 45 before 3:")

array_num.insert(1, 45)

print("New array: "+str(array_num))

C:\del>python exx.py

Original array: array('i', [10, 20, 30, 40, 50])

Insert new value 45 before 3:

New array: array('i', [10, 45, 20, 30, 40, 50])

Pro9:delete the element using array

from array import *

array1 = array('i', [10,20,30,40,50])

array1.remove(40)
for x in array1:

print(x)

C:\del>python exx.py

10

20

30

50

Pro10:search index in array

from array import *

array1 = array('i', [10,20,30,40,50])

print (array1.index(40))

C:\del>python exx.py

Pro11:update array

from array import *

array1 = array('i', [10,20,30,40,50])

array1[2] = 80
for x in array1:

print(x)

output:

C:\del>python exx.py

10

20

80

40

50

2D Array

Matrix addition

X = [[12,7,3],

[4 ,5,6],

[7 ,8,9]]

Y = [[5,8,1],

[6,7,3],

[4,5,9]]

result = [[0,0,0],

[0,0,0],

[0,0,0]]
# iterate through rows

for i in range(len(X)):

# iterate through columns

for j in range(len(X[0])):

result[i][j] = X[i][j] + Y[i][j]

for r in result:

print(r)

C:\del>python exx.py

[17, 15, 4]

[10, 12, 9]

[11, 13, 18]

Matrix multiplication

# Program to multiply two matrices using nested loops

# 3x3 matrix

X = [[12,7,3],

[4 ,5,6],

[7 ,8,9]]

# 3x4 matrix

Y = [[5,8,1,2],

[6,7,3,0],

[4,5,9,1]]

# result is 3x4
result = [[0,0,0,0],

[0,0,0,0],

[0,0,0,0]]

# iterate through rows of X

for i in range(len(X)):

# iterate through columns of Y

for j in range(len(Y[0])):

# iterate through rows of Y

for k in range(len(Y)):

result[i][j] += X[i][k] * Y[k][j]

for r in result:

print(r)

C:\del>python exx.py

[114, 160, 60, 27]

[74, 97, 73, 14]

[119, 157, 112, 23]

Transpose matrix

# Program to transpose a matrix using nested loop

X = [[12,7],

[4 ,5],

[3 ,8]]
result = [[0,0,0],

[0,0,0]]

# iterate through rows

for i in range(len(X)):

# iterate through columns

for j in range(len(X[0])):

result[j][i] = X[i][j]

for r in result:

print(r)

C:\del>python exx.py

[12, 4, 3]

[7, 5, 8]

NumPy Array

NumPy is a package for scientific computing which has support for a powerful N-
dimensional array object. Before you can use NumPy, you need to install it

Installing via pip


Most major projects upload official packages to the Python Package index. They can
be installed on most operating systems using Python’s standard pip package
manager.
Note that you need to have Python and pip already installed on your system.
You can install packages via commands such as:
python -m pip install --user numpy scipy matplotlib ipython jupyter pandas sympy
nose
We recommend using an user install, using the --user flag to pip (note: do not
use sudo pip , which can cause problems). This installs packages for your local user,
and does not write to the system directories.

1. Array of integers, floats and complex Numbers

import numpy as np

A = np.array([[1, 2, 3], [3, 4, 5]])

print(A)

A = np.array([[1.1, 2, 3], [3, 4, 5]]) # Array of floats

print(A)
A = np.array([[1, 2, 3], [3, 4, 5]], dtype = complex) # Array of complex
numbers

print(A)

2. Array of zeros and ones

import numpy as np

zeors_array = np.zeros( (2, 3) )

print(zeors_array)

C:\del>python exx.py

[[0. 0. 0.]

[0. 0. 0.]]

import numpy as np
ones_array = np.ones( (1, 5), dtype=np.int32 )

print(ones_array)

C:\del>python exx.py

[[1 1 1 1 1]]

3. Using arange() and shape()

import numpy as np

A = np.arange(4)

print('A =', A)

B = np.arange(12).reshape(2, 6)

print('B =', B)

C:\del>python exx.py

A = [0 1 2 3]

B = [[ 0 1 2 3 4 5]

[ 6 7 8 9 10 11]]

Addition of Two Matrices

import numpy as np

A = np.array([[2, 4], [5, -6]])


B = np.array([[9, -3], [3, 6]])

C=A+B

print(C)

C:\del>python exx.py

[[11 1]

[ 8 0]]

Multiplication of Two Matrices

import numpy as np

A = np.array([[3, 6, 7], [5, -3, 0]])

B = np.array([[1, 1], [2, 1], [3, -3]])

C = A.dot(B)

print(C)

C:\del>python exx.py

[[ 36 -12]

[ -1 2]]

Transpose of a Matrix

import numpy as np

A = np.array([[1, 1], [2, 1], [3, -3]])

print(A.transpose())

C:\del>python exx.py

[[ 1 2 3]
[ 1 1 -3]]

Access matrix elements, rows and columns


import numpy as np

A = np.array([2, 4, 6, 8, 10])

print("A[0] =", A[0]) # First element

print("A[2] =", A[2]) # Third element

print("A[-1] =", A[-1]) # Last element

C:\del>python exx.py

A[0] = 2

A[2] = 6

A[-1] = 10

Python Classes/Objects

Python is an object oriented programming language.

Almost everything in Python is an object, with its properties and methods.

A Class is like an object constructor, or a "blueprint" for creating objects.

Create a Class

To create a class, use the keyword class:

class MyClass:

x=5

print(MyClass)

output:

C:\del>python myfile.py
<class '__main__.MyClass'>

Create Object

Now we can use the class named myClass to create objects:

class MyClass:

x=5

p1 = MyClass()

print(p1.x)

output:

C:\del>python myfile.py

5
Pdbc(python database connectivity )

1)temporary data

2)permanent data

temporary data:

for i in range(10)

name

marks

d[name]=marks

above data going to store in directory it is temporary in pvm

permanent data:

1)file system:

(excel best suits for very less amount of data)

Limitations:

• No huge data
• No ql support
• No Security
• No Duplicate data prevention
• Data consistency problem

2)database:

• Huge data
• Query lang support
• Security is more
• Tables prevents duplication

Limitations:

• Very huge data(only allows 4 gb data)


• It is only for structured data it will not take un structured data and
semi structured.like images,videos ,xml files

3)cloud…etc:

Advance storage technology

To connect pdbc we need to install softwares

Ex:

Oracle cx_Oracle

Sqlserver pymssql

Mysql pymysql

Standard steps of pdbc:

1)import that database specific modules

import cx_Oracle

import pymysql

2)establish connection

con=cx_Oracle.connect(database information)

con=cx_Oracle.connect('system/oracle@orcl')
3)cursor object

cursor=con.cursor()

4)exec sql query

cursor.execute(sqlquery )

cursor.executescript(sqlqueries )

cursor.executemany()----------------------------to execute a parameterized


query

5)fetch the result

Cursor.fetchone()---------------------to fetch only one row

Cursor.fetchall()---------------to fetch all rows

Cursor.fetchmany(n)--------------------to fetch n rows

6)commit()---------------------to save

rollback()------------------------undo

7)cursor.close()

Con.close()
Program1:to connect with database and print its version

import cx_Oracle

con=cx_Oracle.connect('system/oracle@orcl')

if con!=None:

print('connect established succful')

print('version',con.version)

else:

print('conn not established')

con.close()
Program 2: To create employees table in the database

Query:create table employees(eno number,ename varchar2(10),esal


number(10,2),eaddr varchar2(10))

------------
import cx_Oracle

try:

query="create table employees(eno number,ename varchar2(10))"

con=cx_Oracle.connect('system/oracle@orcl')

cursor=con.cursor()

cursor.execute(query)

print('table created succesfully');

except cx_Oracle.DatabaseError as e:

if con:

con.rollback()

print('there is a problem',e)

finally:

if cursor:

cursor.close()

if con:

con.close()

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

program3:write a program to drop the table

drop table employee


import cx_Oracle

try:

query="drop table employees"

con=cx_Oracle.connect('system/oracle@orcl')

cursor=con.cursor()

cursor.execute(query)

print('table droped succesfully');

except cx_Oracle.DatabaseError as e:

if con:

con.rollback()

print('there is a problem',e)

finally:

if cursor:

cursor.close()

if con:

con.close()
program 4:insert a row into table

import cx_Oracle

try:

query="insert into employees1 values(1,'abc')"

con=cx_Oracle.connect('system/oracle@orcl')

cursor=con.cursor()

cursor.execute(query)

con.commit()

print('table inserted succesfully');

except cx_Oracle.DatabaseError as e:

if con:

con.rollback()

print('there is a problem',e)

finally:
if cursor:

cursor.close()

if con:

con.close()

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

-----------

import cx_Oracle

try:

query="create table emp(eno number,ename varchar2(10),esal


number(10,2),eaddr varchar2(10))"

con=cx_Oracle.connect('system/oracle@orcl')

cursor=con.cursor()

cursor.execute(query)

print('table created succesfully');

except cx_Oracle.DatabaseError as e:

if con:

con.rollback()

print('there is a problem',e)

finally:

if cursor:

cursor.close()

if con:

con.close()

You might also like