2/12/25, 4:57 AM Python_training(SCU)--Iman Mostafa
Python training
LAB1
In [1]: print(x)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[1], line 1
----> 1 print(x)
NameError: name 'x' is not defined
In [ ]: x=3
Print
In [ ]: t=4
print(t) # this code is for huihiuhiuhiuh
#print t
In [ ]: 2+3
In [8]: t=4.5 # not define variables
print("Python") #string
#print(type(t))
# print("hello",end=' * ')
print("WOrld")
Python
WOrld
In [11]: print('Hello',end='/')
#print("Hello students",end=' # ') #shift+enter # default value of end (\n)
print('all')
Hello/all
In [ ]: print('Hello World',end=' huhuhu ')
print('Hi all')
In [14]: print('year', 'month', 'day',sep='/')#,end=' #')
#print('Hi all')
year/month/day
In [ ]: 'Hello World'
"Hello World"
print('''Hello World''')
localhost:8888/lab/tree/Documents/Python Scripts/Advanced AI(prac)/Python_training(SCU)--Iman Mostafa.ipynb 1/15
2/12/25, 4:57 AM Python_training(SCU)--Iman Mostafa
In [ ]: print('My name is \nAli')
In [ ]: print(r'My name is \n Ali')
In [16]: x='''my name is ay haga and igjklkjhkjhkh
vjvhjkkjhkjh'''
print(x)
my name is ay haga and igjklkjhkjhkh
vjvhjkkjhkjh
Variables
names can not start with a number
names can not contain spaces, use _ instead
In [18]: a=2 #case sensitive
c=a+3
print(c)
In [ ]: Ahmed_r=10
print(Ahmed_r)
In [ ]: #Case sensitive
a=3
A=5
#b=2
print(a+b)
In [ ]: $t=7
print($t)
In [ ]: x=3
x='hamada'
print(x)
print(type(x))
In [ ]: val_1=9
print(val_1)
In [19]: # No defining for variables
x=True
y="56" #string
z=13.4
d= False #boolean
print(type (y))
#print(x)
#y
localhost:8888/lab/tree/Documents/Python Scripts/Advanced AI(prac)/Python_training(SCU)--Iman Mostafa.ipynb 2/15
2/12/25, 4:57 AM Python_training(SCU)--Iman Mostafa
<class 'str'>
In [ ]: x=3
y=5
g=complex(x,y)
print(g)
print(g.real)
g.imag
In [ ]: def= 3 #reserved words
print( def)
In [ ]: # define more than 1 var. in 1 line
s,a,r=13,'ahmed',8.5
#s=13,a=8
print(a,s)
type(a)
In [21]: #Convert from a type to another
#print (int(r))
a=3
print(float(a)) #casting
#type(a)
3.0
String
In [ ]: #Long string
x='my name is ..... and iam from egypt jjjjjjkj \
jiojoijoijoijoijjiojo'
print(x)
In [ ]: x='''i love programming and i am workining in scu gggggggh
fhjjhgkjjkhjkhljk'''
print(x)
In [27]: print("Training" \n *5)
print("Ahm\ned")
#print("ttt")
#print( 3* True)
Cell In[27], line 1
print("Training" \n *5)
^
SyntaxError: unexpected character after line continuation character
In [23]: #Concatentation
x='I'+ ''+'Love'+" -------- "+'python'
print(x)
ILove -------- python
localhost:8888/lab/tree/Documents/Python Scripts/Advanced AI(prac)/Python_training(SCU)--Iman Mostafa.ipynb 3/15
2/12/25, 4:57 AM Python_training(SCU)--Iman Mostafa
In [ ]: x='SUEZ canal University'
#print(len(x))
#print(x.lower()) #change to lowercase
#print(x.upper())
# print(x.split(' '))
# # print(x)
# print(x.capitalize()) #capitalize first letter
# print(x.lower().count('e'))
print(x.rfind('canal'))
x.swapcase())
#print(x.islower())
print(x[-3])
#printlen(x)-1)
In [ ]: print(x[-3]) #index
Casting
In [ ]: z=int(3.5)
print(z)
In [ ]: x=float(1)
x
Math. Operations
# | Symbol | Task Performed | # |----|---| # | + | Addition | # | - | Subtraction | # | / | division | # | % | mod | # | * | multiplication | # | // |
floor division | # | ** | to the power of | pow(x,y)
In [ ]: a= 3
b=4
print(a+b)
pow(2,3)
In [ ]: #Division
y=4//3 #python2--- 1
print(y)
print(3%2) #modulo
In [29]: #Combining the previous 2 operations(division+modulus)
x=divmod(2,2)
print(x)
(1, 0)
In [36]: pow(2,3)
m.sqrt(4)
Out[36]: 2.0
localhost:8888/lab/tree/Documents/Python Scripts/Advanced AI(prac)/Python_training(SCU)--Iman Mostafa.ipynb 4/15
2/12/25, 4:57 AM Python_training(SCU)--Iman Mostafa
In [34]: # print(4*2)
# print(4**2)
import math as m
# a=pow(4,2)
# print(a)
In [ ]: #For conditions or loops
x=2
z=3
#z=x
print(z>x)
#print(z>x)
In [ ]: x=-2
print(abs(x)) #absolute
In [ ]: !pip install math #for installing any library
In [ ]: import math as m
print(math.sqrt(4))
In [ ]: b=m.factorial(4)
print(b)
In [ ]: import math as m
import numpy as np #alias
#import pandas #as pd
In [ ]: import math as m
import numpy as np
print(m.sqrt(4))
# m.exp()
# m.log()
m.sin((30)) # must change to radian
In [ ]: a=30
b=40
print(a==b)
In [ ]: s=10
s+=1
In [ ]: print(math.ceil(3.00001)) # approx. to the higher no.
In [ ]: print(math.floor(3.6))
Input
In [41]: x=int(input("write your age: "))
localhost:8888/lab/tree/Documents/Python Scripts/Advanced AI(prac)/Python_training(SCU)--Iman Mostafa.ipynb 5/15
2/12/25, 4:57 AM Python_training(SCU)--Iman Mostafa
In [42]: type(x)
Out[42]: int
In [ ]: y=int(input("No. of children you have"))
In [ ]: z=x+1
print(z)
In [ ]: type(y)
Data structure (Lists-Tuple-Sets-Dictionary)
1- Lists
A list is a data structure in Python that is a mutable, or changeable, ordered sequence of
elements.
In [46]: list1=[1,22,'hi',3.5] #square brackets
print(len(list1))
type(list1)#show how many items in the list
4
Out[46]: set
In [ ]: #in and not in
3.5 in list1
In [ ]: 'hi' not in list1
In [ ]: bicycles = [3, 'cannondale', 'redline', 'specialized']
bicycles[0].capitalize()
Indexing
In [50]: list1=[1,22,'mona',3.5,'hi']
print(list1[2][1])
#print(list1[2][2])
#print(list1[-1])
In [54]: print(list1[1:3])
list1[0]=2 #modify no1 to no2
# print(list1)
#x=list1[:4]
localhost:8888/lab/tree/Documents/Python Scripts/Advanced AI(prac)/Python_training(SCU)--Iman Mostafa.ipynb 6/15
2/12/25, 4:57 AM Python_training(SCU)--Iman Mostafa
#print(x)
# list1[1:4] #get all the items from index 1 to the end of the list
[1, 22, 'mona']
In [ ]: print(list1[-2] ) #get the last element
#another method
#print(list1[len(list1)-1])
Modifying list
In [ ]: list1[0]=44
print(list1)
In [ ]: a=[1,2,3,5,6,7,8,9,'mohamed']
#print(a[:-2] ) #ignore the last 2 elements a[-2]
# print(a[-2])
#print(sum(a)) # on numbers only
#print(max(a)) # on letters or numbers (not both of them)
b=['a','A','y','b'] #arrange by asci code
c=['Mona','mohamed','farida']
print(max(c))
In [ ]: print(a)
a[2]=5
print(a)
In [ ]: a=[1,2,3,5,6,7,8,9,'mohamed']
a[:2]=[]
a
print(len(a))
print(a)
In [ ]: y="Greetings all"
print(y[10])
In [ ]: x=3.5
int(x)
In [ ]: x=list('Engineering') #type casting
print(x)
len(x)
In [ ]: #concatenate two lists
a=[1,2,3,5,6,7,8,9,'mohamed']
b=[10,11]+a
print(b)
#print(a)
In [ ]: c='ahmed'
d=3
localhost:8888/lab/tree/Documents/Python Scripts/Advanced AI(prac)/Python_training(SCU)--Iman Mostafa.ipynb 7/15
2/12/25, 4:57 AM Python_training(SCU)--Iman Mostafa
f=c+str(d)
print(f)
Sort and sorted
In [ ]: my_list=[3,11,4,9]
my_list.sort(reverse=True) #default value is False
a=sorted(my_list)#,reverse=True) # my_list remains the same
print(my_list)
print(a)
In [ ]: list3=['mona','ali','rana','nader','Mona']
#sorted(list3) doesnt affect the actual order of the list
#list3
list3.sort()
list3
In [ ]: # reverse
my_list=[3,11,4,9]
my_list.reverse()
# a
print(my_list)
In [ ]: #Looping through the list
magicians = ['alice', 'david', 'carolina']
for m in magicians:
print(m)
for i in range(1,5):
print(i**2)
In [ ]: squares = [] # create empty list named squares
for value in range(1, 11): #value is the counter
sq = value ** 2 #squares=[1,4]
squares.append(sq)
print(squares)
List comprehension
A list comprehension combines the
for loop and the creation of new elements into one line, and automaticall appends each new
element.
In [ ]: squares = [value**2 for value in range(1, 11)]
print(squares)
In [ ]: my_foods = ['pizza', 'falafel', 'carrot cake']
friend_foods = my_foods[:]
localhost:8888/lab/tree/Documents/Python Scripts/Advanced AI(prac)/Python_training(SCU)--Iman Mostafa.ipynb 8/15
2/12/25, 4:57 AM Python_training(SCU)--Iman Mostafa
print("My favorite foods are:")
print(my_foods)
print("\nMy friend's favorite foods are:")
print(friend_foods)
In [ ]: my_foods.append('cannoli')
friend_foods.append('ice cream')
In [ ]: my_foods = ['pizza', 'falafel', 'carrot cake']
friend_foods = my_foods
print("My favorite foods are:")
print(my_foods)
print("\nMy friend's favorite foods are:")
print(friend_foods)
In [ ]: my_foods.append('cannoli')
friend_foods.append('ice cream')
In [ ]: from operator import itemgetter
a=[('mona',12),('ahmed',20),('eyad',6)]
y=sorted(a,key=itemgetter(0))
print(y)
In [ ]:
append and extend
append : adds an element to the end of a list
extend : adding all items of list2 (passed as an argument) to the end of
the list1
In [ ]: #Difference between extend or append
x=[1,2,3]
y=[4,5,6]
x.append(y) # y remains the same
#x.extend(y)
#print(x)
# print(z)
#print(x[3][1])
In [ ]: print(x)
In [ ]: y.insert(1,'im') #(index,obj)
print(y)
In [ ]: s=[1,3,4,1,5,6,8,5,5,5]
print(s.count(5))
print(s.index(3))
localhost:8888/lab/tree/Documents/Python Scripts/Advanced AI(prac)/Python_training(SCU)--Iman Mostafa.ipynb 9/15
2/12/25, 4:57 AM Python_training(SCU)--Iman Mostafa
In [ ]: f=list(range(1,12,2) ) #(start,end,step)
f
In [ ]: a=['a','v','c']
b=a
#print(b)
a.extend('d')
print(a,b)
In [ ]: a=[1,'Mona']
print(a)
In [ ]: #To solve the previous issue
b=a
#a.extend('d')
print(a)
print(b)
a=[3]
print(a)
print(b)
In [ ]: motorcycles = [] #create empty list
motorcycles.append('honda')
motorcycles.append('yamaha')
motorcycles.append('suzuki')
print(motorcycles)
Remove items from the list
In [ ]: #del (by index)
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
del motorcycles[0]
print(motorcycles)
In [ ]: #pop
motorcycles = ['honda', 'yamaha', 'suzuki']
x=motorcycles.pop() #removes last elemsnt in the list by default (by index)
In [ ]: motorcycles
print(x)
In [ ]: # Remove (by value)
motorcycles.remove('honda')
print(motorcycles)
2-TUPLES
Tuples are used if you want your code to be more secure or unchangable(immutable)
localhost:8888/lab/tree/Documents/Python Scripts/Advanced AI(prac)/Python_training(SCU)--Iman Mostafa.ipynb 10/15
2/12/25, 4:57 AM Python_training(SCU)--Iman Mostafa
In [ ]: t=(1,2,'a',1,2,2)
#t= 1,2,'a',1
print(type(t))
print(len(t))
t.count(2)
In [ ]: #t[0]=2 #tuple is not mutable
t.append(1) # tuple has no append or insert
print(t)
In [ ]: t1=('2.5',) #not a tuple
#t1=(1,) #tuple
type(t1)
In [ ]: a=()
type(a)
In [ ]: t3=(2,5,4,6)
print(t3[3]) # take care of the brackets when indexing the tuple
In [ ]: t4=list(t3)
print(t4)
print(t3)
# t3
#t4[0]=3
# print(t4)
# print(t3)
# t3=tuple(t4)
print(t4)
In [ ]: tup=('mona','ali','rana','nader')
#x=" ".join(tup)
#print(x)
#sort(tup)
tup1=list(tup)
print(tup1)
tup1.sort()
#tup2=tuple(tup1)
print(tup1)
In [ ]: a=[('mona',12,'egypt'),('ahmed',20,'iran'),('eyad',6,'hhh')] # list of tuples
y=sorted(a,key=lambda e:e[2])#,reverse=True)
y
Sets
No repeated items{}
In [ ]: p={1,5,8,8,5,7,0}
print(p)
#p[0] #error
localhost:8888/lab/tree/Documents/Python Scripts/Advanced AI(prac)/Python_training(SCU)--Iman Mostafa.ipynb 11/15
2/12/25, 4:57 AM Python_training(SCU)--Iman Mostafa
In [ ]: max(p)
In [ ]: p={1,5,8,8,5,7,0}
x={3,1,5,9}
In [ ]: print(p|x) #p.union(x)
print(p & x) # intersection
print(p^x) #exclude the same items
4- DICTIONARIES
A Python dictionary consists of a key and then an associated value. my_dict =
{'key1':'value1','key2':'value2'}
In [ ]: dict1= {"brand": "Ford", "model": " mostage","year": 1964 }
print(type(dict1))
len(dict1)
In [ ]: dict1['Model']
#dict1['year']=2000
#print(dict1)
In [ ]: # del (dict1["brand"])
# print(dict1)
#dict1.pop("year")
dict1
dict1.popitem()
dict1
In [ ]: dict2={ "key1": 4, "key2": "hello", "key3": [3,6,8] }
dict2['key3'][1]
In [ ]: #change value in the dictionary or add a new one
dict2['key4']=2000
#print(dict2.items())
print(dict2.keys())
print(dict2.values())
In [ ]: k=list(dict2.items())
print(k)
In [ ]: dict2['key5']
In [ ]: dict2.get('key5','60')
dict2
localhost:8888/lab/tree/Documents/Python Scripts/Advanced AI(prac)/Python_training(SCU)--Iman Mostafa.ipynb 12/15
2/12/25, 4:57 AM Python_training(SCU)--Iman Mostafa
In [ ]: dict1.clear()
dict1['salary']=5000
dict1['salary']='iman'
dict1
In [ ]: del(dict2)
print(dict2)
In [ ]: d={} #empty dictionary
# d['name']='Ahmed'
# d['age']=30
print(d)
type(d)
In [ ]: d['name']='Mona'
d
In [ ]: b = dict(one=[1,3], two=2, three=3)
b
In [ ]: c = dict([('one', [1,2]), ('three',2),('two', 2)]) #dict with list of tuples
c
In [ ]: d = dict(zip(['one', 'two', 'three'], [[1,7], 2, 3]))
d
In [ ]: #Dict. methods
#d.items()
b.keys()
#b.values()
In [ ]: L=['sayed','soha','alaa','mohamed']
d=dict.fromkeys(L)
d
d['sayed']=40
d
Control statements
In [ ]: x = 11
if 10 < x < 13:
print("hello") #indentation
print(x+1)
else:
print("world")
In [ ]: for i in range(1,10,2): #(start,stop,step)
print(i)
In [ ]: data=[2,3,'r',9.9]
for j in data[:]:
localhost:8888/lab/tree/Documents/Python Scripts/Advanced AI(prac)/Python_training(SCU)--Iman Mostafa.ipynb 13/15
2/12/25, 4:57 AM Python_training(SCU)--Iman Mostafa
print(j)
In [ ]: i = 0
while i < 3:
print(i ** 2)
i++
print('Bye')
In [ ]: for i in range(10):
#print(i)
if i==7:
break
print(i)
Functions
There are two types of functions: 1- Built-in function 2- User-defined function
In [ ]: # Built-in function # numpy #pandas
len()
x=int(4.5)
str()
bool
type
In [ ]: #user defined function
def my_func():
print('Hello')
my_func() #calling
When the function results in some value and that value has to be stored in a variable or
needs to be sent back or returned for further operation to the main algorithm, a return
statement is used.
In [ ]: def times(x,y):
z = x*y
return z
In [ ]: times(3,3)
In [ ]: def add(*args):
x=0
for i in args:
x=x+i
print(x)
add(1,2)
localhost:8888/lab/tree/Documents/Python Scripts/Advanced AI(prac)/Python_training(SCU)--Iman Mostafa.ipynb 14/15
2/12/25, 4:57 AM Python_training(SCU)--Iman Mostafa
Lambda function
lambda is anonymous function (function defined without a name)
used when you require a nameless function
have only one expression but can have any no. of arguments
In [ ]: s = lambda y: y*8
s(2)
In [ ]: r= lambda x,y:x**y
r(3,4)
Creating files
In [ ]: file = open(r'C:\Iman\SCU\summer_training\nada.txt', "w") # create new file and wri
file.write(" second year" )
file.close()
In [ ]: file = open(r'C:\Iman\SCU\summer_training\nada.txt', "a") #write file without delet
file.write("\n my name is mohamed" )
file.write('iam 30 years old')
file.close()
In [ ]: file = open(r'C:\Iman\SCU\summer_training\nada.txt', "r") #write file without delet
# for i in file:
# print (i)
x=file.read()
file.close()
x
In [ ]: # create folders
import os
os.makedirs('C:\Iman\SCU\summer_training\Course',exist_ok=False) # overwrite
In [ ]: # check the availability of a file or folder
s=os.path.exists('C:\Iman\SCU\summer_training\Courses')
s
localhost:8888/lab/tree/Documents/Python Scripts/Advanced AI(prac)/Python_training(SCU)--Iman Mostafa.ipynb 15/15