Python
Python
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!")
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")
2+3 = 5
In [ ]: print(2+3)
Optional arguments
There are 2 optinal arguments in print:
end
sep
In [ ]: print('Hello World',end='\n')
print("Hello students") #shift+enter # default value of end (\n)
In [ ]: 'Hello World'
"Hello World"
print('Hello World")
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 [ ]: type(name)
In [ ]: type(y)
In [ ]: z=x+1
print(z)
Variables
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)
<class 'float'>
True
In [ ]: x=3
y=5
g=complex(x,y)
print(g)
print(g.real)
g.imag
Casting
Implicit
Explicit
String
In [ ]: #Long string
x='my name is ..... and iam from egypt jjjjjjkj \
jiojoijoijoijoijjiojo'
print(x)
In [ ]: #Concatentation
x='I'+ ' '+'Love'+" -------- "+'python'
print(x)
# 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
In [ ]: print(4*2)
print(4**2)
import math
a=pow(4,2)
print(a)
In [ ]: x=-2
print(abs(x)) #absolute
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.floor(3.6))
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 [ ]: 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
print(len(a))
print(a)
In [ ]: y="Greetings all"
print(y[0])
In [ ]: x=list('Engineering')
print(x)
In [ ]: c='ahmed'
d=3
f=c+str(d)
f
In [ ]: list3=['mona','ali','rana','nader']
sorted(list3)
list3
list3.sort()
list3
a=[('mona',12),('ahmed',20),('eyad',6)]
y=sorted(a,key=itemgetter(0))
print(y)
the list1
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)
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))
print(len(t))
#t.count(2)
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)
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
4- DICTIONARIES
A Python dictionary consists of a key and then an associated value. my_dict =
{'key1':'value1','key2':'value2'}
In [71]: #dict1[0]
dict1['year']=1999
# print(dict1.keys())
# print(dict1.values())
# print(dict1.items())
print(dict1)
In [82]: dict1['brands']
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
Cell In[82], line 1
----> 1 dict1['brands']
KeyError: 'brands'
{}
Mustang
Out[17]: 6
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)
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)
In [ ]: d['name']='Mona'
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 [ ]: 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
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)
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
file.close()
file.close()
In [ ]: # create folders
import os
os.makedirs('C:\Iman\SCU\summer_training\Course',exist_ok=False) # overwrite
s=os.path.exists('C:\Iman\SCU\summer_training\Courses')
s
Out[10]: 218
Out[9]: 189
In [14]: X_train.shape
Out[14]: (25000,)
In [ ]: