0% found this document useful (0 votes)
20 views

Python Notes Fixed

Uploaded by

shaikha.aljn2
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

Python Notes Fixed

Uploaded by

shaikha.aljn2
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

T2-3: GENERAL INFORMATION

Code/Example Output
print:
print("Hello World") Hello World
id:
a=1
print(id(a)) 140706977407784
Single Ǫuotes ('):
print('Hello How Are You') Hello How Are You
Double Ǫuotes ("):
print(''Hello How Are You'') Hello How Are You
Triple Ǫuotes (''' '''):
print('''Hello Hello
How How
Are Are
You''') You
\t:
print('Khalifa University') Khalifa University
print('Khalifa\tUniversity') Khalifa University
print('Khalifa \tUniversity') Khalifa University
\n:
print('Khalifa\nUniversity') Khalifa
University
input:
name=input('Please type your name:') Please type your name: Hadher
print(''Your name is: '', name) Your name is Hadher
f-strings formatting:
Uni_name_1='Khalifa'
Uni_name_2='University'
print(f'I study at {Uni_name_1} {Uni_name_2}.') I study at Khalifa University.
.format():
Uni_name_1='Khalifa'
Uni_name_2='University'
print('I study at {} {}.'
.format(Uni_name_1,Uni_name_2)) I study at Khalifa University.
%s %d %f %e:
print("I study at %s" %('KU')) I study at KU
print("I am %d years old" %(18)) I am 18 years old
print('Floating number is: %f' %(5.1234)) Floating number is: 5.123400
print('Scientific number of 1000 is: %e' Scientific number of 1000 is: 1.000000e+03
%(1000))
T4: ALGORITHMS AND FLOWCHART
Sequence
PSEUDOCODE

Step 1: Input first number as A

Step 2: Input second number as B

Step 3: Set Sum = A+B

Step 4: Print Sum

Step 5: End

PSEUDOCODE

Step 1: Input first number as A

Step 2: Input second number as B

Step 3: IF A = B Print “Equal” ELSE Print “Not Equal” [End of IF]

Step 4: End

PSEUDOCODE

Step 1: [Initialize] Set I=1, N = 10

Step 2: Repeat steps 3 and 4 while I<=N

Step 3: Print I

Step 4: SET I = I + 1 [END of LOOP]

Step 5: End
Flowchart
T5: CONTROL STRUCTURES I
Code/Example Output
if:
age = int(input("Enter your age :")) Enter your age :19
if (age > 18):
print("You’re older than 18") You’re older than 18
else:
age = int(input("Enter your age :")) Enter your age :14
if (age > 18):
print("You’re older than 18")
else:
print("You’re younger than 18") You’re younger than 18
elif:
age = int(input("Enter your age :")) Enter your age :18
if (age > 18):
print("You’re older than 18")
elif (age == 18):
print("You’re18") You’re18
else:
print("You’re younger than 18")
T6: CONTROL STRUCTURES II
Code/Example Output
while loop + end:
i=0
while (i<=10):
print(i, end="") i=i+1 012345678910
while loop + end:
i=0
while (i<=10):
print(i, end=" ") i=i+1 0 1 2 3 4 5 6 7 8 9 10
break: (exit loop)
n=5
while n > 0:
n += 1
if (n==10):
break
print(n, end="") 6789
print("\nLoop ended") Loop ended
Continue: (goes back to the beginning)
n=5
while n > 0:
n += 1
if (n==7):
continue
if (n==10):
break
print(n, end="") 689
print("\nLoop ended") Loop ended
for loop:
fruits = ["apple", "banana", "mango"]
for i in fruits:
print(i, end=" ") apple banana mango
range: (begin,end,step)
for i in range(1,10,2):
print(i, end="") 13579
nested for: juicy apple
X = ["juicy", "big"] juicy banana
Y = ["apple", "banana", "mango"] juicy mango
for i in X: big apple
for j in Y: big banana
print(i, j) big mango
T7: FUNCTIONS
Code/Example Output
def a function:
def printme(str):
print (str)
return

printme("Hello world!") Hello world!


def printme(str):
print (str)

printme("Hello world!") Hello world!


def printme(str):
return str

print(printme("Hello world!")) Hello world!


def arguments:
def func(i,j):
print("Hello World") Hello world!

func(5,6)
def func():
print("Hello World") Hello world!

func()
*args:
def sum(*args):
s=0
for arg in args:
s=s+arg
return s

print(sum(10,20)) 30
print(sum(10,20,30,40)) 100
**kwargs:
def printinfo(**kwargs):
for arg in kwargs:
print(arg)
Name
printinfo(Name="Shakti", age=10, city="Dubai") age
city
**kwargs - values:
def printinfo(**kwargs):
for arg in kwargs.values():
print(arg)
Shakti
printinfo(Name="Shakti", age=10, city="Dubai") 10
Dubai
**kwargs - items:
def printinfo(**kwargs):
for arg,value in kwargs.items():
print(arg,value)
Name Shakti
printinfo(Name="Shakti", age=10, city="Dubai") age 10
city Dubai
global variable – sample 1:
a=1
def diff (x,y):
a=x-y
print(a)

print(a) 1
diff (5,2) 3
print (a) 1
global variable – sample 2:
a=1
def diff (x,y):
global a
a=x-y
print(a)

print(a) 1
diff (5,2) 3
print (a) 3
Recursive functions:
def countdown(n):
print(n)
if n==0: 5
return 4
else: 3
countdown(n-1) 2
1
countdown(5) 0
lambda:
add_five = lambda x: x+5
print(add_five(10)) 15
T8: LISTS

Code/Example Output
len:
mylist = ["cup", 20, 2.3, "football"]
print(len(mylist)) 4

print(len(["Mon", "Tue", "Wed"])) 3


index:
mylist = ["cup", 20, 2.3, "football"]
print(mylist[0], mylist[1], mylist[2], mylist[3]) cup 20 2.3 football
reversed index:
mylist = ["cup", 20, 2.3, "football"]
print(mylist[-1], mylist[-2], mylist[-3], mylist[-4]) Football 2.3 20 cup
range of index: (start:end:stride)
mylist = ["cup", 20, 2.3, "football", True, "cup"]
print(mylist[:4]) ['cup', 20, 2.3, 'football']

mylist = ["cup", 20, 2.3, "football", True, "cup"]


print(mylist[2:]) [2.3, 'football', True, 'cup']

mylist = ["cup", 20, 2.3, "football", True, "cup"]


print(mylist[1:6]) # default stride=1 [20, 2.3, 'football', True, 'cup']
print(mylist[1:6:1]) # stride=1 [20, 2.3, 'football', True, 'cup']
print(mylist[1:6:2]) # stride=2, skips every 2 [20, 'football', 'cup']
reversing a list:
mylist = ["cup", 20, 2.3, "football", True, "cup"]
print(mylist[::-1]) ["cup", True, "football", 2.3, 20, "cup"]
item check:
mylist = ["cup", 20, 2.3, "football", True, "cup"]
if 2.3 in mylist:
print("2.3 is in the list") 2.3 is in the list
else:
print("2.3 is not in the list")
changing item:
change 1 item:
mylist = ["cup", 20, 2.3, "football", True, "cup"]
mylist[2]= "University" ['cup', 20, 'University', 'football', True, 'cup']
#changes index 2 item in the list to University
print(mylist)

change range of items: ['cup', 20, 1, 2, 'Hello', 'cup']


mylist = ["cup", 20, 2.3, "football", True, "cup"]
mylist[2:5]= [1,2,"Hello"]
#changes index 2,3,4 items in the list
print(mylist)

change and extend a list:


mylist = ["cup", 20, 2.3, "football", True, "cup"]
mylist[2:5]= [1,2,"Hello",7,6]
# changes index 2,3,4 items in the list
print(mylist) ['cup', 20, 1, 2, 'Hello', 7, 6, 'cup'
insert:
mylist = ["cup", 20, 2.3, "football", True, "cup"]
mylist.insert(2, "tree") # insert "tree" at index 2
print(mylist) ['cup', 20, 'tree', 2.3, 'football', True, 'cup']
append:
mylist = ["cup", 20, 2.3, "football", True, "cup"]
mylist.append("tree")
# insert only one argument, at the end
print(mylist) ['cup', 20, 2.3, 'football', True, 'cup', 'tree']
extend:
mylist = ["cup", 20, 2.3, "football", True, "cup"]
mylist.extend(["tree", 2, 6, 5])
#insert multiple arguments at the end
print(mylist) ['cup', 20, 2.3, 'football', True, 'cup', 'tree', 2, 6, 5]
concatenation:
mylist = ["cup", 20, 2.3, "football", True, "cup"]
adding = ["tree", 2, 6, 5]
newlist=mylist+adding
print(newlist) ['cup', 20, 2.3, 'football', True, 'cup', 'tree', 2, 6, 5]
remove:
mylist = ["cup", 20, 2.3, "football", True, "cup"]
mylist.remove("football")
print(mylist) ['cup', 20, 2.3, True, 'cup', 'tree']
pop:
mylist = ["cup", 20, 2.3, "football", True, "cup"]
mylist.pop(3) #using index
print(mylist) ['cup', 20, 2.3, True, 'cup', 'tree']
del:
mylist = ["cup", 20, 2.3, "football", True, "cup"]
del mylist[3] #using index
print(mylist) ['cup', 20, 2.3, True, 'cup', 'tree']

mylist = ["cup", 20, 2.3, "football", True, "cup"]


del mylist #delete entire list
print(mylist) NameError: name 'mylist' is not defined
clear:
mylist = ["cup", 20, 2.3, "football", True, "cup"]
mylist.clear #empty the list
print(mylist) []
copy:
mylist = ["cup", 20, 2.3, "football", True, "cup"]
newlist = mylist.copy()
print(newlist) ["cup", 20, 2.3, "football", True, "cup"]
list:
mylist = ["cup", 20, 2.3, "football", True, "cup"]
newlist = list(mylist)
print(newlist) ["cup", 20, 2.3, "football", True, "cup"]
sort: (ascending order)
mylist = [30, 3.4, -22, 4]
mylist.sort()
print(mylist) [-22, 3.4, 4, 30]

mylist = ["Mars", "Venus", "Jupiter", "Earth"]


mylist.sort()
print(mylist) ['Earth', 'Jupiter', 'Mars', 'Venus']
sorted: (ascending order)
mylist = [30, 3.4, -22, 4]
print(sorted(mylist)) #sortes it in place [-22, 3.4, 4, 30]
print(mylist) #doesn’t get effected [30,3.4,-22,4]

mylist = ["Mars", "Venus", "Jupiter", "Earth"]


print(sorted(mylist)) #sortes it in place ['Earth', 'Jupiter', 'Mars', 'Venus']
print(mylist) #doesn’t get effected ["Mars","Venus","Jupiter","Earth"]
revered function:
mylist = [30, 3.4, -22, 4]
mylist.sort(reverse=True)
print(mylist) [30, 4, 3.4, -22]

mylist = [30, 3.4, -22, 4]


print(sorted(mylist,reverse=True)) [30, 4, 3.4, -22]
sort key:
def abso(y):
if y>=0:
y=y
else:
y = -y
return y

mylist = [30, 3.4, -22, 4]


mylist.sort(key=abso)
print(mylist) [3.4, 4, -22, 30]
reverse:
mylist = ["cup", 20, 2.3, "football", True, "cup"]
mylist.reverse()
print(mylist) ['cup', True, 'football', 2.3, 20, 'cup']
repetition:
list1=['Hello']
print(list1 * 4) ['Hello', 'Hello', 'Hello', 'Hello']
list comprehension:
mylist = [(i)**2 for i in range(1,10)]
print(mylist) [1, 4, 9, 16, 25, 36, 49, 64, 81]

mylist = ["cup",20,2.3,"football",True, "cup"]


list0 = [x for x in mylist if x != "football"]
print(list0)
['cup', 20, 2.3, True, 'cup']
enumerate: (iterable, start=0)
fruits=['apple','orange','kiwi']
a=enumerate(fruits)
print(list(a)) [(0, 'apple'), (1, 'orange'), (2, 'kiwi')]

fruits=['apple','orange','kiwi']
a=enumerate(fruits,5)
print(list(a)) [(5, 'apple'), (6, 'orange'), (7, 'kiwi')]
iter: (object, sentinel)
fruits=['apple','orange','kiwi']
fruits_iter = iter(fruits)
# using next() to print iterator values
print(next(fruits_iter)) Apple
print(next(fruits_iter)) Orange
print(next(fruits_iter)) kiwi
linear search:
mylist = ["cup",20,2.3,"football",True, "cup"]

def linears(xlist, y):


for i in range(len(xlist)):
if xlist[i] == y:
return True
return False

print(linears(mylist,2.3)) True
multidimensional list:
mymultlist1 = [[10,5,21], [4, 55, 19],[32,3,23]]
for i in mymultlist1:
print(i) [10, 5, 21]
[4, 55, 19]
[32, 3, 23]
T9: STRINGS

Code/Example Output
str:
num1 = "21"
num2 = str(31)
print(num1, num2) 21 31
len:
mystr = "Hello Bye"
print(len(mystr)) 9
index:
mystr="Hello"
print(mystr[0], mystr[1], mystr[2], mystr[3], Hello
mystr[4])
reversed index:
mystr="Hello"
print(mystr[-1], mystr[-2], mystr[-3], mystr[-4], o lle H
mystr[-5])
range of index: (start:end:stride)
mystr="Hello Bye"
print(mystr[1:4]) ell
print(mystr[-4:-1]) By
print(mystr[:3]) Hel
print(mystr[3:]) lo Bye

print(mystr[1:9:1]) # stride=1 ello Bye


print(mystr[1:9:2]) # stride=2 el y
print(mystr[1:9:5]) # stride=5 eB
reversing a string:
mystr="Hello Bye"
print(mystr[::-1]) eyB olleH
string check:
mystr="Hello Bye"
print('o' in mystr) True
print('By' in mystr) True
print('h' in mystr) False
print('ello' not in mystr) False
concatenation and append:
string1="Khalifa"
string2="University"
string3=string1 + string2 #concatenation
print("string3 is", string3) string3 is KhalifaUniversity
string4=string1 + " " + string2 #concatenation
print("string4 is",string4) string4 is Khalifa University
join:
x='abc'
y='123'
print(x.join(y)) 1abc2abc3
repetition:
mystr='Hello'
print(mystr*3) HelloHelloHello

mystr='Hello'
print((mystr+" ")*3) Hello Hello Hello
capitalize & title:
mystr="hello How are you?"
x=mystr.capitalize() #first letter in sentence
y=mystr.title() #first letter for every word
print('x is {}'.format(x)) x is Hello how are you?
print('y is {}'.format(y)) y is Hello How Are You?
find & index:
mystr="hello How are you?"
x=mystr.find('r') #first occurrence, else -1
y=mystr.index('r') #first occurrence, else error
print('x is {}'.format(x)) x is 11
print('y is {}'.format(y)) y is 11
startwith & endwith:
mystr="hello How are you?"
print(mystr.startswith('H')) False
print(mystr.startswith('he')) True
print(mystr.endswith('ou?')) True
swapcase:
mystr="hello How are you?"
x=mystr.swapcase()
#swap upper and lower case. HELLO hOW ARE YOU?
print(x)
replace:
mystr="hello How are you?"
x=mystr.replace('o','u') #replace all
y=mystr.replace('o','u',2) #replace twice
print('x is {}'.format(x)) x is hellu Huw are yuu?
print('y is {}'.format(y)) y is hellu Huw are you?
split:
mystr1="hello How are you?"
mystr2="apple, orange, banana, watermelon"
x=mystr1.split() #split at spaces
y=mystr2.split(",") #split at ,
print('x is {}'.format(x)) x is ['hello', 'How', 'are', 'you?']
print('y is {}'.format(y)) y is ['apple', ' orange', ' banana', ' watermelon']
strip:
mystr1=" hello How are you? "
print(mystr1) hello How are you?
print(mystr1.strip()) hello How are you?

mystr2=" hello How are you?"


print(mystr2) hello How are you?
print(mystr2.strip(?)) hello How are you
T10 - P1: TUPLES

Code/Example Output
tuple:
list1=[1,2,3,4]
items1=(('a','b','c','d'))
items2=1,3,'a','p'
x=tuple(list1)
y=tuple(items1)
z=tuple(items2)
print(x) (1, 2, 3, 4)
print(y) ('a', 'b', 'c', 'd')
print(z) (1, 3, 'a', 'p')
len:
mytuple = ("cup",20,2.3,"football",True, "cup")
print(len(mytuple)) 6
index:
mytuple = ("cup", 20, 2.3, "football", True, "cup")
print(mytuple[0],mytuple[1],mytuple[2],mytuple[3]) cup 20 2.3 football
reversed index:
mytuple = ("cup", 20, 2.3, "football", True, "cup")
print( mytuple [-1], mytuple [-2], mytuple [-3], cup True football 2.3
mytuple [-4], mytuple [-5])
range of index: (start:end:stride)
mytuple = ("cup",20,2.3,"football",True, "cup")
print(mytuple[1:4]) (20, 2.3, 'football')
print(mytuple[-4:-1]) (2.3, 'football', True)
print(mytuple[:3]) ('cup', 20, 2.3)
print(mytuple[3:]) ('football', True, 'cup')

print(mytuple[1:4:1]) #stride=1 (20, 2.3, 'football')


print(mytuple[1:5:2]) #stride=2 (20, 'football')
print(mytuple[:5:3]) # stride=3, no beginning ('cup', 'football')
reversing a tuple:
mytuple = ("cup",20,2.3,"football",True, "cup")
print( mytuple [::-1]) ('cup', True, 'football', 2.3, 20, 'cup')
tuple check:
mytuple = ("cup",20,2.3,"football",True, "cup")
print('cup' in mytuple) True
print(2.3 in mytuple) True
print(False in mytuple) False
print('ello' not in mytuple) True
concatenation, append and multiply:
tup1=(1,2,3,'apple')
tup2=('moon','bat')
tup3=tup2+tup1
print(tup3) ('moon', 'bat', 1, 2, 3, 'apple')
print((tup3)*3) ('moon', 'bat', 1, 2, 3, 'apple', 'moon', 'bat', 1,
2, 3, 'apple', 'moon', 'bat', 1, 2, 3, 'apple')
packing/unpacking:
mtup = ("Sun", "Moon", 3.3)

(low, medium, high) = mtup


print(low) Sun
print(medium) Moon
print(high) 3.3
packing/unpacking with *:
mtup = ("Sun", "Moon", 3.3, 5, "b")

(low, *medium, high) = mtup


print(low) Sun
print(medium) ['Moon', 3.3, 5]
print(high) b
index:
mytuple = ("cup",20,2.3,"football",True, "cup")
print(mytuple.index("cup"), mytuple.index(2.3)) 02
a=mytuple.index(20)
print("20 is present at location",a) 20 is present at location 1
count:
mytuple = ("cup",20,2.3,"football",True, "cup")
print(mytuple.count(2.3)) 1
print(mytuple.count("cup")) 2
print(mytuple.count(4)) 0
zip:
numbers = (1, 2, 3)
letters = ('a', 'b', 'c')
zipped = zip(numbers, letters)
print(tuple(zipped)) ((1, 'a'), (2, 'b'), (3, 'c'))
del:
mytuple = ("cup",20,2.3,"football",True, "cup")
del mytuple[2]
print (mytuple) builtins.TypeError: 'tuple' object doesn't
#tuples are immutable, cannot delete a single item support item deletion

mytuple = ("cup",20,2.3,"football",True, "cup")


del mytuple
print (mytuple) builtins.NameError: name 'mytuple' is not
#you can delete an entire tuple defined
T10 - P2 : DICTIONARY

Code/Example Output
dictionary:
stu={"Name":"Mohammed", "Age":20, "Student":True}
print(stu) {'Name': 'Mohammed', 'Age': 20,
'Student': True}
stu={"Name":"Mohammed", "Age":20, "Student":True,
"Age":30}
print(stu) #Duplicate keys will be overwritten {'Name': 'Mohammed', 'Age': 30,
'Student': True}
dict & len:
stu=dict(Name="Mohammed",Age=20, Student=True)
print(stu) {'Name': 'Mohammed', 'Age': 20,
print(stu["Age"]) 'Student': True}
print(len(stu)) 20
3
keys, values and items:
uni= {"Uni":"KU","Campus":"Main","PO":127788,"City":"AD"}
print(uni.keys()) dict_keys(['Uni', 'Campus', 'PO',
'City'])

print(uni.values()) dict_values(['KU', 'Main', 127788,


'AD'])

print(uni.items()) dict_items([('Uni', 'KU'), ('Campus',


'Main'), ('PO', 127788), ('City', 'AD')])

print(list(uni.keys())) ['Uni', 'Campus', 'PO', 'City']


get:
stu={'Name': 'Mohammed', 'Age': 20, 'Student': True}
print(stu["Age"]) 20
print(stu.get("Age")) 20
changing items:
uni=
{"University":"KU","Campus":"Main","PO":127788,"City":"Abu
Dhabi"}
uni["Campus"]= "SAN"
uni["PO"]=None
print(uni) {'University': 'KU', 'Campus': 'SAN',
'PO': None, 'City': 'Abu Dhabi'}
update:
uni=
{"University":"KU","Campus":"Main","PO":127788,"City":"Abu
Dhabi"}
uni.update({"PO":None})
print(uni) {'University': 'KU', 'Campus': 'Main',
'PO': None, 'City': 'Abu Dhabi'}

stu={'Name': 'Mohammed', 'Age': 20, 'Student': True}


stu.update({'Name':'Fatima','Age':19,'Student':False})
print(stu) {'Name': 'Fatima', 'Age': 19,
'Student': False}
add items:
stu={'Name': 'Mohammed', 'Age': 20, 'Student': True,}
stu["Campus"]="Main" {'Name': 'Mohammed', 'Age': 20,
print(stu) 'Student': True, 'Campus': 'Main'}

stu={'Name': 'Mohammed', 'Age': 20, 'Student': True,}


stu.update({"Campus":"Main"})
print(stu) {'Name': 'Mohammed', 'Age': 20,
'Student': True, 'Campus': 'Main'}
pop, popitem and del:
stu={'Name': 'Mohammed', 'Age': 20, 'Student': True,
'Campus': 'Main'}
stu.pop("Age")
print(stu) {'Name': 'Mohammed', 'Student':
True, 'Campus': 'Main'}
stu.popitem()
print(stu) {'Name': 'Mohammed', 'Student':
True}
del stu['Student']
print(stu) {'Name': 'Mohammed'}
del and clear:
stu={'Name': 'Mohammed', 'Age': 20, 'Student': True,
'Campus': 'Main'}
stu.clear()
print(stu) {}

stu={'Name': 'Mohammed', 'Age': 20, 'Student': True,


'Campus': 'Main'}
del stu builtins.NameError: name 'stu' is
print(stu) not defined
copy:
uni1=
{"University":"KU","Campus":"Main","PO":127788,"City":"Abu
Dhabi"}
uni2=uni1.copy()
print(uni2) {'University': 'KU', 'Campus': 'Main',
'PO': 127788, 'City': 'Abu Dhabi'}
T11: FILES

Code/Example Output
file = open("Week2\Task1.txt", "r") Read mode (default mode). The pointer is placed at
the beginning of the file
file = open("Week2\Task1.txt", "w") Write mode. The pointer is placed at the beginning of
the file. If the file already contains some data, then it
will be overridden but if the file is not present then it
creates the file as well.
file = open("Week2\Task1.txt", "rb") Read mode in binary format. The pointer is placed at
the beginning of the file
file = open("Week2\Task1.txt", "wb") Write mode in binary format. The pointer is placed at
the beginning of the file. If the file already contains
some data, then it will be overridden but if the file is
not present then it creates the file as well.

name, mode and closed:


file = open("Test.txt", "a")
print("The name of the file is,", file.name) The name of the file is, Test.txt
print("The mode in which the file open is,", The mode in which the file open is, a
file.mode) The file is closed: False
print("The file is closed:", file.closed)
close:
file = open("Test.txt", "a")
print("The name of the file is,", file.name) The name of the file is, Test.txt
print("The mode in which the file open is,", The mode in which the file open is, a
file.mode)
file.close() The file is closed: True
print("The file is closed:", file.closed)
write:

_str = "H\ne\nl\nl\no"
file = open("hello.txt", "w")
file.write(_str)
file.close()

write:
my_string = """My name is John Doe
I am 20 years old
I study Engineering at Khalifa University
Python Programming is fun"""
file = open("Test.txt", "w")
file.write(my_string)
file.close()

writelines:
my_string = ["My name is John Doe\n",
"I am 20 years old\n",
"I study Engineering at Khalifa University\n",
"Python Programming is fun"]
file = open("Test.txt", "w")
file.writelines(my_string)
file.close()

appending to an existing file:

my_string2 = "\n\nBlue is my favorite color\n"


file = open("Test.txt", "a")
file.write(my_string2)
file.close()

read:
file = open("Test.txt", "r") My name is John Doe
print(file.read()) I am 20 years old
file.close() I study Engineering at Khalifa University
Python Programming is fun

Blue is my favorite color

file = open("Test.txt", "r")


print(file.read(36)) My name is John Doe
file.close() I am 20 years ol
read:
file = open("Test.txt", "rb")
print(file.read()) b'My name is John Doe\r\nI am 20 years old\r\nI
file.close() study Engineering at Khalifa University\r\nPython
Programming is fun\r\n\r\nBlue is my favorite
color\r\n'
readline:
file = open("Test.txt", "r")
print("First Line: ", file.readline()) First Line: My name is John Doe
file.readline()
print("Third Line: ", file.readline()) Third Line: I study Engineering at Khalifa University
file.close()
readlines:
file = open("Test.txt", "r")
print(file.readlines()) ['My name is John Doe\n', 'I am 20 years old\n', 'I
file.close() study Engineering at Khalifa University\n', 'Python
Programming is fun\n', '\n', 'Blue is my favorite
color\n']
with keyword:
with open("Test.txt", "r") as file:
for line in file:
print(line,end="") My name is John Doe
print("The file is closed: ", file.closed) I am 20 years old
I study Engineering at Khalifa University
Python Programming is fun

Blue is my favorite color


The file is closed: True
splitlines:
_str = "Line 1\nLine 2\nLine 3"
lines = _str.splitlines()
print(lines) ['Line 1', 'Line 2', 'Line 3']

_str = "Line 1\nLine 2\nLine 3"


lines = _str.splitlines(True)
print(lines) ['Line 1\n', 'Line 2\n', 'Line 3']
File pointers:
- tell() : tells current position of the pointer.
- seek(offset,from) : changing the file pointer position.
-- offset : number of bytes to move
-- from : reference position from where to start moving.

tell and seek:


file = open("Test.txt", "r")
print("The file pointer position is:", file.tell()) The file pointer position is: 0
print(file.read(15)) My name is John
print("The file pointer position is:", file.tell()) The file pointer position is: 15
file.seek(0,0)
print("The file pointer position is:", file.tell()) The file pointer position is: 0
file.seek(30,0)
print("The file pointer position is:", file.tell()) The file pointer position is: 30
T12: NUMPY

Code/Example Output
impot: NONE
import numpy
or # “as np” np is a variable, it could be anything
import numpy as np else. “as i, as dubai, as num1”
array:
import numpy as np
my_array1 = np.array([1,2,3,4,5])
my_array2 = np.array((1,2,3,4,5))
print(my_array1,my_array2) [1 2 3 4 5] [1 2 3 4 5]
array:
import numpy as np
my_array3 = np.array([1,2.5,'three'])
my_array4 = np.array([1,2.5,3])
print(my_array3,my_array4) ['1' '2.5' 'three'] [1. 2.5 3. ]
ndim, shape, size and len:
import numpy as np
myarray =
np.array([[1,2,3],[4,5,6],[7,8,9],[10,11,12]])
print("Number of dimensions is",myarray.ndim) Number of dimensions is 2
print("The shape of the array is",myarray.shape) The shape of the array is (4, 3)
print("The size of the array is",myarray.size) The size of the array is 12
print("The length of the array is",len(myarray)) The length of the array is 4
indexing and slicing:
import numpy as np
myarray = np.array([1,2,3,4,5,6,7,8])
print(myarray[0]) 1
print(myarray[-1]) 8
print(myarray[0:6:2]) [1 3 5]
print(myarray[-3:-1]) [6 7]
print(myarray[:5]) [1 2 3 4 5]
print(myarray[5:]) [6 7 8]
print(myarray[::2]) [1 3 5 7]
indexing and slicing:
import numpy as np
myarray = np.array([[1,2,3,4,5],
[6,7,8,9,10]])
print(myarray[0]) [1 2 3 4 5]
print(myarray[1]) [ 6 7 8 9 10]
print(myarray[-1]) [ 6 7 8 9 10]
# myarray(row,col)
print(myarray[0,1]) 2
print(myarray[1,-1]) 10
print(myarray[0,1:3]) [2 3]
print(myarray[0:2,2]) [3 8]
print(myarray[1:4,2:4]) [[8 9]]
Mathematical operations:
import numpy as np
myarray1 = np.array([1, 2, 3, 4])
myarray2 = myarray1*2
myarray3 = myarray1+2
print ("myarray1 is", myarray1) myarray1 is [1 2 3 4]
print ("myarray2 is", myarray2) myarray2 is [2 4 6 8]
print ("myarray3 is", myarray3) myarray3 is [3 4 5 6]
print ("myarray4 is", myarray1**2) myarray4 is [ 1 4 9 16]
print (myarray1[0]-2) -1
change, insert and append:
import numpy as np
myarray1 = np.array([1,2,3])
myarray1[1] = -10
print('myarray1 is:', myarray1) myarray1 is: [ 1 -10 3]
myarray2 = np.insert(myarray1,0,5)
print('myarray2 is:', myarray2) myarray2 is: [ 5 1 -10 3]
myarray3 = np.append(myarray2,6)
print('myarray3 is:', myarray3) myarray3 is: [ 5 1 -10 3 6]
where:
import numpy as np
l=[1,2,3,4,5]
a=np.array(l)
print('a is',a) a is [1 2 3 4 5]
b=a>3
print('b is',b) b is [False False False True True]
c=np.where(a>3)
print('c is',c) c is (array([3, 4], dtype=int64),)
d=a[c]
print('d is',d) d is [4 5]
delete in 1D:
import numpy as np
myarray1 = np.array([9,8,7,6,8,11,14])

# Delete by referring to the index (2)


myarray1 = np.delete(myarray1,2)
print('myarray after deleting index 2 is:', myarray1) myarray after deleting index 2 is: [ 9 8 6
8 11 14]
# Delete by referring to a value (11)
myarray1 =
np.delete(myarray1,np.where(myarray1==11))
print('myarray after deleting value 11 is:', myarray1)

# Deleting multiple items myarray after deleting value 11 is: [ 9 8


myarray2 = np.delete(myarray1,[2,3,4]) 6 8 14]
print('myarray2 is:', myarray2)

myarray2 is: [9 8]
delete rows and columns:
import numpy as np
myarray1 = np.array([[1 ,2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]])

# Delete single column, here first column (0)


myarray2 = np.delete(myarray1,0,axis=1)
print('Deleting column 0\n', myarray2) Deleting column 0
[[ 2 3 4]
# Delete multiple columns, here first and third column [ 6 7 8]
(0,2) [10 11 12]]
myarray3 = np.delete(myarray1,[0,2],axis=1)
print('Deleting columns 0 and 2\n', myarray3) Deleting columns 0 and 2
[[ 2 4]
[ 6 8]
# Delete single row, here second row (1) [10 12]]
myarray4 = np.delete(myarray1,1,axis=0)
print('Deleting row 1\n', myarray4) Deleting row 1
[[ 1 2 3 4]
# Delete multiple rows, here first and third row (0,2) [ 9 10 11 12]]
myarray5 = np.delete(myarray1,[0,2],axis=0)
print('Deleting rows 0 and 2\n', myarray5) Deleting rows 0 and 2
[[5 6 7 8]]
copy: (to create new array)
without:
import numpy as np
myarray1 = np.array([1 ,2, 3, 4])
myarray2 = myarray1
print (myarray1, id(myarray1)) [1 2 3 4] 2055532454336
print (myarray2, id(myarray2)) [1 2 3 4] 2055532454336
myarray1[0]=30
print (myarray1) [30 2 3 4]
print (myarray2) [30 2 3 4]

with:
import numpy as np
myarray1 = np.array([1 ,2, 3, 4])
myarray2 = myarray1.copy()
print (myarray1, id(myarray1)) [1 2 3 4] 2315916542640
print (myarray2, id(myarray2)) [1 2 3 4] 2315916542720
myarray1[0]=30
print (myarray1) [30 2 3 4]
print (myarray2) [1 2 3 4]
concatenation:
import numpy as np
myarray1 = np.array([1,2])
myarray2 = np.array([3,4,5])
myarray3=np.concatenate((myarray1,myarray2))
print('myarray3 is:', myarray3) myarray3 is: [1 2 3 4 5]

import numpy as np myarray3 is


myarray1 = np.array([[1, 2], [3, 4]]) [[1 2]
myarray2 = np.array([[5, 6], [7, 8]]) [3 4]
[5 6]
myarray3=np.concatenate((myarray1,myarray2),axis=0) [7 8]]
print('myarray3 is\n', myarray3)
myarray4 is
myarray4=np.concatenate((myarray1,myarray2),axis=1) [[1 2 5 6]
print('myarray4 is\n', myarray4) [3 4 7 8]]
sort:
import numpy as np
myarray1 = np.array([-3, 2, 0, -8])
myarray2 = np.sort(myarray1)
print(myarray1) [-3 2 0 -8]
print(myarray2) [-8 -3 0 2]
sort: (according to axis)
import numpy as np
myarray1 = np.array([[1,-3,-6] , [-9,-5,3] , [9,4,0]])
print(np.sort(myarray1,axis=None)) [-9 -6 -5 -3 0 1 3 4 9]

[[-9 -5 -6]
print(np.sort(myarray1,axis=0)) [ 1 -3 0]
[ 9 4 3]]

[[-6 -3 1]
print(np.sort(myarray1,axis=1)) [-9 -5 3]
[ 0 4 9]]
iterating:
import numpy as np
myarray = np.array([[1 ,2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]])
for i in myarray:
print(i) [1 2 3 4]
[5 6 7 8]
[9 10 11 12]

for i in myarray:
for j in i:
print(j,end='') 123456789101112
arrays of ones and zeros:
print(np.ones((2,2))) [[1. 1.]
[1. 1.]]

print(np.ones((2,2),dtype=int)) [[1 1]
[1 1]]

print(np.zeros((3, 5), dtype=float)) [[0. 0. 0. 0. 0.]


[0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0.]]
random:
import numpy as np arr1 is
arr1 = np.random.random(4) [0.30453313
print("arr1 is\n",arr1) 0.20923577 0.77339378
0.884489]

arr3 = np.random.randint(1,16,4)
print("arr3 is\n",arr3) arr3 is [3 3 5 1]
#Check PPT exercises for examples.

You might also like