Professional Documents
Culture Documents
releases
creative commons
.
https://www.linkedin.com/in/EngMa7moud3ly
https://www.facebook.com/EngMa7moud3ly
https://github.com/Ma7moud3ly
. ..
bug
stackoverflow
CIA
Pink Python..
intentionally blank page
0 ✓
1 ✓
Python Basics 2 ✓
Libraries 3 ✓
Data Storages 4 ✓
5 ✓
Web Applications 6 ✓
GUI 7 ✓
Programming_language
Pink Python
9
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
•
...
و
issues Github
10
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
Python ✓
11
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
Python
Python
language
scripting
. •
•
12
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
Tiobe Index
GitHub
13
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
: programming language
processors •
machine code
. ones zeroes
ADD MOV
location •
register
Assembly
14
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
High Level
Interpreted :
assembler
hexadecimal binary
High Level •
source code
15
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
assembler •
complier
. machine code
compile C •
Linux
compile •
executable •
platform compiled •
dependent
source code •
16
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
windows/linux/android/ios
interpreter •
interpreter script
compiler
machine code
scripting language
interpreted
.
general purpose
17
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
desktop application •
web application •
android/ios •
web scrapping •
Machine Learning AI •
Networking •
raspberrypi •
apps
18
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
Windows ✓
Linux ✓
IOS Android ✓
Python Online ✓
19
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
Interpreted
script
Windows
python
release 3
20
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
2.x 3.x
releases
2.X
3.X
3 3 2
2.7 which-python
2020
. 3
3 2
Python2orPython3
Short version: Python 2.x is legacy, Python 3.x is the present and future of the language
21
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
IDLE python
IDE
Integrated_development_environment
IDE
IDLE •
Python IDLE •
Interpreter
22
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
Linux
23
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
IOS Android
van Rossum
qpython qpython3
3 qpython3
Editor
24
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
Python Online
tutorialspoint execute_python_online
PythonAnyWhere •
Dashboard
25
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
Interactive Mode
chat Interpreter
console qpython •
python terminal •
IDLE
26
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
CMD
PythonAnyWhere
print •
Hello World
C++ Java
27
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
Python IDLE
Interactive interpreter
Qpython •
Editor
test.py
28
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
Code Editors
vscode notepdad++
CMD Terminal
vscode
code extensions
extensions editor
visualstudio
29
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
test.py py •
extension hint
extension reload
start debug •
script debugger
command line
30
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
command Line
Terminal
python script_name.py
test.py •
Command line
E test.py •
command line
31
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
PyCharm IDE
32
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
Python Basics
Operations ✓
Data types ✓
Numbers ✓
Strings ✓
Arrays ✓
Comments ✓
Functions ✓
OOP ✓
Making Decision ✓
Loop ✓
33
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
Arithmetic Operators
Interactive Interpreter •
>>> 5 + 5
10
>>> 5 * 5
25
>>> 5 - 5
0
>>> 10 / 5
2.0
>>> 5 % 2
1
>>> 5 ** 2
25
Operators •
Operands
34
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
/ << <<
1 •
10-16+7 10-2*8+7
8*8+7 8*8+7 2 10
64+7
3+2*4**2-30/2
35
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
Operator
Relational Operators
!=
> Operands
<
>= True
<=
False
>>> 5 == 5
5 5
True
>>> 5 != 4
4 5
True
>>> 5 < 6
6 5
True
>>> 5 > 7
7 5
False
>>> 3 <= 5
5 3
True
>>> 2 * 3 > 4
4 3 2
True
Math Operation •
36
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
Logical Operations
Logic gates
output input
1 0
logical operators
37
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
False True
False True
Interactive Interpreter ..
>>> 5+2 > 4-3 and not 1 > 3 7 > 1 and not False
True True and True = True
38
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
or and
False True
and •
or •
and •
or •
39
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
variables
values
Assigning Variables
variable_name = value
interpreter •
5 x
x •
40
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
identifiers
variable identifier
class function
identifier
identifier •
@#$% IDLE
. underscore _ •
reserved keywords •
identifiers
keywords •
41
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
>>> x = 2 x = 2
>>> y = 3
2 x
3 y
>>> x
2 call
>>> y y x
3
>>> x*y
6
>>> x+y * x-y
5
IDLE •
Multiple Assignment
42
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
Data Types
data
numbers -1
5j complex
strings -2
str string
Boolean -3
43
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
type
Variable type
Dynamically typed
False True x •
44
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
c/c++/java/c# •
statically typed
int x = 1 1 x
integer
Dynamically Typed •
complex .. float
int(value)
float(value)
complex(value)
complex(real,img)
45
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
int •
complex
Math
Math
Mathematical Functions
import
Modules
dir
46
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
>>> pi
pi
3.141592653589793
>>> sqrt(25)
5.0 sqrt
47
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
>>> round(10.12845,2)
10.13 round
>>> pi
3.141592653589793
>>> round(pi,2)
3.14
>>> sin(90)
0.8939966636005579
sin,cos,tan
>>> sin(radians(90))
1.0
radian
1 sin(90)
180
>>> x=radians(90)
>>> int(sin(x))
1
>>> int(cos(x))
0
Math
math
48
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
str string
>>> x = 5 int x
>>> y = '5'
str y
>>> type(x)
<class 'int'>
>>> type(y) y x
<class 'str'> error
>>> x + y
TypeError: unsupported operand
y
type(s) for +: 'int' and 'str'
>>> x + int(y) x
10
>>> str(x) + y
'55'
49
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
Multi-Line String
3 quote
escape character \n
print •
escape character
50
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
\n •
\n Hello\nWorld •
tab \t •
double/single quotes
>>> x = "Hello"world"
SyntaxError: invalid syntax
>>> x = 'Hello'world'
SyntaxError: invalid syntax
Hello
51
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
>>> x = "Hello\"world"
>>> x
'Hello"world'
>>> x = "Hello'world"
>>> x
Hello'world
strings
IDLE
command line
52
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
String Operation
Concatenation
str y x •
Repetition
Slicing
index •
H E L L O Hello ..
0 1 2 3 4
index
53
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
str[index] index
str[index:length]
Format
concatenation •
str •
formatting operator •
%s
54
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
quote •
%s
>>> x = 120
>>> "the number is %s students"%x
'the number is 120 students'
>>> name,age,phone='Mahmoud',23,'011'
>>> x="Name : %s\nAge : %s\nPhone : %s"%(name,age,phone)
>>> print(x)
Name : Mahmoud
Age : 23
Phone : 011
String functions
>>> x.upper()
capital upper
'PINK PYTHON'
>>> x small lower
'Pink Python' lower upper
>>> x = x.upper()
>>> x
'PINK PYTHON'
>>> x.lower()
'pink python'
assignment
>>> x
'PINK PYTHON' var = var.upper()
55
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
>>> x find
'PINK PYTHON'
index
>>> x.find('k')
-1 1
>>> x.find('K') k 1
3 K
>>> x
'PINK PYTHON'
>>> x.startswith('P')
True stratswith
>>> x.endswith('n')
False
>>> x.endswith('N') False True
True endswith
>>>
x.endswith('PYTHOn')
False
>>>
x.endswith('PYTHON')
True
string
56
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
index
array
dictionary tuple
List
list
>>> x = [1,'Hi',True]
>>> type(x) 3 x list
<class 'list'>
57
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
>>> x = [0,1,2,3,4,5]
>>> x[0:1]
[0]
>>> x[0:3] List_name[start:start+length]
[0, 1, 2]
>>> x[1:3] 0,1,2,3,4,5
[1, 2] 1 1 321
>>> x[3:5] 4 3 1 3
[3, 4]
>>> x[1:4] x[1:4]
[1, 2, 3]
>>> y = ['a','b','c']
>>> x = [1,True,y] list List
>>> x y 3 y
[1, True, ['a', 'b', 'c']] x
>>> x[2] 0
['a', 'b', 'c']
x 2
>>> x[2][0]
x[2][0]
'a'
>>> type(x[2])
<class 'list'> xx=x[2]
xx[0]
>>> x = [1,2,4,-2,4,1,5]
>>> len(x)
7 len
>>> max(x)
5 max
>>> min(x) mix
-2
58
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
>>> x
[1, 2, 4, -2, 4, 1, 5, 10]
insert
>>> x.insert(0,-5)
>>> x
[-5, 1, 2, 4, -2, 4, 1, 5, 10]
>>> x.insert(4,-9)
>>> x
[-5, 1, 2, 4, -9, -2, 4, 1, 5, 10]
>>> x.sort()
sort
>>> x
[-5, -5, -2, 1, 1, 2, 4, 4, 5, 10]
>>> x.sort(reverse=True)
>>> x
sort(reverse=True)
[10, 5, 4, 4, 2, 1, 1, -2, -5, -5]
>>> x
[10, 5, 4, 4, 2, 1, 1, -2, -5, -5] index
>>> x.index(2)
4
>>> x
[10, 5, 4, 4, 2, 1, 1, -2, -5, -5] count
>>> x.count(-5)
2
59
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
tuples
tuples list
list •
list_name = [data,data,data]
tuples •
tuple_name = (data,data,data)
tuple list •
list_name [index]
tuple_name [index]
tuples !
>>> x = [1,2,3]
>>> y = (1,2,3)
>>> type(x)
<class 'list'>
>>> type(y)
<class 'tuple'>
>>> x
[1, 2, 3]
60
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
>>> x[0]=-1
>>> x
[-1, 2, 3]
>>> y
(1, 2, 3)
>>> y[0]=-1
TypeError: 'tuple' object does not support item assignment
Dictionary
dictionary
index
{ } curly brackets
key value
dict_name['key_name']
61
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
dicts
>>> x = {'name':'Mahmoud','age':23,'country':'Egypt'}
>>> type(x)
<class 'dict'>
>>> x['name']
'Mahmoud'
>>> x['age']
23
>>> x['country']
'Egypt'
>>> x[0]
KeyError: 0
>>> x['Age']
KeyError: 'Age'
KeyError Age •
case sensitive
>>> x = {'color1':'red',
'color2':'green','color3':'blue'} dict value
>>> x['color1'] get
'red' dict.get('key')
>>> x.get('color1') dict['key']
'red'
>>> x['color3']='yellow'
>>> x dict value
{'color1': 'red', 'color2': key assignment
'green', 'color3': 'yellow'}
62
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
>>> x.pop('color4')
'orange'
>>> x.pop('color3') dict key
'yellow'
key pop
>>> x
{'color1': 'red', 'color2':
'green'}
>>> 'color1' in x
True dict key
>>> 'color3' in x True in
False
False
data structures
63
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
interpreter
hash •
''' """
comment1 comment1
Comment2 Comment2
Comment3 Comment3
Comment.. Comment..
''' """
64
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
print(1) 1
#print(2) 3
print(3); print(4); #print(5) 4
'''
print('you')
print("can't")
print('see')
print('Me :3')
'''
65
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
function
list print
dict tuple
inputs
output
data
built-in functions
66
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
x datatypes
len(x)
x.reverse() reverse
؟
x x reverse •
List •
object
call function
call
comma arguments
return type
print
67
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
function_name(arg1,arg2,arg…)
variable=function_name(arg1,arg2,arg…)
arguments •
parameter
68
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
interpreter
interpreter
print output
#print Hi
print('Hi') # 123
print(123) # [1, 2, 3]
{'day1': 'sat', 'day2':
x = [1,2,3] 'sun'}
print(x) #list
1-My Name is: Mahmoud
y = {'day1':'sat','day2':'sun'}
print(y) #dict 2-My Name is:Mahmoud
3-My Age is: 23
name = "Mahmoud" # 4-My Age is: 23
# Traceback (most recent call
# last):
print("1-My Name is:",name)
print("4-My Name is:"+age)
TypeError: must be str, not
#
print("2-My Name is:"+name) int
age = 23 #
#
print("3-My Age is:",age)
#
print("4-My Age is: %s"%age)
#
print("4-My Name is:"+age)
69
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
input
run
input
input
enter
str
var=input()
var=input('Message')
input
>>> x = input()
Hi
>>> print(x)
Hi
>>> x = input('write something : ')
write something : Hello ^_^
>>> print(x)
Hello ^_^
input •
string
float int
70
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
print input
71
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
built in functions
interpreter
Function definition
interpreter def •
identifier •
keywords
interpreter colon •
72
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
.Code Blocks
block
c/c++ block
end
Block_(programming)
line indent
xx
5 1
73
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
def xx(): 1
print(1) 2
print(2)
3
print(3)
4
print(4)
5
print(5)
xx()
def xx():
print(1)
error
print(2)
print(3)
print(4)
print(5)
xx()
xx() call
undefined error
def xx():
print(1) xx interpreter
print(2)
NameError: name 'xx' is not
print(3)
defined
print(4)
print(5)
74
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
reusable
return type
len max
return type
return
75
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
print(add(100,300))
return •
result
print() •
. print result
76
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
parameters
parameters •
arguments
def name(par1,par2,par3,par4):
code…
name(arg1,arg2,arg3,arg4)
parameters argument
def name(par1,par2,..):
code…
name(par1=arg1,par2=arg2,..)
77
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
def xx(x,y,z): x = 1 , y = 2 , z =3
print("x = %s , y = %s , z =%s"%(x,y,z)) x = 1 , y = 1 , z =1
x = 3 , y = 2 , z =1
x=1 x = 1 , y = 2 , z =3
y=2
z=3
xx(x,y,z)
xx(x=x,y=x,z=x)
xx(z,y,x)
xx(z=z,y=y,x=x)
x,y,z x,y,z •
xx(x,y,z) •
xx(x=x,y=x,z=x) •
xx(x=1,y=2,z=3)
xx(3,2,1) xx(z,y,x) •
xx(x=3,y=2,z=1)
78
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
Scope of Variables
x,y,z x,y,z
scope
life cycle
x = 10
global variable x
local function
call variable
call
79
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
x=1 global x = 1
y=2 global y = 2
local x = 3
def xx(): local y = 4
x=3 again global x = 1
y=4 again global y = 2
print('local x = %s'%x) >>>
print('local y = %s'%y)
print('global x = %s'%x)
print('global y = %s'%y)
xx()
print('again global x = %s'%x)
print('again global y = %s'%y)
xx x=1,y=2 global •
x=3,y=4 local
global local
global local •
. global local
global var_name
80
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
x=1 global x = 1
y=2 global y = 2
local x = 3
def xx(): local y = 4
global x again global x = 3
x=3 # x become global again global y = 2
y=4 # y still local >>>
print('local x = %s'%x)
print('local y = %s'%y)
print('global x = %s'%x)
print('global y = %s'%y)
xx()
print('again global x = %s'%x)
print('again global y = %s'%y)
local y global x •
global x=3 •
81
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
object
classes
methods : class •
attributes
class ClassName:
variables...
functions()..
identifier class •
methods •
class variables •
object method
82
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
object object
self
class Animal:
name=''
pet=''
prey=''
enemy=''
talent=''
def __init__(self,name,pet,prey,enemy,talent):
self.name=name
self.pet=pet
self.prey=prey
self.enemy=enemy
self.talent=talent
def cv(self):
cv='name:%s\nis pet:%s\nprey:%s\nenemy:%s\ntalent:%s'%(
self.name,self.pet,self.prey,self.enemy,self.talent)
print(cv)
def on_danger(self):
print('''when (%s) attacks (%s) it (%s)
'''%(self.enemy,self.name,self.talent))
83
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
Animal •
class variables •
on_danger cv __init__
constructor __init__ •
__init__
Animal self •
Animal.name
name,pet,prey __init__ •
__init__
name
84
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
self.name
on_danger cv cv •
. enemy
class
objects
properties objects
inherit behavior
methods name,enemy,pet
on_danger behavior
run
interactive interpreter
85
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
>>>cat=Animal(name='Cat',pet=True,prey='Mouse',enemy='Dog',tal
ent='Run Fast')
>>> cat.name
'Cat'
>>> cat.pet
True
>>> cat.cv()
name:Cat
is pet:True
prey:Mouse
enemy:Dog
talent:Run Fast
>>> cat.on_danger()
when (Dog) attacks (Cat) it (Run Fast)
class constructor
assignment __init__ •
class variables
86
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
porperties giraffe •
object
object
87
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
str x •
dir(str)
str x object •
. strings
Operations
self me •
class Operation:
num1=num2=0
def __init__(me,num1,num2):
me.num1=num1
me.num2=num2
def add(me):
return me.num1+me.num2 #add num1 and num2
def sub(me):
return me.num1-me.num2 #subtract num2 from num1
def mul(me):
return me.num1*me.num2 #multiply num1 by mum2
def div(me):
return me.num1/me.num2 #divide num1 on num2
88
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
x=Operation(100,5) 105
print(x.add()) 95
print(x.sub()) 500
print(x.mul()) 20.0
print(x.div())
y=Operation(200,20) 220
print(y.add()) 180
print(y.sub()) 4000
print(y.mul()) 10.0
print(y.div())
x.num1=30 35
x.num2=5 25
print(x.add()) 150
print(x.sub()) 6.0
print(x.mul())
print(x.div())
Code Re-
4 usability
objects
89
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
Inheritance
properties
methods behavior
Inheritance
parent
parent
class ParentClass:
variables..
functions()..
class ChildClass(ParentClass):
variables..
functions()..
parent
parent method
90
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
class Son(Father):
def __init__(me,name):
print(name,me.father_name)
temo=Son('Tamer')
temo.job()
profession job
Father Son •
Father
Son Father •
class Son:
father_name='Ahmed Pasha'
profession='Officer'
def __init__(me,name):print(name,me.father_name)
def job(me):print(me.profession)
temo=Son('Tamer')
temo.job()
91
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
Animals
class Animal:
name=''
pet=''
prey=''
enemy=''
talent=''
def __init__(self,name,pet,prey,enemy,talent):
self.name=name
self.pet=pet
self.prey=prey
self.enemy=enemy
self.talent=talent
def cv(self):
cv='name:%s\nis pet:%s\nprey:%s\nenemy:%s\ntalent:%s'%(
self.name,self.pet,self.prey,self.enemy,self.talent)
print(cv)
def on_danger(self):
print('''when (%s) attacks (%s) it (%s)
'''%(self.enemy,self.name,self.talent))
class Cats(Animal):
family=''
def cat_family(self):
print(self.family)
92
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
Animals Cats •
cat_family family •
Cats object •
classes
93
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
interpreter run
function
interpreter call
interpreter
If statement
if
if condition :
code...
if condition : one_line_code
if •
if
94
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
comparison operations •
relational logical
>>> if True:print('yes')
yes
True
>>> if 1:print('yes')
yes
>>> if -1:print('yes')
yes
>>> x = 5
>>> x = 5
>>> y = 'hello'
>>> if x==5 and len(y)==4: relational
print('yes')
logical operations operations
>>> if x==5 and len(y)==5:
print('yes')
yes
95
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
else
if
if if else
else
if condition :
code..
else:
another_code..
if
if..else
odd 1 even 0
% •
96
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
run •
run
input
. •
else if elif
if condition1 :
code1..
elif condition2 :
code2..
else:
code3..
interpreter •
condition2 condition1 •
code2
code3 condition2 •
97
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
else if •
code2 condition2
if condition1 :
code1..
elif condition2 :
code2..
elif if if
x = y = 1 x x = y = 1 x
if x>0:print('x') if x>0:print('x')
y
if y>0:print('y') elif y>0:print('y')
98
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
if ..elif..else
GPA •
else:
print("Failed")
run •
input
input •
int
99
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
run
100 1
. 100 print()
interpreter
while loop
condition while
while condition:
code..
while condition:single_line_code...
100
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
True condition
True condition •
( interpreter
. loop •
True condition •
False
5 0
i = 0 0 i=0
1
2 6 i while
while i < 6 :
3 i=i+1 i
print(i)
4
i=i+1 5
Done 6 i
print('Done') i = 6
print('i =',i) 6<6 = False
6 i Done
101
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
break
break
condition
i<=10 •
i=5 10 0
break i==5 ,1
i = 0 0
while i <= 10 : 1
print(i) 2
3
if(i==5):break
4
i=i+1 5
print('Done') Done
print('i =',i) i = 5
while i =5 break •
5 i i=i+1
break
102
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
i = 0 0
while True : 1
print(i) 2
3
if(i==5):break
4
i=i+1 5
print('Done') Done
print('i =',i) i = 5
continue
while interpreter
10 0
i = 0 1
while i < 10 : 3
i=i+1 5
if i%2==0:continue 7
print(i) 9
increment •
0 2 i •
continue
loop
. i increment
i = 0
while i <= 10 :
print(i)
if i%2==0:continue
i=i+1
0 •
0%0==0 0 0 i •
i=i+1 continue
0 i
continue 0 i •
increment •
continue i
104
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
while … else
while
if else
while condition
else
while..else
while condition:
statements..
else:
another statements.
i = 10 i = 10
while i < 6 : condition == False
print(i)
i=i+1
else:
print('i =',i)
print('condtion == False')
else
105
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
i = 0 0
while i < 6 : 1
2
print(i)
3
i=i+1
4
else:
5
print('i =',i) i = 6
print('condtion == False') condition == False
while 6 i •
else
False
i = 0 0
while i < 6 : 1
print(i)
2
if(i==3):break
i=i+1 3
else:
print('i =',i)
print('condition == False')
106
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
condition while
run
while •
run
while(True): Percentage : 99
x = int(input("Percentage : ")) Excellent
if (x==-1):break A+
if( x >= 85 ): ==================
print("Excellent") Percentage : 58
if(x>=95):print('A+') Good
elif(x>=90):print('A') D
else:print('A-') ==================
elif( x >= 75 ): Percentage : 85
print("Very Good") Excellent
if(x>=80):print('B+') A-
else:print('B') ==================
elif( x >= 50 ): Percentage : 60
print("Good") Good
if(x>=70):print('B-') C
elif(x>=60):print('C') ==================
else:print('D') Percentage : -1
else: >>>
print("Failed")
print("==================")
107
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
1 if (x==-1):break
break
int() •
input
error •
Percentage : s20
x = int(input("Percentage : "))
ValueError: invalid literal for int() with base 10: 's20'
Exceptions
108
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
for iteration
c/c++ for
iteration for
loop
numbers=[1,2,3,4,5] 1
2
for number in numbers: 3
print(number) 4
5
number numbers •
x='HELLO' H
E
for letter in x: L
L
print(letter)
O
109
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
string sequence •
HELLO
number letter •
iteration variable
for .. in range
for
for
range
. range
range(start,stop,step)
range(start,stop) step = 1
110
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
step start
stop
list list
stop
1 step 1 stop
111
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
stop
c/c++ for
for
2 10 0
C++
0
2
4
6
8
10
112
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
range(0,12,2) •
iteration
loop continue
for i in range(22): 1
if(i==10):break 3
5
if(i%2==0):continue
7
print(i) 9
0 stop range
20 0 for 1
sequence 10 10 i •
10 20 break
0 % 2 •
loop continue
113
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
for while 10 0
i = -1 for i in range(11):
while i <= 10 : if i%2:continue
i=i+1
print(i)
if i%2:continue
print(i)
0 1 i=0
10 stop
for .. else
iteration
for i in range(4): 0
print(i) 1
2
else:
3
print('done..')
done..
114
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
Syntax Errors
SyntaxError : colon
100
Exceptions
syntax exceptions
interpreter
runtime
NameError call
'5'+5
115
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
TypeError
ZeroDivisionError
Exceptions
bltin-exceptions
Handling Exception
exceptions
try
try:
something_to_do
except:
something_else.
try interpreter •
except Exception
try..except
input
116
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
input int •
x int
odd even 2 •
input int •
ValueError
try..except
try: Odd
Enter A Number : 2
x = int(input('Enter A Number : '))
Even
except:
Enter A Number : f
print('incorrect number')
incorrect number
continue Enter A Number : 3
if x%2==0: Odd
print('Even') Enter A Number : d
print('Odd')
117
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
try interpreter •
Exception try..except
try:
something_to_do
except <error_name1>:
something_else.
except <error_name2>:
something_else.
Exceptions
num2 num1
ValueError int
num2 •
ZeroDivisionError
118
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
try..except finally
try:
something_to_do.
except:
something_else.
finally:
do_whatever.
except try
finally
119
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
dictionary •
mark value •
key exception
finally exception •
mark
exception
errors documentation
120
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
Modules ✓
Standard Library ✓
Packages ✓
PyPi ✓
PiP ✓
Packaging ✓
121
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
Modules
IDLE run
import
importing modules
class object
import module_name
from module_name import object
from module_name import *
122
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
fact
factorial
24 1 2 3 4 4
Run factorial.py
call •
n fact •
1 while
num num
factorial
factorial
fact
123
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
import factorial
x = factorial.fact(4)
print(x)
>>> 24
factorial import •
factorial.py
factorial.py
interpreter import
import
run .1
. .2
Lib .3
factorial.fact()
print x •
fact
NameError
fact
124
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
module_name.object
import object •
object_name
import
factorial •
for fact2
125
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
for while
import
factorial
fact2 error •
factorial •
126
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
import
127
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
standard
Library
modules
Standard Library
Math
from scratch
Standard Library
Standard Library
128
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
c built in modules •
standard Library
built in functions
129
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
Interpreter •
.py
Lib modules •
c •
os
>>>import os
>>> os.__file__
'C:\\Users\\Mahmoud\\AppData\\Local\\Programs\\Python\\Python36-32\\lib\\os.py'
__file__ os import •
import
10 3.6 >
c:/python python •
os.py os •
built in os •
130
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
time
UTC
131
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
>>> x = t.localtime()
>>> x
time.struct_time(
time_struct localtime
tm_year=2018, tm_mon=9,
tm_mday=28, tm_hour=2, tm_min=27,
tm_sec=49, tm_wday=4,
tm_yday=271, tm_isdst=0) tm_mon tm_year
tm_hour tm_mday
>>> print('Now %sh:%sm:%ss'%
tm_sec tm_min
(x.tm_hour,x.tm_min,x.tm_sec))
Now 2h:27m:49s
time time
132
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
sys
sys
>>> sys.version
'3.6.3 (v3.6.3:2c5fed8..' version
sys sys
133
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
sys
input •
sys_argv.py •
exception run •
python
argv list
134
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
argv[1] argv[0] •
exception
Hello World •
Hello
command line •
sys
input
135
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
smtplib
smtplib
stmp
Simple_Mail_Transfer_Protocol
؟ B A
mail server A •
mail server B A •
smtp
136
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
mail server •
smtp.mail.yahoo.com
gmail yahoo
smtp.gmail.com
what-is-smtp-server
gmail yahoo
gmail yahoo •
stmplib •
mail server
137
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
security security
Gmail •
https://serversmtp.com smtp.gmail.com
mail sever
stmplib
stmplib import •
object EmailMessage
stmplib from,subject,body
138
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
import smtplib
from email.message import EmailMessage
server =smtplib.SMTP(server,port)
server.starttls()
server.login(your_login_email,your_password)
yahoo STMP •
TLS 587 •
. application access
msg = EmailMessage()
msg['From'] = your_login_email
msg['To'] = the_reciever
msg['Subject'] = "Python email"
body = "Python test mail"
msg.set_content(email_body)
139
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
EmailMessage object •
login from
quit send_message
server.send_message(msg)
server.quit()
mail.py
import smtplib
from email.message import EmailMessage
def send(con,fields):
server =smtplib.SMTP(con['server'],con['port'])
server.starttls()
server.login(con['from'],con['pass'])
msg = EmailMessage()
msg['From'] = con['from']
msg['To'] = con['to']
msg['Subject'] = con['subject']
body=''
for key,val in fields.items():body+='%s : %s\n'%(key,val)
msg.set_content(body)
result=server.send_message(msg)
server.quit()
if result=={}:return True
else:return False
140
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
if send(con, fields):print('Done..')
else : print('failed..')
to
fields dictionary •
141
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
Gmail
attachment
email.examples html
142
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
Packages
Lib
.py
Package
Package
Package •
.whl
standred library
packages
143
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
PyPi
Packages
pypi.org
numpy
multi-dimensional arrays
standard library
numpy
144
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
download files
pip
pip
PIP
packages pip
Terminal
pip
command line
installing pip
145
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
PIP
PyPi
upgrade Packages •
Package •
pip •
documentation
pip
. quickstart
146
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
PIP
pypi numpy
command line
successfully installed
Package __file__
Packaging
pypi
147
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
modules
install pypi
pip
factorial.py Package
-factorial facotrial •
-__init__.py
-setup.py __init__.py factorial.py
-LICENSE
-README.md __init__.py •
interpreter
README.md facotrial •
GitHub
Markdown
LICENCE •
setup.py •
factorial pip
148
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
README.md •
#Factorial
factorial has magic function to calculate the factorial of any numbers ^_^
md
. GitHub
setup.py •
import setuptools
long_description = open("README.md", "r").read()
setuptools.setup(
name="factorial",
version="0.0.1",
author="Mr python",
author_email="author@example.com",
description="A small example package",
long_description=long_description,
long_description_content_type="text/markdown",
url="anyurl",
packages=setuptools.find_packages(),
classifiers=[
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
],
)
setuptools import •
Packages
149
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
long_description README •
Author
long_description description •
README
packages •
package
find_package __init__.py
packaging
command line
setuptools setup.py •
wheel Packaging
150
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
PyPi .whl
command line •
E package
wheels •
dist build
.whl dist •
PyPi
factorial-0.0.1-py3-none-any.whl .whl
151
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
successfully installed
. python interpreter
__file__
lib/site-packages/factorial
Package
PyPi Packages
152
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
Variables ✓
Files ✓
Database ✓
153
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
Variables
Files
database
154
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
students={}
input insert •
def insert():
while True:
name=input("Student Name : ")
_class=input("Student Class : ")
section=input("Student Section : ")
percent=input("Student Percentage : ")
student={'class':_class,'section':section,'percent':percent}
students[name]=student
agin=input("Any More ? ")
if(agin!='yes'):break
155
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
key dict
insert
call
students
156
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
remove search •
students
def search():
name=input("Enter Student Name : ")
if name in students:
print('Name :',name)
for key,value in students[name].items():
print(key,':',value)
else : print('student not found')
def remove():
global students
name=input("Enter Student Name : ")
if name in students:students.pop(name)
else : print('student not found')
input •
search call
Ahmed
157
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
insert 1 •
0 students
while True:
x = input('1-Insert 2-Search 3-Remove 4-Students 0-Exit ? : ')
if (x=='1') : insert()
elif(x=='2') : search()
elif(x=='3') : remove()
elif(x=='4') : print(list(students.keys()))
elif(x=='0') : break
run storages1.py
158
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
students run
Files
Databases
Files
File Object
file object
TextIOWrapper built in
access mode
methods object
read write
159
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
import io
file_object = io.open(file_name, access_mode)
file_name •
access_mode •
access mode •
write read
binary file •
binary modes
access mode
w+
overwrite
160
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
a+
overwrite append
rb binary
wb binary
wb+ binary
ab+ binary appending
interactive interpreter
>>> x = open('E://test.txt','w+')
>>> x
<_io.TextIOWrapper name='E://test.py' mode='w+' encoding='cp1252'>
open •
test.txt
interpreter •
File_oject.close()
161
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
write 5
file object x
x x.write() write
open built-in
write
>>> x = open('E://test.txt','w+')
>>> x.write('Hello Python ^_^')
16
>>> x.close()
E test.txt •
w+ access mode
close ا •
close
a+ access mode
read
. read
..r w+ test.txt •
>>> x = open('E://test.txt','r')
>>> x.read()
'Hello Again ^_^'
163
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
read •
؟
>>> x.read()
''
read
seek tell
postion tell
tell
position seek
>>> x = open('E://test.txt','r')
>>> x.read() read
'Hello Again ^_^'
>>> x.read() read
''
164
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
>>> x.seek(5)
5 seek
>>> x.tell()
5
>>> x.read() seek position
' Again ^_^'
readlines
readlines
multiline
seek read •
list lines •
readlines
165
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
>>> x = open('E://test.txt','r')
>>> lines = x.readlines()
>>> lines
['Hello Again ^_^\n', 'A\n', 'B\n', 'C\n', 'D']
>>> lines[0]
'Hello Again ^_^\n'
>>> lines[1]
'A\n'
os
standard library os
os
import os
os.mkdir(path) mkdir
E:
>>> os.mkdir('E://folder')
folder
os.rmdir(directory_path) rmdir
>>> os.rmdir('E://folder') folder
os.rename(old_name',new_name) rename
test.txt
>>> os.rename('E://test.txt',
'E://test2.txt') test2.txt E:
os.remove(file_path)
remove
test2.py
>>> os.remove('E://test2.txt')
io . os
166
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
files os
storages1.py
read
def save():
data=str(students)
file=open("students.txt","w")
file.write(data)
file.close()
def read():
global students
try:
file=open("students.txt","r")
data=file.read()
file.close()
students=eval(data)
except:
students={}
students.txt
167
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
dictionary
students.txt read •
try..except exception
students.py •
students dictionary
read save
insert save •
remove
read •
call students
read
168
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
students={}
read()
while True:
x = input('1-Insert 2-Search 3-Remove 4-Students 0-Exit ? : ')
if (x=='1') : insert()
elif(x=='2') : search()
elif(x=='3') : remove()
elif(x=='4') : print(list(students.keys()))
elif(x=='0') : break
storages2.py
command line
student.txt
169
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
files
students parse
decode json
170
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
str
SQL Databases
SQL
171
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
Database Server -1
Interface Module -2
SQLite3
lightweight
serverless
SQLite
SQLite
sqlite3
sql import •
172
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
>>> con=sql.connect("E://database.db")
E: •
database.db
cursor,commit,close
cursor
connection object
173
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
execute,fetchone,fetchall,rowcount
SQL quesries
sql server
sql
CREATE TABLE
CREATE TABLE •
174
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
LONGTEXT
MEDIUMTEXT text
LONGTEXT
VARCHAR •
VARCHAR(length)
text
TEXT
Database Servers
VARCHAR •
TEXT
id,age,name,email 4 user •
175
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
cell Rows
unique id •
insert unique id •
int
CREATE
CREATE table_name •
IF NOT EXISTS •
CREATE
176
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
DROP TABLE
DROP
INSERT INTO
INSERT INTO •
table_name
VALUES
cell
age,name,email
id •
quotes •
UPDATE
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
SET UPDATE •
condition
1 id user •
python name
DELETE
178
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
user •
python name
SELECT
SELECT
id name Age
1 mahmoud 23
2 ali 22
3 python 30
mahmoud,ali, python
179
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
1 id •
id=1,name=mahmoud,age=20
execute
execute queries
cur.execute('SQL STRING')
SQL execute
180
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
commit
cur.execute('SQL STRING')
con.commit()
close
connection
connection object
con.close()
id,name,age user •
181
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
table SELECT * •
cell name id •
UPDATE •
182
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
SQLite
File System
SQL
storages1.py
SQLite
students
183
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
cur.execute(query)
con.commit()
name,class,section,percent insert •
INSERT INTO
INSERT UPDATE
name SELECT •
not_found []
INSERT not_found=True •
UPDATE •
commit •
search
def search():
name=input("Enter Student Name : ")
rows=cur.execute("""SELECT * FROM students
WHERE name='%s'"""%name).fetchall()
184
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
name •
list setchall •
rows
index (Mahmoud,1,A,90)
remove
def remove():
name=input("Enter Student Name : ")
result=cur.execute("DELETE FROM students WHERE name='%s'"%name)
con.commit()
query name •
name
185
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
def students():
col=cur.execute("SELECT name FROM students").fetchall()
for name in col:print(name[0])
storages3.py
186
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
youtube-dl ✓
ffmpeg ✓
openCV ✓
tesseract ✓
187
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
youtube-dl
youtube-dl
188
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
pip youtub-dl
command line
command line
189
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
command line •
youtube-dl video_url
youtube-dl
CLI
pip upgrade
download release
190
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
channel playlist
GitHub documentation
FORMAT SELECTION
Youtube-dl
191
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
bestaudio
mp4
F -F
–get-url •
video player
url
192
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
youtube-dl
Python Package
embedding-youtube-dl youtube-dl
import youtube_dl
ydl_opts = {}
ydl=youtube_dl.YoutubeDL(ydl_opts)
ydl_opts •
dict
input •
193
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
ydl_opts •
command line
youtube_dl
194
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
youtuber youtbe-dl
windows executable C#
command line
195
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
ffmpeg
command line
ffmpeg
command line
youtube-dl
wrapper
ffmpy wrapper
ffmpeg-python
196
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
ffmpeg-python
pip
ffmpeg-python
ffmpeg
builds
ffmpeg.zeranoe.com
ffmpeg,ffplay,ffprobe bin
ffmpeg
.. ffmpeg •
command line
197
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
PATH
environment varaibles
environment
run variables
window+R
SystemPropertiesAdvanced
cmd
start SystemPropertiesAdvanced
ffmpeg
ffmpeg.exe bin
198
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
Package Manager
video editor
video converstion
ffmpeg
documentation
199
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
GitHub
https://ma7moud3ly.github.io/video.mp4
command line •
C:\Users\Mahmoud>E:
image.gif
ffmpeg-python
ffmpeg
import ffmpeg
input = ffmpeg.input('https://ma7moud3ly.github.io/video.mp4')
output = ffmpeg.output(input, 'image.gif')
ffmpeg.run(output)
200
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
object input •
ffmpeg run •
flip
import ffmpeg
input = ffmpeg.input('https://ma7moud3ly.github.io/video.mp4')
hflip=input.hflip() ; vflip=input.vflip()
ffmpeg.run(ffmpeg.output(hflip, 'hflip.mp4'))
ffmpeg.run(ffmpeg.output(vflip, 'vflip.mp4'))
201
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
crop
x,y 4 crop
width,height
import ffmpeg
input = ffmpeg.input('https://ma7moud3ly.github.io/video.mp4')
crop=input.crop(x=0,y=0,width=200,height=200)
ffmpeg.run(ffmpeg.output(crop, 'crop.mp4'))
drawtext
import ffmpeg
input = ffmpeg.input('https://ma7moud3ly.github.io/video.mp4')
202
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
y='(h-text_h)/2'
)
output=ffmpeg.output(text, 'text.mp4')
ffmpeg.run(output)
drawtext •
203
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
OpenCV
OpenCV
opencv
computer vision
objects
tag
..computer visio
openCv
204
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
pip releases
pip numpy
numpy
OpenCV
pixels
0 8 8
255 0 255
205
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
3 R,G,B RGB
(0,0,255) (255,0,0)
(255,255,255) (0,0,0)
3 list 3
4 4 4
206
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
index 2 4 4 Matrix •
col row
(255,255,255) px00 •
px01 img •
1 0 img[0,1]
3 List RGB •
255,255,255 (R,G,B)
RGB 3 list
data types
numpy list
multidimensional array
numpy
OpenCV numpy
quickstart
207
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
narrays
ndarray numpy
>>> np.zeros((2,2),int)
array([[0, 0], zeros
[0, 0]]) tuple
>>> np.ones((2,2),int)
array([[1, 1], 1 ones
[1, 1]])
>>> x=np.ones((3,3),int)
>>> x
array([[1, 1, 1], 3 3 x
[1, 1, 1],
[1, 1, 1]]) int
>>> x[0,0]=2
>>> x[1,1]=2
>>> x[2,2]=2 array[row,col]
>>> x assignment
array([[2, 1, 1],
[1, 2, 1],
[1, 1, 2]])
array[row_index]
>>> x[0] x[0]
array([2, 1, 1])
array[:,row_index]
>>> x[:,0]
array([2, 1, 1]) x[:,0]
208
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
ndarray
ndarray
>>> x=np.ones((2,2),int)
>>> x=x+2
array([[3, 3],
[3, 3]])
>>> y=np.ones((2,2),int)+3
array([[4, 4],
[4, 4]])
>>> x+y
array([[7, 7],
[7, 7]])
>>> x*y
array([[12, 12],
[12, 12]])
>>> y=np.ones((2,3),int)+3
array([[4, 4, 4], x
[4, 4, 4]]) 3 2 y 2 2
>>> x
array([[3, 3],
[3, 3]])
>>> x*y
ValueError:...
209
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
100X100
ones(100,100,3) 3
3 [0,0] •
[255,255,255]
index
OpenCV
210
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
OpenCV
white_img •
cv2 OpenCV •
import
imshow •
window
imshow •
100X100
import cv2
import numpy as np
def show(img):
cv2.imshow('Image',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
img=np.zeros((400,400,3),np.uint8)
show(img)
211
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
400,400 zeros •
show •
imshow show •
waitkey
destroayAllWindows
freeze window
import cv2
import numpy as np
def show(img):
cv2.imshow('Image',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
img=np.zeros((400,400,3),np.uint8)
for row in range(img.shape[0]):
for col in range(img.shape[1]):
img[row,col]=[0,255,0]
show(img)
212
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
green •
RGB BGR
0,255,0 img
iteration i
imwrite
(255,0,0)
import cv2
import numpy as np
B,G,R
img=np.zeros((400,400,3),np.uint8) img
for row in range(img.shape[0]): 255,0,0
for col in range(img.shape[1]):
img[row,col]=[255,0,0] img.png img
imwrite
cv2.imwrite('img.png',img)
213
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
400 X 400
496 480,000
2 •
4k 400
20 2160 3840
encoding •
compress png,jpg
pixels bits
214
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
imread
logo.png script
OpenCV
import cv2
import numpy as np
def show(img):
cv2.imshow('Image',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
main = cv2.imread('logo.png')
scaled = cv2.resize(main, (0,0), fx=4, fy=4)
gray = cv2.cvtColor(scaled,cv2.COLOR_BGR2GRAY)
show(scaled)
show(gray)
ndarray imread •
scale resize •
fx=4,fy=4 4 main
BGR cvtColor •
GRAY
215
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
Gray Scale
BGR RGB
ndarry Blue,Green,Red 3
3
Grayscale •
255 0
BGR 3 0:255
>>> gray.shape
(396, 328)
>>> gray.size
129888
>>> gray[0,0]
0
>>> gray[100,100]
89
attributes Interpreter •
gray
(width ,height) Shape •
396*328 size •
3 RGB grayscale
3 8 •
Grayscale
3 Grayscale
216
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
Drawing
OpenCV
line,rectangle,circle
line
cv2.line(image,(x1,y2),(x2,y2),color,thickness)
rectangle
cv2.rectangle(image,(x1,y2),(x2,y2),color,thickness)
circle
cv2.circle(image,(x,y),radius,color,thickness)
putText
cv2.putText(image,Text,(x,y),Font,Size,color,thickness)
217
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
import cv2
import numpy as np
def show(img):
cv2.imshow('Image',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
img=np.ones((500,500,3),np.uint8)*255
red = (0,0,255)
green = (0,255,0)
blue = (255,0,0)
cv2.line(img,(10,10),(10,490),green,4)
cv2.putText(img,'Line',(15,50),cv2.FONT_HERSHEY_SIMPLEX,1,green,2)
cv2.rectangle(img,(100,100),(200,200),red,4)
cv2.putText(img,'Rectangle',(110,120),cv2.FONT_HERSHEY_SIMPLEX,0.5,red,2)
cv2.circle(img,(300,300),100,blue,4)
cv2.putText(img,'Circle',(275,300),cv2.FONT_HERSHEY_SIMPLEX,0.5,blue,2)
show(img)
OpenCv
tutorial_py_drawing_functions
218
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
Face Detection
face detection
face
opencv
Haar-cascade
digital
window pixles
Face
features
pixel intensity
grayscale
219
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
haar-like feature
Alfréd Haar
detection features
windows
Face
feature 6000
Face
cascade stages
haar cascade
tutorial
tutorial_py_face_detection
220
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
classifiers openCv •
. site-packages/cv2/data pip
classifires •
haarcascades
221
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
haarcascade •
haarcascade_frontalface_default.xml
haarcascade_smile.xml
img2.jpg img1.jpg
222
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
import numpy as np
import cv2
def show(img):
cv2.imshow('Image',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
img = cv2.imread('img1.jpg')
small=cv2.resize(img.copy(),(0,0),fx=0.4,fy=0.4)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
smile_cascade = cv2.CascadeClassifier('haarcascade_smile.xml')
faces = face_cascade.detectMultiScale(gray)
s=0
for (x,y,w,h) in faces:
cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),2)
face_gray = gray[y:y+h, x:x+w]
face_color = img[y:y+h, x:x+w]
smiles = smile_cascade.detectMultiScale(face_gray)
for (ex,ey,ew,eh) in smiles:
cv2.rectangle(face_color,(ex,ey),(ex+ew,ey+eh),(0,255,255),2)
s=s+1
break
height=img.shape[0]
width=img.shape[1]
x_offset=0
y_offset=gray.shape[0]-small.shape[0]
img[y_offset:y_offset+small.shape[0], x_offset:x_offset+small.shape[1]] =
small
cv2.putText(img,'%s Persons'%len(faces),( width-150,height-50),
cv2.FONT_HERSHEY_SIMPLEX,0.8,(255,255,255),2)
cv2.putText(img,'%s Smile'%s,(width-150,height-10),cv2.FONT_HERSHEY_SIMPLEX,
0.8,(255,255,255),2)
show(img)
223
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
img1.jpg
small resize •
gray img •
gray detectMultiScale •
rectangle x,y
smile •
face_color face_gray
face_color smile_cascade
img puttext •
s faces len
224
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
OpenCv
import numpy as np
import cv2
cap = cv2.VideoCapture(0)
while(True):
ret,img = cap.read()
cv2.imshow('frame',img)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
while •
frames •
225
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
img frame
imshow •
py_video_display tutorial
226
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
import numpy as np
import cv2
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
smile_cascade = cv2.CascadeClassifier('haarcascade_smile.xml')
cap = cv2.VideoCapture(0)
def detect_persons(img):
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray)
s=0
for (x,y,w,h) in faces:
cv2.rectangle(img,(x,y),(x+w,y+h),(0,0,255),1)
face_gray = gray[y:y+h, x:x+w]
face_color = img[y:y+h, x:x+w]
smiles = smile_cascade.detectMultiScale(face_gray)
cv2.putText(img,'%s
Persons'%len(faces),(20,20),cv2.FONT_HERSHEY_SIMPLEX,0.5,(0,0,255),1)
cv2.putText(img,'%s
Smile'%s,(20,50),cv2.FONT_HERSHEY_SIMPLEX,0.5,(0,0,255),1)
return img
while(True):
ret,img = cap.read()
img=detect_persons(img)
cv2.imshow('frame',img)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows
usb
VideoCapture
227
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
OCR
computer
Optical_character_recognition
word
OCR Engine
tesseract ocr
text recognizer
tesseract-ocr tesseract
tesseract
228
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
tesseract
command line •
tesseract
tesseract CMD •
tessdata Tesseract-OCR
training data
tessdata Data-Files
229
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
command line
eng output_file
Data-Files
command line
ocr.png
ocr.png
230
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
ocr ocr.png •
ocr.txt
tesseract
wrapper tesseractocr
pytesseract
pip •
pillow •
231
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
img = Image.open('ocr.png')
text = image_to_string(img)
print(text)
ocr.png •
pytesseract
training
documentation
tesseract
232
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
Hosts ✓
web servers ✓
Apache server ✓
Framework ✓
Flask Framework ✓
Python Hosting ✓
233
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
ip address server
domain name
domain name •
response •
plain text
Graphical
html static •
request
234
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
html
html
server side
request •
request •
response
html
235
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
request •
.html page
.py request •
execute request
236
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
server side
file database •
client side
Hosts
domain name
request
PythonAnyWhere Azure
shared hosting •
interface apache
shared hosting
Bluehost GoDaddy
237
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
web servers
Web_server
24 •
host
clients server
http/https
response requests
html
php,Python,Ruby
response execute
hosts deploying
238
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
CGI
html response
interpreter
interpreter interface
Apache server
http server
apache
build
releases
Bitname
239
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
php
php interfaces
apachehaus
Apache24 apachehaus •
binaries bin •
cgi-bin •
CGI
httpd.conf conf •
240
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
Apache
>cd apache24/bin
Apache24\bin>httpd
localhost •
241
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
Apache configuration
conf httpd.conf
AddHandler cgi-script •
.py AddHandler # •
.py .cgi •
.. perl pl
execute interpreter ..
command line
Ctrle +C
CLI
242
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
CGI
test.py cgi-bin
#!python
print("Content-type: text/html\n\n")
print('<h1 style="color:red">','Hello CGI','</h1>')
interpreter location •
interpreter execute
#!/usr/bin/python
interpreter #!python •
environment variables
3.7 10
C:\Users\Mahmoud\AppData\Local\Programs\Python\Python36-32\python.exe
html •
\n
localhost
243
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
http://localhost/cgi-bin/test.py
Internal Error
CGI
CGI
flask frameworks
Django
244
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
Contact Form
html
245
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
contact.py •
#!python
print ("Content-type: text/html\n")
import cgi,os
from mail import send
con={'server' : 'smtp.mail.yahoo.com',
'port' : '587',
'from' : '...@yahoo.com',
'pass' : '****',
'to' : '...@gmail.com',
'subject' : 'CONTACT FORM'
}
form={}
if os.environ['REQUEST_METHOD'] == 'POST':
for key,val in dict(cgi.FieldStorage()).items():
val=str(val)
val=val[val.find(',')+3:len(val)-2]
form[key]=val
if send(con,form):
print('<center><h1 style="color:green">Succeed<h1></center>')
else:
print('<center><h1 style="color:red">Failed<h1></center>')
else:
html=open('contact.html','r').read()
print(html)
mail.py •
stmplib Packages
246
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
if os.environ['REQUEST_METHOD'] == 'POST' •
iteration FieldStorage •
form dictionary
dictionary send •
con form
3 else •
contact.html submit
print open
cgi-bin contact.py,mail.py.contact.html •
http://localhost/cgi-bin/contact.py
247
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
cgi-contact.zip
CGI
Framework
Apache CGI
configuration
execute refresh
frameworks
upload debugging
design pattern
python html
html
template enignes
248
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
Falsk
flask
documentation
pip Flask
falsk
flask.py app.py •
@app.route('/')
def home():
return '<h1>Hello Flask</h1>'
app.run(debug=True)
249
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
http://127.0.0.1:5000
Flask(__name__) object •
__name__
routes route •
http://127.0.0.1:5000 •
http://127.0.0.1:5000/home
250
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
route •
@app.route('/')
@app.route('/home/')
@app.route('/index/')
def home():
return '<h1>Hello Flask</h1>'
http://127.0.0.1:5000/home http://127.0.0.1:5000
route route •
route
run app.run(debug=True) •
debugging debug=True
app.py
refresh save
251
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
url variable
http://127.0.0.1:5000/?name=python
<> route •
@app.route('/page/<name>/')
@app.route('/page/<name>/<age>/')
def page(name="",age=""):
page route •
route
252
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
about app.py
@app.route('/')
@app.route('/home/')
@app.route('/index/')
def home():
return '<h1>I`M Home Page</h1>'
@app.route('/about/')
@app.route('/about/<name>/')
@app.route('/about/<name>/<age>/')
def about(name="",age=""):
return '<h1>My Name Is : %s<br>My Age Is : %s</h1>'%(name,age)
app.run(debug=True)
GET Request
253
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
html
template frameworks
html
x='World' CGI
print('<div>Hello %s</div>'%x)
html tags
html CGI
file
html
html
html
render_template html
254
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
page.html /page •
msg templates
page html •
{{variable_name}}
app
- app.py
templates app.py •
- templates
html
-- home.html
-- about.html about.html home.html
home.html
<h1>Hello ^_^</h1>
<p>Local Time : {{time}} </p>
<p>Operating System : {{os}} </p>
time html •
os
255
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
about.html
<h1>About Me</h1>
<p>My Name Is : {{name}}</p>
<p>My Age Is : {{age}}</p>
app.py
@app.route('/')
@app.route('/home/')
@app.route('/index/')
def home():
return render_template('home.html',time=time.ctime(),os=platform.system())
@app.route('/about/')
@app.route('/about/<name>/')
@app.route('/about/<name>/<age>/')
def about(name='',age=''):
return render_template('about.html',name=name,age=age)
app.run(debug=True)
os time
256
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
templates
html tags
docs
templates for if •
257
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
{% %} {{ }} •
endif endfor
colors about
about.html
def about(name='',age=''):
colors=['red','green','blue','orange']
return render_template('about.html',name=name,
age=age,colors=colors)
about.html
<h1>About Me</h1>
{%if name!='' and age !=''%}
<p>My Name Is : {{name}}</p>
<p>My Age Is : {{age}}</p>
{%else%}
<p>no information provided</p>
{%endif%}
<h1>Favorite Colors</h1>
<ul>
{% for color in colors %}
<li style="color:{{color}}">{{color}}</li>
{% endfor %}
</ul>
about •
age name
258
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
name if •
html <ul>
javascript css
- app.py
- templates
img javascript css
-- page.html
- static
-- style.css static template
-- script.js
static js css
static/css/style.css static/js/script.js
259
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
html
/static/file_name •
debugging
js,css CDN •
template jquery
html templates •
- app.py
- templates
-- home.html jquery.html
-- about.html
-- jquery.html jquery static •
- static
-- jquery.min.js •
260
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
jquery.html
<script src="{{url_for('static',filename='jquery.min.js')}}">
</script>
<script>
$(document).ready(function(){
$("#btn").click(function(){
alert('{{msg}}')
});
});
</script>
<button id="btn">Click Me</button>
jquery html •
static
msg
@app.route('/jquery/')
def jquery():
msg="Hello Flasker ^_^"
return render_template('jquery.html',msg=msg)
261
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
html
html inputs
form
method submit
262
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
Form.html
<h1>Falsk Calculator</h1>
<form action="" method="post">
<input type="number" name='num1' value="{{num1}}" required>
<select name="opr">
<option>+</option>
<option>-</option>
<option>*</option>
<option>/</option>
<option>%</option>
<option>**</option>
</select>
<input type="number" name='num2' value="{{num2}}" required>
<label>{{result}}</label><br><br>
<button type="submit">Calc</button>
</form>
select input 2 •
values num1,num2,opr
action
form route
263
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
route app.py
request.from[input_name] •
eval execute •
result
264
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
Files upload
Flask
- app.py
- templates
- static
-- uploads
static upload templates
upload.html templates •
upload.html
<h1>File Upload</h1>
{%if done%}
<div>done uploading
<strong>
<a target="_blank"
href="{{request.script_root}}/static/uploads/{{file}}">{{file}}</a>
</strong>
<p><a href="{{request.script_root}}/upload">back<a></p>
</div>
{%else%}
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="myfile" required>
<br><br>
<button type="submit" >Upload</button>
</form>
{%endif%}
265
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
upload request
request.script_root •
script_root
submit
upload app.py
app.py
@app.route('/upload/',methods=['POST', 'GET'])
@app.route('/upload/',methods=['POST', 'GET'])
def upload():
if request.method == 'POST':
from werkzeug.utils import secure_filename
f = request.files['myfile']
f.save(app.root_path+'/static/uploads/'+secure_filename(f.filename))
return render_template('upload.html',done=True,file=f.filename)
return render_template('upload.html')
f request.files[input_file_name] •
filename save
266
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
static/uploads save •
filename
app.root_path •
html
app.app_root request.script_root
secure_filename •
f.filename
sessions
session
sessions
267
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
sessions
sessions refresh •
refresh
session
sessions php •
cookies
encryption
admin session
- app.py templates •
- templates
-- home.html inputs 2 login.html
-- about.html
-- jquery.html
-- form.html
-- login.html
268
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
Login.html
{%if incorrect%}
<h3>Inccorect Email or Password! </h3>
{%endif%}
<form action="" method="post">
<input type="email" name='email' placeholder="Email" required>
<input type="password" name='password' placeholder="Password"
required>
<button type="submit">Submit</button>
</form>
home.html
list •
login/logout
home.html
<h1>Hello ^_^</h1>
{%if admin%}
<h4>You Are the SuperUser Of the Website</h4>
{%endif%}
<p>Local Time : {{time}} </p>
<p>Operating System : {{os}} </p>
<ul>
<li><a href="{{request.script_root}}/home">Home</a></li>
<li><a href="{{request.script_root}}/about">About</a></li>
<li><a href="{{request.script_root}}/jquery">Jquery</a></li>
<li><a href="{{request.script_root}}/form">Form</a></li>
<li><a href="{{request.script_root}}/upload">Upload</a></li>
{%if admin%}
<li><a href="{{request.script_root}}/logout">Logout</a></li>
{%else%}
<li><a href="{{request.script_root}}/login">Login</a></li>
{%endif%}
</ul>
269
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
app.py
app = Flask(__name__) •
app.secret_key = 'd0dd342ebe25a8f6b7360e8c4183a5fc'
myLoginEmail='login_email@mail.com'
myLoginPass='123456'
secret_key •
session
key •
os urandom
>>> import os
>>> os.urandom(16).hex()
'd8527771bafd6a80496cb68fbbe22114'
270
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
login route
@app.route('/login/',methods=['POST', 'GET'])
def login():
if request.method == 'POST':
email = request.form['email']
password = request.form['password']
if(email==myLoginEmail and password==myLoginPass):
session['isAdmin']=True
return redirect(request.script_root+'/')
else:
return render_template('login.html',incorrect=True)
return render_template('login.html')
password email •
session •
admin home.html •
home
home.html admin •
home route
271
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
def is_admin():
if 'isAdmin' in session:
isAdmin=session['isAdmin']
return isAdmin
return False
@app.route('/')
@app.route('/home/')
@app.route('/index/')
def home():
return render_template('home.html',time=time.ctime()
,os=platform.system(),admin=is_admin())
True admin •
False
login isAdmin
False True
home.html •
logout
272
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
@app.route('/logout/')
def logout():
session['isAdmin']=False
return redirect(request.script_root+'/')
flask-test.zip
273
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
Falsk Falsk 3
flask-contact.zip
274
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
Flask OpenCV
upload openCV falsk
OpenCV
flask-opencv.zip
275
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
Editabel Portfolio
startbootstrap-freelancer Github html
Portfolio
Falsk
portfolio
276
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
flask-portfolio.zip
277
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
Python Hosting
CGI
ssh access
vps/cloud hosting
python2 CGI
test.py public_html/cgi_bin •
#!/usr/bin/python
import platform
print ('Content-type: text/html\n')
print ('<h1>Hello From Shared Hosting ^_^</h1>')
print ('<h2>My operating system is %s<h2>'%platform.system())
print ('<h2>My python version is %s<h2>'%platform.python_version())
278
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
Content-type: text/html\n •
platform •
www.domain_name.com/cgi_bin/test.py •
cgi_bin
.htaaccess
public_html
279
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
public_html •
test.py python
cgi_bin
.htaccess python •
644
your_domain/python/test.py
280
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
python3
Flask
how-to-install-and-configure-python-on-a-
ssh hosted-server
Linux terminal
putty
putty access
ssh 22 putty •
user
281
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
[~]$ cd public_html
[~/public_html]$ mkdir download
[~/public_html]$ cd download
[~/public_html/download]$ wget https://www.python.org/ftp/python/3.4.3/Python-
3.4.3.tgz
2018-09-18 19:03:31 (1.18 MB/s) - `Python-3.4.3.tgz' saved
[~/public_html/download]$ dir
./ ../ Python-3.4.3.tgz
[~/public_html/download]$ tar xvzf Python-3.4.3.tgz
[~/public_html/download]$ dir
./ ../ Python-3.4.3/ Python-3.4.3.tgz Python-3.4.3.tgz.1 ]
[~/public_html/download]$ cd Python-3.4.3
[~/public_html/download/Python-3.4.3]$ ./configure --prefix=$HOME/.local
.
.
[~/public_html/download/Python-3.4.3]$ make
.
[~/public_html/download/Python-3.4.3]$ make install
.
.
282
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
public_html terminal •
cd public_html
mkdir download download •
cd download
build •
wget https://www.python.org/ftp/python/3.4.3/Python-3.4.3.tgz
.. putty paste •
paste
cd Python-3.4.3 •
/home/.local •
./configure --prefix=$HOME/.local
build make install make •
environment variables
. terminal
283
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
vim •
file manager
export PATH="$HOME/.local/bin:$PATH"
Terminal •
source ~/.bash_profile
ssh client python3 •
284
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
pip upgrade •
Packages
CGI python3
python public_html
#!/home/<user_name_on_host>/.local/bin/python3
print ("Content-type: text/html\n")
import os,platform
print ('<h1>Hello From Shared Hosting ^_^</h1>')
print ('<h2>My operating system is %s<h2>'%platform.system())
print ('<h2>My python version is %s<h2>'%platform.python_version())
285
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
python interpreter •
python2 python3
3 interpreter •
286
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
webserver
Apache
Interpreter
Flask
wsgiref
Flask deploying •
app.run(debug=True)
287
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
CGI •
flask- cgi-bin •
test.zip
-cgi-bin flask-test •
-flask-test
-index.py index.py
-app.py
-templates
-static
http://localhost/cgi-bin/flask-test/index.py
. index.py •
#!python
from wsgiref.handlers import CGIHandler
from app import app
CGIHandler().run(app)
interpreter location •
run app.py •
288
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
http://localhost/cgi-bin/flask-test/index.py •
-flask-test
-index.py
-.htaccess
-app.py .htaccess
-templates
-static
index.py
#!/home/<user_name_on_host>/.local/bin/python3
from wsgiref.handlers import CGIHandler
from app import app
CGIHandler().run(app)
.htaccess
289
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
rewrite .htaccess •
url/flask-test/index.py url/flask-test
numpy flask-OpenCV •
pythonanywhere
CGI
cloud hosting
Flask cloud
PythonAnywhere
290
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
PythonAnywhere
web dashboard •
291
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
app.py
mysite Files •
app.py
292
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
online interpreter
save •
293
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
Flask
PythonAnywhere flask-test.zip
~/mysite $ dir
__pycache__ app.py flask-test.zip
~/mysite $ unzip flask-test.zip
replace app.py? [y]es, [n]o, [A]ll, [N]one, [r]ename: y
inflating: app.py
~/mysite $ exit
Exit Console closed.
294
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
replace app.py •
exit y
reload web
web errors •
295
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
user
Packages pip3.7
Falsk
--user package •
Package
PythonAnywhere
deploying flask
296
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
297
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
GUI
platforms
GuiProgramming
Kivy
Kivy
cross platform
Download Kivy
298
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
cython pygame •
installation-windows kivy
main.py
App myApp •
build myApp •
299
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
kivy color •
OpenCV 1 0 R,G,B •
255 : 0
Run
300
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
Kivy PC
kivy
kivy script •
Kivy Launcher
Kivy Launcher •
kivy •
- kivy
test
- test
- main.app
- android.txt
kivy test •
301
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
test/main.py
test/android.txt
title=Test
author=Pink Python
orientation=portrait
title android.test •
landscape portrait
test.zip
302
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
Window
minimize maximize
Config
303
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
Config •
Config.set('graphics', 'width','600')
Config.set('graphics', 'height','600')
1 auto fullscreen •
borders
left top •
304
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
class myApp(App):
def build(self):
return Button(text='Hello From Kivy',color=(1,0,0,1))
myApp().run()
window
api-kivy.config Config
305
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
Layouts
container
layouts kivy
layouts
Anchorlayout
anchorlayout
AnchorLayout •
AnchorLayout object •
306
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
Button AnchorLayout
color=(1,0,0,1),size=(200,50),size_hint=(None,None))
layout.add_widget(btn)
return layout
myApp().run()
AnchorLayout layout •
anchor_y=center anchor_x=center
btn •
.Button
307
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
anchorlayout
FloatLayout
position floatlayout
widgets
FloatLayout •
FloatLayout object •
layout=FloatLayout()
pos FloatLayout •
(50,50) x,y
Button(text='Button', pos=(50,50))
308
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
FlaotLayout
class myApp(App):
def build(self):
layout=FloatLayout()
btn1=Button(
text='(0,0)',size=(100,100),size_hint=(None,None),
pos=(0,0)
)
btn2=Button(
text='(150,150)',size=(100,100),size_hint=(None,None),
pos=(150,150)
)
btn3=Button(
text='(300,300)',size=(100,100),size_hint=(None,None),
pos=(300,300)
)
layout.add_widget(btn1)
layout.add_widget(btn2)
layout.add_widget(btn3)
return layout
myApp().run()
309
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
layout btn1,btn2,btn3 3 •
add_widget
0,0 pos(x,y) •
layout
pos_hint
Button(text='Button', pos_hint={'x':0.5,'y':0.4})
pos_hint={'x':0.5,'y':0.4} 1 0 x,y •
layout 40 50
310
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
btn1=Button(
text='(10%,10%)',size=(100,100),size_hint=(None,None),
pos_hint={'x':0.1,'y':0.1}
)
btn2=Button(
text='(40%,40%)',size=(100,100),size_hint=(None,None),
pos_hint={'x':0.4,'y':0.4}
)
btn3=Button(
text='(70%,70%)',size=(100,100),size_hint=(None,None),
pos_hint={'x':0.7,'y':0.7}
)
311
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
BoxLayout
size anchor position
BoxLayout
BoxLayout •
BoxLayout object •
layout=BoxLayout(orientation='horizontal')
layout=BoxLayout(orientation='vertical')
orientation •
312
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
BoxLayout •
orientation layout
vertical orientation
313
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
boxlayout boxlayout •
BoxLayout
50 100 BoxLayout
class myApp(App):
def build(self):
layout = BoxLayout(orientation='vertical')
layout1 = BoxLayout(orientation='horizontal',
size_hint=(1,0.1))
btn11 = Button(text='Button 11',size_hint=(0.8,1))
btn12 = Button(text='Button 12',size_hint=(0.1,1))
btn13 = Button(text='Button 13',size_hint=(0.1,1))
layout1.add_widget(btn11)
layout1.add_widget(btn12)
314
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
layout1.add_widget(btn13)
layout2 = BoxLayout(orientation='horizontal')
btn21 = Button(text='Button 21')
btn22 = Button(text='Button 22')
btn23 = Button(text='Button 23')
btn24 = Button(text='Button 24')
layout2.add_widget(btn21)
layout2.add_widget(btn22)
layout2.add_widget(btn23)
layout2.add_widget(btn24)
layout.add_widget(layout1)
layout.add_widget(layout2)
return layout
myApp().run()
315
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
Widgets
CheckBox, Image, Slider, Progress Bar, Text Input, Toggle button, Switch,
Video
Button
widgets
press
Button import •
Button object •
button=Button()
Button Attributes •
316
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
text
font_size
Color
background_color
id
constructor •
btn=Button(text='Hello')
btn.text='Hello World'
.. •
size , size_hint
size=(width,height)
size_hint=(None,None)
size_hint •
layout container
size_hint=(width%,height%)
317
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
size_hint=(0.4,1) 0:1 •
100 container 04
Events
on_release on_press 3
def press(instance):
print('pressed..')
btn=Button(on_press=press)
. instance press
press object
instance.id instance.text id
318
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
btn=Button(
text="Press On Me",
color=(0,0,0,1), #black
background_color=(1,1,1,1), #white
font_size=100,
size_hint=(1,0.5),
pos_hint={'y':0.25},
on_press=self.press,
)
layout.add_widget(btn)
return layout
myApp().run()
50 100 button
api-kivy.uix.button Button
319
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
Label
label
import •
Label object •
label=Label(text="I'm A Label")
font_size color
size_hint size
Button Label
Label
class myApp(App):
i=0
320
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
label=Label()
def press(self,instance):
self.label.text='count : '+str(self.i)
self.i+=1
def build(self):
layout=BoxLayout(orientation=’vertical’)
self.label=Label(
text=”I’m A Label”,
color=(0,1,0,1), #green
font_size=70,
)
btn=Button(
text=”Press On Me”,
color=(1,0,0,1), #red
background_color=(0,1,0,1), #green
font_size=70,
on_press=self.press,
)
layout.add_widget(self.label)
layout.add_widget(btn)
return layout
myApp().run()
321
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
TextInput
TextBox EditText
import •
TextInput object •
label=Label(text='write anything')
multiline=True or False .
True
focus= True or False
allow_copy=True or False
background_color=(R,G,B,Alpha)
color=(R,G,B,Alpha)
text='my text'
hint_text='text'
focus
hint_text_color=(R,G,B,Alpha)
322
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
events
enter multiline=False •
on_text_validate
def on_enter(instance):
print('user pressed enter')
text TextInput •
players=['Essam El Hadary',
'Wael Gomaa',
'Ahmed Fathy',
'Hossam Ghaly',
'Emad Meteb',
'Mohamed Zidan'
]
323
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
class TestApp(App):
label=Label(color=(1,0,0,1),valign="top",size_hint=(1,0.90),font_size=70)
def text_change(self,instance,value):
self.label.text=""
for player in players:
if value in player.lower():
self.label.text+=player+'\n'
def build(self):
layout=BoxLayout(orientation='vertical')
txt=TextInput(hint_text='Search For Players',
multiline=False,
size_hint=(1,0.1),
color=(1,0,0,1),
font_size=80
)
txt.bind(text=self.text_change)
layout.add_widget(txt)
layout.add_widget(self.label)
return layout
TestApp().run()
players List •
Label
324
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
TextInput
api-kivy.uix.textinput
325
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
Image
Image
AsyncImage
import •
object •
img=Image()
async_img= AsyncImage()
Source
True
allow_stretch = True or False
Image Widget
stretch
keep_ratio = True or False
cashe
Nocache = True or False
326
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
class TestApp(App):
i=0
img=AsyncImage(size_hint=(1,0.9),source=src[i],keep_ratio=False)
img.source=src[2]
def press(self,btn):
if btn.id=='1' and self.i<(len(src)-1):
self.i+=1
self.img.source=src[self.i]
elif btn.id=='2' and self.i>0:
self.i-=1
self.img.source=src[self.i]
elif btn.id=='3':self.img.allow_stretch=btn.state=='down'
elif btn.id=='4':self.img.keep_ratio=btn.state=='down'
def build(self):
layout=BoxLayout(orientation='vertical')
btns=BoxLayout(orientation='horizontal',size_hint=(1,0.1))
btns.add_widget(Button(text='>>>',id='1',on_press=self.press))
btns.add_widget(Button(text='<<<',id='2',on_press=self.press))
btns.add_widget(ToggleButton(text='Stretch',id='3',on_press=self.press))
btns.add_widget(ToggleButton(text='Ratio',id='4',on_press=self.press))
layout.add_widget(self.img)
layout.add_widget(btns)
return layout
TestApp().run()
327
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………
AsyncImage
kivy Kivy
gallery
328
https://docs.python.org/3/
http://tutorialspoint.com/python
https://www.w3schools.com/python
PINK PYTHON 2018
break