Python Basics for Beginners
Python Basics for Beginners
[Link]
python 2 vs python 3
>>> print("hi")
hi
>>> print("jain")
jain
>>> 100+200
300
>>>
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 [Link]
enter number3
enter number4
12
-1
0.75
C:\del>python [Link]
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, [Link]) [MSC v.1915 32 bit
(Intel)] on win32
welcome to python
>>> print("stravan")
stravan
>>>
>>> 100+200
300
>>> 100<200
True
Introduction to python
Why is python
C:\Users\srikanth>CD\
C:\>javac -version
javac 11.0.2
C:\>java -version
C:\>jshell
jshell> [Link]("hi");
hi
a ==> 20
b ==> 20
c ==> 0
jshell> [Link](a+b);
40
>>> 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'>
Monty
Python’s
Circus
1969 to 1974
Gudio barrowed all the features from
1)Desktop application
3)database applications
5)games
6)data analysis
7)machine learning
8)AI
Which companies
Major companies python
Features of python:
Ex1:
>>> a,b=10,20
>>> print(a+b)
30
Ex2:
for i in range(10):
print(i)
Ex of opensource:
[Link] independent
[Link]
[Link] typed
[Link]
[Link]
[Link]
[Link] library
Ex:
import math
print([Link](4))
output
C:\del>python [Link]
2.0
print(randint(0,9))
output:
C:\del>python [Link]
C:\del>python [Link]
C:\del>python [Link]
output:
C:\del>python [Link]
70
C:\del>python [Link]
58
print(randint(0,9),randint(0,9),sep="")
output:
C:\del>python [Link]
31
C:\del>python [Link]
25
C:\del>python [Link]
18
for i in range(5):
print(randint(0,9),randint(0,9),sep="")
output:
C:\del>python [Link]
19
09
13
62
50
Limitations of python:
[Link] applications
Flavors of python:
1)Jython or JPython
2)Cpython
3)Iron Python(C#)
4)Pypy(pvm -----jit)
5)Rubypython
Python versions:
print(“hello”)
Identifiers:
3)case sensitive
6) _x➔private
7) _ _x→strongly private
Reserved words:
33 reserved words
True,False,None
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
>>> [Link]
['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
float
complex (10+3j)
bool
str
bytes
bytearray
range
list
tuple
set
frozenset
dict
None
print()
type()
id()
[Link]:
Integral values
[Link] form
[Link]
[Link] form
[Link] decimal
[Link] form:
Base-10
0 to 9
A=6754
[Link]
Base-2
0and 1
a=1111
a=0b1111 or 0B1111
a=-0b1111 or -0B1111
[Link] form
Base -8
0 to 7
a=0o1111 or 0O1111
[Link] 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
note :there is no range for data type in python. because everything is an object.
Class Test{
Psvm
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
>>> f=123.456
>>> f
123.456
>>> f=0x123.456
f=0x123.456
1.2e3=1.2*1000=1200.0
>>> x=1.2e3
>>> x
1200.0
a+bj
a=real part
b=imaginary part
j=sqrt(-1)
j*j=-1
>>> x=10+20j
>>> x
(10+20j)
>>> type(x)
<class 'complex'>
>>> y=10.5+2.3j
>>> y
(10.5+2.3j)
X=10+j20
>>> a=10+20j
>>> b=20+30j
>>> a+b
(30+50j)
bool:
>>> x=True
>>> x
True
>>> x=true
b=true
>>> a='true'
>>> a
'true'
>>> True+True
>>> True+False
>>> False+False
True=1
False=0
str:
>>> x
'rajesh'
>>> x="rajesh"
>>> x
'rajesh'
“jain
university”
multyline sting:
“””jain
University”””
>>> x='''jain
... university'''
>>> x
'jain\nuniversity'
>>> '''jain
'jain\n"python" university'
Ex:
>>> x
Slice operator(substring)
‘jain’
>>> s='jain'
>>> s[0]
'j'
>>> s[1]
'a'
>>> s[3]
'n'
>>> s[5]
s[5]
>>> s='jain'
>>> s[-1]
'n'
>>> s[-3]
'a'
Slice syntax:
s[begin:end]
'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[Link]
'annv'
>>> s='jain'
>>> s*10
'jainjainjainjainjainjainjainjainjainjain'
char ----str
long—python2 only
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)
int(10+20j)
>>> int(True)
>>> int('10.5')
int('10.5')
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()
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')
complex('rajesh')
>>> complex('10.4')
(10.4+0j)
>>> complex('ob1111')
complex('ob1111')
>>> complex("10","12")
complex("10","12")
bool()
>>> bool(0)
False
>>> bool(10)
True
>>> bool(-10)
True
>>> bool(0.0)
False
>>> bool(10.0)
True
>>> bool(10+20j)
True
False
>>> bool(0+1j)
True
False
>>> bool("raj")
True
True
>>> str(10)
'10'
>>> str(10.5)
'10.5'
>>> str(True)
'True'
>>> str(10+20j)
'(10+20j)'
Mutable===changable
Immutable===non changable
X=10
Y=10
No memory wastage
Reusing the object
V1=”bang”
V2=”bang”
V3=”bang”
V10000=”bang”
id(v1)
id(v2)
v3=”mysore”
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
Float
X=10.0
Y=10.0
Xis y
False
Note:for float no reusing concept
X=10+20j
Y=10+20j
X is y
False
Int 0-256
Bool always
Str always
A=10
B=10
C=10
0.1
0.01
0.11
….
Infinity
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'
10
20
30
40
>>> x=[10,20,256,258]
>>> b=bytes(x)
Traceback (most recent call last):
b=bytes(x)
>>> x=[10,20,30,40]
>>>x=[10,20,30,40]
B=bytearray(x)
>>> b[0]
10
>>> b[0]=120
b[0]=120
Duplicates allowed
Hetrogenious allowed
None allowed
Growable
mutable
L=[]
Type(l)
<class ‘list’>
[Link](10)
[Link](20)
[Link](30)
[Link](10)
print(l)------------------------[10,20,30,10]
[Link](“jain”)
[Link](None)
print(l)---------------------------------[10,20,…,None]
>>> s=[10,'jain',True]
>>> s
>>> s1=s*2
>>> s1
>>> s2=s*s
s2=s*s
Duplicates allowed
Hetrogenious allowed
But required mutable
>>> l=[10,20,30,40]
>>> type(l)
<class 'list'>
>>> t=(10,20,30,40)
>>> type(t)
<class 'tuple'>
>>> t
>>> t[0]
10
>>> t[0:3]
>>> t[0]=100
t[0]=100
>>> t1=t*2
>>> t1
>>> t=(10,20,[2,6])
>>> t
(10, 20, [2, 6])
form1:
>>> range(10)
range(0, 10)
>>> range(100)
range(0, 100)
>>> r=range(10)
>>> type(r)
<class 'range'>
>>> range(0,10)
range(0, 10)
9
>>> r[0]
>>> r[4]
>>> r[0:3]
range(0, 3)
>>> r=range(10)
>>> r[0]=777
r[0]=777
range(0, 100)
>>> range(10,30)
range(10, 30)
Form 3:
>>> range(10,50,5)
range(10, 50, 5)
10
15
20
25
30
35
40
45
>>> range(10.5,20.6)
range(10.5,20.6)
>>> range(10.5)
range(10.5)
Set:{}
No index
Growable
No slice operator
Mutable
No append method
>>> s={10,20,30,10,20,30}
>>> type(s)
<class 'set'>
>>> s
>>> s[0]
s[0]
>>> s={10,20,30}
<class 'set'>
>>> [Link]('jain')
>>> s
>>> [Link](20)
>>> s
Frozenset:
>>> s={10,20,30,40}
>>> fs=frozenset(s)
>>> type(fs)
<class 'frozenset'>
>>> fs
>>> [Link](50)
Traceback (most recent call last):
[Link](50)
Dict:{ }
Rollnumber-name
Mobilenumber-name
>>> d={100:'raju',200:'ramu',300:'raj'}
>>> type(d)
<class 'dict'>
>>> d
>>> s=set()
>>> type(s)
<class 'set'>
Python Collections :
There are four collection data types in the Python programming language:
List
A list is a collection which is ordered and changeable. In Python lists are written
with square brackets.
print(thislist)
output:
C:\del>python [Link]
print(thislist[1])
output:
C:\del>python [Link]
Banana
thislist[1] = "blackcurrant"
print(thislist)
output:
C:\del>python [Link]
thislist[3] = "blackcurrant"
print(thislist)
output:
error:
C:\del>python [Link]
thislist[3] = "blackcurrant"
for x in thislist:
print(x)
output:
C:\del>python [Link]
apple
banana
cherry
if "apple" in thislist:
output:
C:\del>python [Link]
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:
[Link]("orange")
print(thislist)
[Link](1, "orange")
print(thislist)
Remove Item
[Link]("banana")
print(thislist)
Example
The pop() method removes the specified index, (or the last item if index is not
specified):
[Link]()
print(thislist)
output:
C:\del>python [Link]
['apple', 'banana']
Example
del thislist[0]
print(thislist)
output:
C:\del>python [Link]
['banana', 'cherry']
del thislist
print(thislist)
output:
C:\del>python [Link]
s.
Example
[Link]()
print(thislist)
print(thislist)
Tuple
print(thistuple)
C:\del>python [Link]
You can access tuple items by referring to the index number, inside square
brackets:
print(thistuple[1])
output:
banana
Once a tuple is created, you cannot change its values. Tuples are unchangeable.
thistuple[1] = "blackcurrant"
print(thistuple)
output:
C:\del>python [Link]
Traceback (most recent call last):
thistuple[1] = "blackcurrant"
You can loop through the tuple items by using a for loop.
Set
A set is a collection which is unordered and unindexed. In Python sets are written
with curly brackets.
print(thisset)
output:
C:\del>python [Link]
C:\del>python [Link]
Note: Sets are unordered, so the items will appear in a random order.
for x in thisset:
print(x)
output:
C:\del>python [Link]
apple
cherry
banana
C:\del>python [Link]
cherry
banana
apple
C:\del>python [Link]
banana
cherry
apple
output:
C:\del>python [Link]
True
Change Items
Once a set is created, you cannot change its items, but you can add new items.
Add Items
To add more than one item to a set use the update() method.
[Link]("orange")
print(thisset)
output:
C:\del>python [Link]
print(thisset)
output:
C:\del>python [Link]
{'mango', 'grapes', 'cherry', 'orange', 'apple', 'banana'}
print(len(thisset))
output:
Remove Item
[Link]("banana")
print(thisset)
output:
C:\del>python [Link]
{'apple', 'cherry'}
Note: If the item to remove does not exist, remove() will raise an error.
[Link]("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.
x = [Link]()
print(x)
print(thisset)
output:
C:\del>python [Link]
apple
{'banana', 'cherry'}
Note: Sets are unordered, so when using the pop() method, you will not know
which item that gets removed.
[Link]()
print(thisset)
output:
C:\del>python [Link]
set()
The del keyword will delete the set completely:
del thisset
print(thisset)
print(thisset)
Dictionary
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
print(thisdict)
output:
C:\del>python [Link]
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
x = thisdict["model"]
print(x)
output:
C:\del>python [Link]
Mustang
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
x = [Link]("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 [Link]
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
for x in thisdict:
print(x)
output:
C:\del>python [Link]
brand
model
year
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
for x in thisdict:
print(thisdict[x])
output:
C:\del>python [Link]
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 [Link]():
print(x)
outuput:
C:\del>python [Link]
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 [Link]():
print(x, y)
output:
C:\del>python [Link]
brand Ford
model Mustang
year 1964
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
if "model" in thisdict:
output:
C:\del>python [Link]
Dictionary Length
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 [Link]
Removing Items
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
[Link]("model")
print(thisdict)
output:
C:\del>python [Link]
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
[Link]()
print(thisdict)
outuput:
C:\del>python [Link]
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 [Link]
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
del thisdict
Output:
C:\del>python [Link]
s.
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
[Link]()
print(thisdict)
outuput:
C:\del>python [Link]
{}
# note the use of equals rather than colon for the assignment
print(thisdict)
outuput:
C:\del>python [Link]
a = 33
b = 200
if b > a:
outuput:
C:\del>python [Link]
b is greater than a
Elif
a = 33
b = 33
if b > a:
elif a == b:
Else
a = 200
b = 33
if b > a:
elif a == b:
else:
output:
C:\del>python [Link]
a is greater than b
a = 200
b = 33
if b > a:
else:
output:
C:\del>python [Link]
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
C:\del>python [Link]
a is greater than b
a = 33
b = 200
if b > a:
outuput:
C:\del>python [Link]
b is greater than a
Elif
a = 33
b = 33
if b > a:
elif a == b:
b = 33
if b > a:
elif a == b:
else:
output:
C:\del>python [Link]
a is greater than b
a = 200
b = 33
if b > a:
else:
output:
C:\del>python [Link]
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 [Link]
a is greater than b
ex2:
a = 330
b = 330
output:
C:\del>python [Link]
Python Loops
• while loops
• for loops
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 [Link]
1
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 [Link]
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 [Link]
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.
for x in fruits:
print(x)
output:
C:\del>python [Link]
apple
banana
cherry
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 [Link]
apple
banana
Example
Exit the loop when x is "banana", but this time the break comes before the print:
for x in fruits:
if x == "banana":
break
print(x)
output:
C:\del>python [Link]
Apple
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 [Link]
apple
cherry
for x in range(6):
print(x)
output:
C:\del>python [Link]
print(x)
C:\del>python [Link]
print(x)
output:
C:\del>python [Link]
11
14
17
20
23
26
29
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 [Link]
Finally finished!
Nested Loops
The "inner loop" will be executed one time for each iteration of the "outer loop":
for y in fruits:
print(x, y)
output:
C:\del>python [Link]
red apple
red banana
red cherry
big apple
big banana
big cherry
tasty apple
tasty banana
tasty cherry
Creating a Function
def my_function():
output:
no output
Calling a Function
def my_function():
my_function()
output:
C:\del>python [Link]
Parameters
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):
my_function("Emil")
my_function("Tobias")
my_function("Linus")
output;
C:\del>python [Link]
Emil Refsnes
Tobias Refsnes
Linus Refsnes
my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
output:
C:\del>python [Link]
I am from Sweden
I am from India
I am from Norway
I am from Brazil
Return Values
def my_function(x):
return 5 * x
print(my_function(3))
print(my_function(5))
print(my_function(9))
output:
C:\del>python [Link]
15
25
45
def hi():
print("hi")
hi()
output:
C:\del>python [Link]
hi
Parameters in function
print("Hi ",name);
displayname("rajesh")
output:
C:\del>python [Link]
Hi rajesh
#defining the function
return a+b;
a = int(input("Enter a: "))
b = int(input("Enter b: "))
print("Sum = ",add(a,b))
output:
C:\del>python [Link]
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
output:
C:\del>python [Link]
A lambda function can take any number of arguments, but can only have one
expression.
Syntax
lambda arguments : expression
x = lambda a: a + 10
print(x(5))
output:
C:\del>python [Link]
15
x = lambda a, b: a * b
print(x(5, 6))
outuput:
C:\del>python [Link]
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 [Link]
13
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 [Link]
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 [Link]
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 [Link]
22
33
Use lambda functions when an anonymous function is required for a short period of
time.
Arrays
Syntax:
Typecode Value
Write a Python program to create an array of 5 integers and display the array
items. Access individual element through indexes
for i in array_num:
print(i)
print(array_num[1])
print(array_num[2])
C:\del>python [Link]
10
20
30
40
50
10
20
30
2 Write a Python program to append a new item to the end of the array.
array_num.append(60)
C:\del>python [Link]
array_num = array('i', [10, 20, 30, 40, 50, 60, 70, 80])
array_num.reverse()
print(str(array_num))
C:\del>python [Link]
Original array: array('i', [10, 20, 30, 40, 50, 60, 70, 80])
pro4:Write a Python program to get the length in bytes of one array item in the
internal representation.
C:\del>python [Link]
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.
C:\del>python [Link]
Current memory address and the length in elements of the buffer: (3453384, 5)
C:\del>python [Link]
Original array: array('i', [10, 30, 30, 40, 30, 60, 30])
Pro7: Write a Python program to append items from inerrable to the end of the
array.
array_num.extend(array_num)
print("Extended array: "+str(array_num))
C:\del>python [Link]
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.
array_num.insert(1, 45)
C:\del>python [Link]
[Link](40)
for x in array1:
print(x)
C:\del>python [Link]
10
20
30
50
print ([Link](40))
C:\del>python [Link]
Pro11:update array
array1[2] = 80
for x in array1:
print(x)
output:
C:\del>python [Link]
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)):
for j in range(len(X[0])):
for r in result:
print(r)
C:\del>python [Link]
[17, 15, 4]
[10, 12, 9]
Matrix multiplication
# 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]]
for i in range(len(X)):
for j in range(len(Y[0])):
for k in range(len(Y)):
for r in result:
print(r)
C:\del>python [Link]
Transpose matrix
X = [[12,7],
[4 ,5],
[3 ,8]]
result = [[0,0,0],
[0,0,0]]
for i in range(len(X)):
for j in range(len(X[0])):
result[j][i] = X[i][j]
for r in result:
print(r)
C:\del>python [Link]
[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
import numpy as np
print(A)
print(A)
A = [Link]([[1, 2, 3], [3, 4, 5]], dtype = complex) # Array of complex
numbers
print(A)
import numpy as np
print(zeors_array)
C:\del>python [Link]
[[0. 0. 0.]
[0. 0. 0.]]
import numpy as np
ones_array = [Link]( (1, 5), dtype=np.int32 )
print(ones_array)
C:\del>python [Link]
[[1 1 1 1 1]]
import numpy as np
A = [Link](4)
print('A =', A)
B = [Link](12).reshape(2, 6)
print('B =', B)
C:\del>python [Link]
A = [0 1 2 3]
B = [[ 0 1 2 3 4 5]
[ 6 7 8 9 10 11]]
import numpy as np
C=A+B
print(C)
C:\del>python [Link]
[[11 1]
[ 8 0]]
import numpy as np
C = [Link](B)
print(C)
C:\del>python [Link]
[[ 36 -12]
[ -1 2]]
Transpose of a Matrix
import numpy as np
print([Link]())
C:\del>python [Link]
[[ 1 2 3]
[ 1 1 -3]]
A = [Link]([2, 4, 6, 8, 10])
C:\del>python [Link]
A[0] = 2
A[2] = 6
A[-1] = 10
Python Classes/Objects
Create a Class
class MyClass:
x=5
print(MyClass)
output:
C:\del>python [Link]
<class '__main__.MyClass'>
Create Object
class MyClass:
x=5
p1 = MyClass()
print(p1.x)
output:
C:\del>python [Link]
5
Pdbc(python database connectivity )
1)temporary data
2)permanent data
temporary data:
for i in range(10)
name
marks
d[name]=marks
permanent data:
1)file system:
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:
3)cloud…etc:
Ex:
Oracle cx_Oracle
Sqlserver pymssql
Mysql pymysql
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=[Link]()
[Link](sqlquery )
[Link](sqlqueries )
6)commit()---------------------to save
rollback()------------------------undo
7)[Link]()
[Link]()
Program1:to connect with database and print its version
import cx_Oracle
con=cx_Oracle.connect('system/oracle@orcl')
if con!=None:
print('version',[Link])
else:
[Link]()
Program 2: To create employees table in the database
------------
import cx_Oracle
try:
con=cx_Oracle.connect('system/oracle@orcl')
cursor=[Link]()
[Link](query)
except cx_Oracle.DatabaseError as e:
if con:
[Link]()
print('there is a problem',e)
finally:
if cursor:
[Link]()
if con:
[Link]()
----------------------------------
try:
con=cx_Oracle.connect('system/oracle@orcl')
cursor=[Link]()
[Link](query)
except cx_Oracle.DatabaseError as e:
if con:
[Link]()
print('there is a problem',e)
finally:
if cursor:
[Link]()
if con:
[Link]()
program 4:insert a row into table
import cx_Oracle
try:
con=cx_Oracle.connect('system/oracle@orcl')
cursor=[Link]()
[Link](query)
[Link]()
except cx_Oracle.DatabaseError as e:
if con:
[Link]()
print('there is a problem',e)
finally:
if cursor:
[Link]()
if con:
[Link]()
---------------------------------------------------------------------
-----------
import cx_Oracle
try:
con=cx_Oracle.connect('system/oracle@orcl')
cursor=[Link]()
[Link](query)
except cx_Oracle.DatabaseError as e:
if con:
[Link]()
print('there is a problem',e)
finally:
if cursor:
[Link]()
if con:
[Link]()