2/12/25, 11:31 AM Python--Iman Mostafa
Python training
In [ ]: x=3
In [ ]: print(X)
Comments
In [4]: #this part of project is about addition kjkugyfjyfjutdtdktdkutdku
x=3+3
print(x)
In [4]: """
This is a comment
written in
more than just one line
"""
print("Hello, World!")
Out[4]: ' \nThis is a comment\nwritten in\nmore than just one line\n'
In [ ]: print(4)
Print
In [ ]: t=4
print(t) # this code is for huihiuhiuhiuh
#print t
In [5]: print(5)
print(2) #indentation
5
2
In [ ]: print(5+2)
print("5+2")
In [7]: print("2+3 =",2+3)
2+3 = 5
In [ ]: print(2+3)
Print several things
localhost:8888/lab/tree/Documents/Python Scripts/Advanced AI(prac)/Python--Iman Mostafa.ipynb 1/15
2/12/25, 11:31 AM Python--Iman Mostafa
In [ ]: # print several things
print('The value of 3+4 is', 3+4)
print('A', 1, 'XYZ', 2)
Optional arguments
There are 2 optinal arguments in print:
end
sep
In [9]: print('Hello World',end='#')
print("Hello students")
Hello World#Hello students
In [ ]: print('Hello World',end='\n')
print("Hello students") #shift+enter # default value of end (\n)
In [ ]: print('Hello World',end=' ')
print("Hello students") #shift+enter
print('Hi all')
In [ ]: t='ahmed' # not define variables
print(t) #string
type(t)
print("hello",end=' * ')
print("World")
In [17]: print('year', 'month', 'day',sep=' ',end=' ')
print('Hi all')
year month day Hi all
In [ ]: print ('The value of 3+4 is', 3+4, '.')
print ('The value of 3+4 is ', 3+4, '.', sep='')
In [ ]: 'Hello World'
"Hello World"
print('Hello World")
In [ ]: print('My name is \nAli')
In [ ]: print(r'My name is \n Ali')
In [ ]: x=''my name is ay haga and igjklkjhkjhkh
vjvhjkkjhkjh''
print(x)
Getting input
localhost:8888/lab/tree/Documents/Python Scripts/Advanced AI(prac)/Python--Iman Mostafa.ipynb 2/15
2/12/25, 11:31 AM Python--Iman Mostafa
In [ ]: name = input('Enter your name: ')
print('Hello, ', name)
In [ ]: type(name)
In [ ]: num = input('Enter a number: ') #eval converts text to number
print('Your number squared:', num)
print(type(num))
In [ ]: num = eval(input('Enter a number: ')) #eval converts text to number
print('Your number squared:', num*num)
print(type(num))
In [ ]: y=int(input("No. of children you have"))
In [ ]: type(y)
In [ ]: x=int(input("write your name: "))
In [ ]: z=x+1
print(z)
Variables
names can not start with a number
names can not contain spaces, use _ instead
In [ ]: Ahmed_r=10
print(Ahmed_r)
In [ ]: #Case sensitive
a=3
A=5
#b=2
print(a+b)
In [7]: _t=7
print(_t)
In [ ]: x=3
x='hamada'
print(x)
print(type(x))
In [ ]: val_1=9
print(val_1)
localhost:8888/lab/tree/Documents/Python Scripts/Advanced AI(prac)/Python--Iman Mostafa.ipynb 3/15
2/12/25, 11:31 AM Python--Iman Mostafa
In [8]: # No defining for variables
x=True
y="ahmed" #string
z=13.4
d= False #boolean
print(type (z))
print(x)
#y
<class 'float'>
True
In [ ]: x=3
y=5
g=complex(x,y)
print(g)
print(g.real)
g.imag
In [ ]: def= 3 #reserved words can't be variable names
print( def)
In [ ]: # define more than 1 var. in 1 line
s,a,r=13,'ahmed','8'
#s=13,a=8
print(a,s)
type(a)
Casting
Implicit
Explicit
In [11]: #Convert from a type to another
#Explicit
a=3.5
print('before',type(a))
c=int(a)
print(int(a)) #casting
type(c)
before <class 'float'>
3
Out[11]: int
String
In [ ]: #Long string
x='my name is ..... and iam from egypt jjjjjjkj \
localhost:8888/lab/tree/Documents/Python Scripts/Advanced AI(prac)/Python--Iman Mostafa.ipynb 4/15
2/12/25, 11:31 AM Python--Iman Mostafa
jiojoijoijoijoijjiojo'
print(x)
In [ ]: x='''i love programming and i am workining in scu gggggggh
fhjjhgkjjkhjkhljk'''
print(x)
In [ ]: print("Training \n" *5)
#print("ttt")
#print( 3* True)
In [ ]: #Concatentation
x='I'+ ' '+'Love'+" -------- "+'python'
print(x)
In [ ]: x='SUEZ canal University'
#print(len(x))
#print(x.lower())
#print(x.upper())
# print(x.split(' '))
# # print(x)
# print(x.capitalize())
# 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
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 |
In [ ]: a= 3
b=4
print(a+b)
pow(2,3)
In [ ]: #Division
y=4//3 #python2--- 1
print(y)
print(3%2) #modulo
localhost:8888/lab/tree/Documents/Python Scripts/Advanced AI(prac)/Python--Iman Mostafa.ipynb 5/15
2/12/25, 11:31 AM Python--Iman Mostafa
In [ ]: #Combining the previous 2 operations(division+modulus)
x=divmod(3,2)
print(x)
In [ ]: print(4*2)
print(4**2)
import math
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
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
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))
localhost:8888/lab/tree/Documents/Python Scripts/Advanced AI(prac)/Python--Iman Mostafa.ipynb 6/15
2/12/25, 11:31 AM Python--Iman Mostafa
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 [ ]: list1=[1,22,'hi','3.5'] #square brackets
print(len(list1))
#
type(list1)#show how many items in the list
In [ ]: #in and not in
'3.5' in list1
In [ ]: 'hi' not in list1
In [ ]: #indexing
#print(list1[2])
print(list1[2][1])
In [ ]: #list1=[1,22,'hi','3.5']
x=234
x[0]
#print(list1[len(list1)-1])
In [ ]: list1[1:3]
#x=list1[:7]
#print(x)
# list1[1:4] #get all the items from index 1 to the end of the list
In [ ]: print(list1[-1] ) #get the last element
#another method
#print(len(list1)-1)
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
print(min(b))
In [ ]: print(a)
a[2]=5
print(a)
In [ ]: #a[:2]=[]
a
localhost:8888/lab/tree/Documents/Python Scripts/Advanced AI(prac)/Python--Iman Mostafa.ipynb 7/15
2/12/25, 11:31 AM Python--Iman Mostafa
print(len(a))
print(a)
In [ ]: #del a[2] #by index
# a
#a.remove(5) #by object
y=a.pop(2) #by index
a
print(y)
In [ ]: y="Greetings all"
print(y[0])
In [ ]: x=list('Engineering')
print(x)
In [ ]: #concatenate two lists
b=[1,2]+a
print(b)
#print(a)
In [ ]: c='ahmed'
d=3
f=c+str(d)
f
Sort and sorted
In [ ]: my_list=[3,11,4,9]
my_list.sort(reverse=False) #default value is False
# b=[3,11,4,9]
# a=sorted(b) # my_list remains the same
#my_list.reverse()
# a
print(my_list)
In [ ]: list3=['mona','ali','rana','nader']
sorted(list3)
list3
list3.sort()
list3
In [ ]: from operator import itemgetter
a=[('mona',12),('ahmed',20),('eyad',6)]
y=sorted(a,key=itemgetter(0))
print(y)
append and extend
append : adds an element to the end of a list
localhost:8888/lab/tree/Documents/Python Scripts/Advanced AI(prac)/Python--Iman Mostafa.ipynb 8/15
2/12/25, 11:31 AM Python--Iman Mostafa
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)
# z= 9 in x
# # z
# print(z)
#print(x[3][1])
In [ ]: y.insert(1,11) #(index,obj)
y
In [ ]: s=[1,3,4,1,5,6,8,5,5,5]
print(s.count(5))
print(s.index(5))
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)
2-TUPLES
Tuples are used if you want your code to be more secure or unchangable(immutable)
In [ ]: t=(1,2,'a',1)
t= 1,2,'a',1
print(type(t))
localhost:8888/lab/tree/Documents/Python Scripts/Advanced AI(prac)/Python--Iman Mostafa.ipynb 9/15
2/12/25, 11:31 AM Python--Iman Mostafa
print(len(t))
#t.count(2)
In [ ]: t[0]=2 #tuple is not mutable
# t.append(1) # tuple has no append or insert
# t
In [ ]: t1=(2,) #not a tuple
#t1=(1,) #tuple
type(t1)
In [ ]: a=()
type(a)
In [ ]: t3=(2,5,4,6)
print(t3[0]) # take care of the brackets when indexing the tuple
In [ ]: t4=list(t3)
print(t4)
# t3
t4[0]=3
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(tup2)
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
In [ ]: max(p)
In [ ]: x={3,1,5,9}
In [ ]: print(p|x) #p.union(x)
print(p & x) # intersection
localhost:8888/lab/tree/Documents/Python Scripts/Advanced AI(prac)/Python--Iman Mostafa.ipynb 10/15
2/12/25, 11:31 AM Python--Iman Mostafa
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 [80]: dict1= { "brand": "Ford", "model": "Mustang", "year": 2000}
#print(type(dict1))
print(len(dict1))
#x=[2,4,6]
#x[0]=3
In [71]: #dict1[0]
dict1['year']=1999
# print(dict1.keys())
# print(dict1.values())
# print(dict1.items())
print(dict1)
{'brand': 'Ford', 'model': 'Mustang', 'year': 1999}
In [82]: dict1['brands']
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
Cell In[82], line 1
----> 1 dict1['brands']
KeyError: 'brands'
In [78]: #del (dict1["brand"])
# print(dict1)
x=dict1.pop('model')
# # dict1
# # dict1.popitem()
print(dict1)
print(x)
{}
Mustang
In [17]: dict2={ "key1": 4, "key2": "hello", "key3": [3,6,8] }
dict2['key3'][1]
Out[17]: 6
In [21]: #change value in the dictionary or add a new one
#dict2['key4']=2000
print(dict2.items())
print(dict2.keys())
print(dict2.values())
localhost:8888/lab/tree/Documents/Python Scripts/Advanced AI(prac)/Python--Iman Mostafa.ipynb 11/15
2/12/25, 11:31 AM Python--Iman Mostafa
dict_keys(['key1', 'key2', 'key3'])
dict_values([4, 'hello', [3, 6, 8]])
In [ ]: k=list(dict2.items())
print(k)
In [26]: dict2['key5']
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
Cell In[26], line 1
----> 1 dict2['key5']
KeyError: 'key5'
In [87]: #dict1['brands']
print(dict1.get('brands','sorry,this is wrong'))
print(dict2)
sorry,this is wrong
{'key1': 4, 'key2': 'hello', 'key3': [3, 6, 8]}
In [89]: #dict1.clear()
dict1['salary']=5000
dict1['name']='iman'
print(dict1)
{'salary': 5000, 'name': 'iman'}
In [91]: #del(dict1)
dict1['salary']=5000
dict1['name']='iman'
print(dict1)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[91], line 2
1 #del(dict1)
----> 2 dict1['salary']=5000
3 dict1['name']='iman'
4 print(dict1)
NameError: name 'dict1' is not defined
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
localhost:8888/lab/tree/Documents/Python Scripts/Advanced AI(prac)/Python--Iman Mostafa.ipynb 12/15
2/12/25, 11:31 AM Python--Iman Mostafa
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[:]:
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
localhost:8888/lab/tree/Documents/Python Scripts/Advanced AI(prac)/Python--Iman Mostafa.ipynb 13/15
2/12/25, 11:31 AM Python--Iman Mostafa
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)
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
localhost:8888/lab/tree/Documents/Python Scripts/Advanced AI(prac)/Python--Iman Mostafa.ipynb 14/15
2/12/25, 11:31 AM Python--Iman Mostafa
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
In [1]: import tensorflow as tf
from tensorflow.keras.datasets import imdb
In [2]: top_words = 5000
(X_train, y_train), (X_test, y_test) = imdb.load_data(num_words=top_words)
In [10]: import numpy as np
np.size(X_train[0])
Out[10]: 218
In [9]: import numpy as np
np.size(X_train[1])
Out[9]: 189
In [14]: X_train.shape
Out[14]: (25000,)
In [ ]:
localhost:8888/lab/tree/Documents/Python Scripts/Advanced AI(prac)/Python--Iman Mostafa.ipynb 15/15