Python Notes Fixed
Python Notes Fixed
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 5: End
PSEUDOCODE
Step 4: End
PSEUDOCODE
Step 3: Print I
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
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
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"]
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
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?
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')
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'])
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.
_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()
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
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])
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]])
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]
[[-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]]
arr3 = np.random.randint(1,16,4)
print("arr3 is\n",arr3) arr3 is [3 3 5 1]
#Check PPT exercises for examples.