You are on page 1of 330

PINK PYTHON 1.

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 ✓

for Page in PINKPYTHON :


PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

Programming_language

Pink Python

9
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………


...

‫و‬

issues Github

10
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

Python ✓

11
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

Python

Python

Python is an interpreted high-level programming language


for general-purpose programming.

1989 Guido Van Rossum

language

scripting

Computer proposal 1999 ABC

Programming for Everybody

. •


12
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

portable easy-to-read easy-to-learn

android, ios Windows, Linux, Mac

Tiobe Index

GitHub

13
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

Python is an interpreted high-level programming language


for general-purpose programming.

: programming language

processors •

machine code

. ones zeroes

ADD MOV

location •

register

Assembly

Low level language

14
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

High Level Language

High Level

Interpreted :

assembler

hexadecimal binary

High Level •

source code

15
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

assembler •

complier

source code compilers

. machine code

C/C++/BASIC compiled language •

compile C •

. binary executable code .exe

Linux

compile •

header machine code

executable •

windows Linux files/binaries

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

interpreter python environment

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

An integrated development environment (IDE) An IDE normally consists of a source code


editor, build automation tools, and a debugger. Most modern IDEs have intelligent code
completion. Some IDEs, such as NetBeans and Eclipse

IDE

IDLE •

integrated development and learning environment

Python IDLE •

Interpreter

22
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

Linux

python3 python terminal

23
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

IOS Android

van Rossum

qpython qpython3

3 qpython3

Editor

Interactive Interpreter Console

24
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

Python Online

tutorialspoint execute_python_online

PythonAnyWhere •

Dashboard

25
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

Interactive Mode

chat Interpreter

python CMD IDLE

console qpython •

python terminal •

Enter Interactive Interpreter

print("Hello World ^_^")

IDLE

26
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

CMD

PythonAnyWhere

print •

Hello World

C++ Java

27
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

Python IDLE

File > New File IDLE •

code editor Ctrl+N

print("Hello World ^_^") •

Run > Run module F5

Interactive interpreter

Qpython •

Editor

test.py

28
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

Code Editors

sublime code editor Python IDLE

vscode notepdad++

CMD Terminal

vscode

code extensions

extensions editor

visualstudio

29
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

test.py py •

extension hint

extension reload

start debug •

DEBUG CONSOLE debugging

script debugger

notepad debugger IDLE

command line

30
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

command Line

CMD command line

Terminal

command line .py

python script_name.py

test.py •

Command line

E test.py •

command line

31
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

command line IDLE Interactive Interpreter

IDE Code editor IDLE Code Editor

PyCharm IDE

32
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

Python Basics

Operations ✓

Data types ✓

Numbers ✓

Strings ✓

Arrays ✓

Comments ✓

Functions ✓

OOP ✓

Making Decision ✓

Loop ✓

Errors and Exceptions ✓

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

3+32-15 3+2*16-30/2 3+2*16-30/2

<< << <<

35
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

Comparison (Relational) Operators

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

>>> 2*3+4*5 == 15*2-4


True

Math Operation •

36
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

Logical Operations

Logic gates

output input

1 0

logical operators

1 0 False True not or and

and , or , not False True

False False False False False False


True False False True False True
And or
False True False False True True
True True False True True True

False True not

37
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

False True

False True

Interactive Interpreter ..

>>> True and True >>> False or False


True False
>>> True and False >>> not True
False False
>>> True or False >>> not False
True True

>>> 5+3 < 4-1 or 3*4 == 2*6 8<3 or 12==12


True False or True = True

>>> 5+2 > 4-3 and not 1 > 3 7 > 1 and not False
True True and True = True

>>> ((5+2)>(4-3))and not(1>3)


True

38
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

or and

False True

and •

or •

and •

or •

>>> 5 and 6 >>> 0 or 2


6 2
>>> 5 or 6 >>> True and 2
5 2
>>> 0 and 2 >>> 2 and True
0 True

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

var1,var2,var3=val1,val2,val3 var1=var2=var3 = val

>>> x,y,z=1,2,3 >>> x=y=z=20


>>> x >>> x
1 20
>>> y >>> y
2 20
>>> z >>> z
3 20

42
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

Data Types

data

numbers -1

1.5 float 1 int integer

5j complex

strings -2

"Hello World" ''

str string

Boolean -3

capital False True bool

list , tuple , dictionary 3 -4

43
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

type

>>> type(5) >>> type('Hello')


<class 'int'> <class 'str'>
>>> type(5.5) >>> type(True)
<class 'float'> <class 'bool'>
>>> type(5j)
<class 'complex'>

Variable type

Dynamically typed

False True x •

str int bool

44
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

c/c++/java/c# •

statically typed

int x = 1 1 x

integer

Dynamically Typed •

100 2 1 int integer

.0 1.0 0.7 float

complex .. float

Number Type Conversion #

int(value)

float(value)

complex(value)

complex(real,img)

45
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

>>> int(5.5) >>> x = 10


5 >>> type(x)
>>> float(10) <class 'int'>
10.0 >>> x = complex(x)
>>> complex(2,4) >>> x
(2+4j) (10+0j)
>>> type(x)
<class 'complex'>

int •

imaginary real complex •

complex

Math

Math

Mathematical Functions

import

Modules

from math import *

print

dir

46
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

from math import * math

>>> pi
pi
3.141592653589793

>>> sqrt(25)
5.0 sqrt

>>> pow(2,4) 4 2 pow


16.0

>>> floor(5.6) floor


5
>>> ceil(5.6)
6 ceil

>>> log10(10) 10 log10


1.0
log
>>> log(100,10)
2.0 2 10 100

>>> factorial(4) factorial


24
24 1 2 3 4 4
>>> fabs(-10)
10.0 fabs

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)

>>> radians(180) == pi radians 90


True

180
>>> x=radians(90)
>>> int(sin(x))
1
>>> int(cos(x))
0

Math

math

48
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

str string

double quotes single quotes

>>> x = "Hello world"


>>> type(x)
<class 'str'>
>>> type('Hi')
<class 'str'> not defined
>>> 'hi'
'hi' identifier
>>> hi
NameError: name 'hi' is not error
defined
>>>

>>> 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

single quote /double quote

>>> x = '''Hello >>> x="""1


World''' 2
>>> x 3"""
'Hello\nWorld' >>> x
>>> print(x) '1\n2\n3'
Hello >>> print(x)
World 1
2
3

escape character \n

print •

escape character

non printable slash

50
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

>>> x = "Hello\nWorld" >>> x = "Hello\tWorld"


>>> x >>> x
'Hello\nWorld' 'Hello\tWorld'
>>> print(x) >>> print(x)
Hello Hello World
World

\n •

\n Hello\nWorld •

print

tab \t •

double/single quotes

>>> x = "Hello"world"
SyntaxError: invalid syntax
>>> x = 'Hello'world'
SyntaxError: invalid syntax

double quote "Hello"world"

Hello

51
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

\" slash quote

double quotes single quote

>>> 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 •

the number is .. students x •

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 = "Pink Python" len


>>> len(x)
11

>>> 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
.……..……………….…........…...…..…………………….……..……………………….………

identifier data types

index

array

list data sequence

dictionary tuple

List

list

data List_name = [data , data , data]

object bool string number

>>> x = [1,'Hi',True]
>>> type(x) 3 x list
<class 'list'>

>>> x[0] list


1
list_name[index]
>>> x[1]
'Hi' 1 0 index
>>> x[2]
True 1 0

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

>>> x.append(10) append


>>> x
[1, 2, 4, -2, 4, 1, 5, 10]

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.reverse() reverse


>>> x
[10, 5, 1, 4, -2, -5, 4, 2, 1, -5]

>>> 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

dict_name = { key1 : value , key2 : value , key3 : value }

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 •

small age key

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['color4']='orange' value key


>>> x
assignment dict
{'color1': 'red', 'color2':
'green', 'color3': 'yellow', key
'color4': 'orange'}

>>> 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

>>> list(x.keys()) values key


['color1', 'color2']
keys() dict
>>> list(x.values())
['red', 'green'] list values()

data structures

63
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

interpreter

hash •

# single line comment

single/double quotes 3 string

''' """
comment1 comment1
Comment2 Comment2
Comment3 Comment3
Comment.. Comment..
''' """

64
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

#Hi! I'm A comment. run


#the Interpreter will not see me ^_^

print(1) 1
#print(2) 3
print(3); print(4); #print(5) 4

#for Multiline comment


#Turn it to a string

'''
print('you')
print("can't")
print('see')
print('Me :3')
'''

download script comment.py from GitHub

65
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

function

list print

dict tuple

inputs

output

data

user defined functions •

min print built-in

type len max

built-in functions

66
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

x datatypes

len(x)

x.reverse() reverse

‫؟‬

built-in functions len •

x x reverse •

List class object

List •

append pop index count list

object

call function

call

comma arguments

return type

print
67
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

function_name(arg1,arg2,arg…)

variable=function_name(arg1,arg2,arg…)

>>> x = print("Hello") argument print


Hello
>>> x
x

>>> x = len("Hello") argument len


>>> x
x
5

arguments •

parameter

user defined functions

68
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

Input and Output

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)

Download script print.py from GitHub

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
.……..……………….…........…...…..…………………….……..……………………….………

>>> x=input('Enter A number : ')


Enter A number : 10
>>> type(x)
<class 'str'>
>>> x + 5
TypeError: must be str, not int
>>> int(x) + 5
15

print input

print("HI ^_^") HI ^_^


Enter The First Number :
# 20
num1 = input("Enter The First Number : ") Enter The Second Number
# : 5
num1 = float(num1) num1 + num2 = 25.0
num1 - num2 = 15.0
#
num1 * num2 = 100.0
# num1 / num2 = 4.0
num2 = float(input("Enter The Second Number :
"))

print("num1 + num2 = " + str(num1 + num2))


print("num1 - num2 = " + str(num1 - num2))
print("num1 * num2 = " + str(num1 * num2))
print("num1 / num2 = " + str(num1 / num2))

Download input_output.py from GitHub

71
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

User Defined Functions

built in functions

interpreter

Function definition

def name(parameter1, parameter2,parameter n):


code…
code…

interpreter def •

identifier •

keywords

interpreter colon •

72
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

.Code Blocks

block

c/c++ block

start curly brackets

end

Block_(programming)

line indent

xx

5 1

def xx(): xx print


print(1)
run
print(2)
print(3)
print(4)
xx()
print(5)

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

def xx(): call xx


1
print(1)
2
print(2) 3
print(3) 4
print(4) 5
call again
print(5) 1
2
print('call xx') 3
4
xx()
5
print('call again') and again
xx() 1
print('and again') 2
3
xx() 4
5

return type

len max

return type

return

def name(parameter1, parameter2,parameter n):


code…
code…
return variable...

75
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

num2 num1 add

def add(num1,num2): num1 add


result = num1 + num2
num2
return result
result
x = add(5,6) 11
print(x) 40
400
y = add(10,30) >>>
print(y)

print(add(100,300))

Download script functions1.py from GitHub

return •

result

print() •

call return type

. 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)

Download script functions2.py from GitHub

x,y,z x,y,z •

xx(x,y,z) •

xx(x=1,y=2,z=3) interpreter xx(1,2,3)

xx(x=x,y=x,z=x) •

xx(x=1,y=2,z=3)

x,y,z xx(z=3,y=2,x=1) xx(z=z,y=y,x=x)

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)

Download script functions3.py from GitHub

xx x=1,y=2 global •

x=3,y=4 local

x,y global x,y •

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)

Download script functions4.py from GitHub

local y global x •

global x=3 •

81
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

Object Oriented Programming

object

classes

methods : class •

attributes

class ClassName:
variables...
functions()..

identifier class •

methods •

class variables •

object method

82
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

class constructor __init__() •

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))

Download script class1.py from GitHub

83
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

Animal •

name , pet , prey , enemy , talent 5 Animal •

class variables •

on_danger cv __init__

constructor __init__ •

class variables kuvt __init__ •

__init__

Animal self •

class methods call class variables •

self.cv() self. name self

Animal.name

name,pet,prey __init__ •

__init__

name

84
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

self class variable

self.name

on_danger cv cv •

. enemy

class

objects

properties objects

inherit behavior

class variables Animal

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)

cat animal object •

__init__ cat properties •

class constructor

assignment __init__ •

class variables

attribute class variable cat •

class methods on_danger cv properties

86
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

>>>giraffe=Animal('Giraffe', False, 'Vegetarian', 'Lion',


'Kick with legs')
>>> giraffe.cv()
name:Giraffe
is pet:False
prey:Vegetarian
enemy:Lion
talent:Kick with legs
>>> giraffe.on_danger()
when (Lion) attacks (Giraffe) it (Kick with legs)

porperties giraffe •

object

object

>>> x = "Pink Python"


>>> type(x)
<class 'str'>
>>> dir(str)
[... 'find', 'format', 'format_map', 'index', 'isalnum',
'isalpha', 'isdecimal', 'isdigit', ...]
>>> x.upper()
'PINK PYTHON'
>>> x.split()
['Pink', 'Python']

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())

Download script class2.py from GitHub

Code Re-

4 usability

objects

89
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

Inheritance

properties

methods behavior

Inheritance

parent

child parent child

child child object

parent

class ParentClass:
variables..
functions()..

class ChildClass(ParentClass):
variables..
functions()..

parent

properties Child object child

parent method

90
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

class Father: Tamer Ahmed Pasha


father_name='Ahmed Pasha' Police Officer
profession='Police Officer'
def job(me):print(me.profession)

class Son(Father):
def __init__(me,name):
print(name,me.father_name)

temo=Son('Tamer')
temo.job()

Download script class3.py from GitHub

father_name, profession Father •

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
.……..……………….…........…...…..…………………….……..……………………….………

constructor Son object •


name __init__
Father me. father_name Son
job call Son object •
Father
. inheritance

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)

Download script class4.py from GitHub

92
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

Animals Cats •

cat_family family •

Cats object •

Cats child Animals parent

>>> lion=Cats('Lion',False,'Small Animals','Big


Animals','Run Fast')
>>> lion.family='Big Cats'
>>> lion.cv()
name:Lion
is pet:False
prey:Small Animals
enemy:Big Animal
talent:Run Fast
>>> lion.on_danger()
when (Big Animals) attacks (Lion) it (Run Fast)

classes

93
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

interpreter run

function

interpreter call

interpreter

condition control flow

If statement

if

if condition :
code...

if condition : one_line_code

if •

None 0 False condition •

if

94
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

comparison operations •

logical operations operation

if condition False True

relational logical

logical operations relational •

>>> if True:print('yes')
yes
True
>>> if 1:print('yes')
yes

>>> if -1:print('yes')

yes

>>> if False:print('yes') False 0


>>> if 0:print('yes')

>>> x = 5

>>> if x>4:print('yes') relational operation


x>4=True
yes

>>> 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..

condition colon : else •

if

if..else

odd 1 even 0

% •

num = float(input('Enter a number : ')) Enter a number : 5


5.0 is odd.
if(num%2==0):print('%s is even.'%num) >>>
Enter a number : 10
5.0 is even.
else:print('%s is odd.'%num) >>>

Download script ifelse.py from GitHub

96
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

run •

run

input

. •

else if elif

if condition1 :
code1..
elif condition2 :
code2..
else:
code3..

interpreter •

code3 code2 code1 condition1

condition2 condition1 •

code2

code3 condition2 •

97
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

else if •

code1 condition1 elif 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 •

x = int(input("Enter your percentage : ")) Enter your percentage


if( x >= 85 ): : 91
Excellent
print("Excellent")
A
if(x>=95):print('A+') >>>
elif(x>=90):print('A') Enter your percentage
: 80
else:print('A-')
Very Good
elif( x >= 75 ): B+
print("Very Good") >>>
Enter your percentage
if(x>=80):print('B+')
: 60
else:print('B') Good
elif( x >= 50 ): C
print("Good") >>>
Enter your percentage
if(x>=70):print('B-') : 40
elif(x>=60):print('C') Failed
else:print('D') >>>

else:
print("Failed")

Download script condition.py from GitHub

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
.……..……………….…........…...…..…………………….……..……………………….………

while True condition •

True condition

True condition •

( interpreter

while True:print( loop )

. 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

Download script while.py from GitHub

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

Download script while_break.py from GitHub

while i =5 break •

5 i i=i+1

True condition infinite loop

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

Download script while_continue.py from GitHub

increment •

0 2 i •

continue

continue loop loop


103
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

print

continue while break •

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.

else False False condition •

i = 10 i = 10
while i < 6 : condition == False
print(i)
i=i+1
else:
print('i =',i)
print('condtion == False')

False 10<6 condition •

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

Download script while_else.py from GitHub

while 6 i •

else

False while else •

False

else while break •

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')

Download script while_else.py from GitHub

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("==================")

Download script while_loop.py from GitHub

107
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

True infinite loop •

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

for item in sequence:


code..

tuple dictionary list data sequence for •

sequence for string

loop

numbers=[1,2,3,4,5] 1
2
for number in numbers: 3
print(number) 4
5

items iteration numbers list •

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

increment condition init for

False condition index

for

for in range range

range

. range

range(start,stop,step)

range(start,stop) step = 1

range(stop) start =0 step = 1

110
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

step stop start 3 range

step start

stop

>>> list(range(1,10,1)) >>> list(range(2,8,1))


[1, 2, 3, 4, 5, 6, 7, 8, 9] [2, 3, 4, 5, 6, 7]
>>> list(range(0,10,2)) >>> list(range(3,33,3))
[0, 2, 4, 6, 8] [3, 6, 9, 12, 15, 18, 21, 24, 27, 30]

list list

stop

>>> list(range(1,5)) >>> list(range(5))


[1, 2, 3, 4] [0, 1, 2, 3, 4]
>>> list(range(1,5,1)) >>> list(range(0,5,1))
[1, 2, 3, 4] [0, 1, 2, 3, 4]

1 step stop start

1 step 1 stop

>>> list(range(1,5,1)) >>> list(range(4,0,-1))


[1, 2, 3, 4] [4, 3, 2, 1]
>>> list(range(5,1,-1)) >>> list(range(20,-2,-2))
[5, 4, 3, 2] [20, 18, 16, 14, 12, 10, 8, 6, 4, 2, 0]

111
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

step stop start •

stop

sequence iteration for

range for sequence range

c/c++ for

for

for index in range(start,stop,step):


code..

2 10 0

C++

// c++ for loop # python for loop


for(int i = 0 ; i < 12 ; i=i+2) for i in range(0,12,2):
cout<<i<<endl; print(i)

0
2
4
6
8
10

112
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

range(0,12,2) •

iteration

loop break for •

loop continue

for i in range(22): 1
if(i==10):break 3
5
if(i%2==0):continue
7
print(i) 9

Download script for_range.py from GitHub

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)

increment i=-1 while

0 1 i=0

11 range stop for

10 stop

for .. else

for else while

iteration

for i in range(4): 0
print(i) 1
2
else:
3
print('done..')
done..

Download script for_else.py from GitHub

114
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

Syntax Errors

SyntaxError : colon

fatal error IndentationError

100

>>> if True print('yes')

SyntaxError: invalid syntax


>>>

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
.……..……………….…........…...…..…………………….……..……………………….………

while True: Enter A Number : 1


Odd
x = int(input('Enter A Number : '))
Enter A Number : 2
if x%2==0:print('Even') Even
else:print('Odd') Enter A Number : f
ValueError: invalid literal
for int() with base 10: 'f'

input int •

x int

odd even 2 •

input int •

ValueError

try..except

while True: Enter A Number : 1

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

else: incorrect number

print('Odd')

Download script try1.py from GitHub

117
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

try interpreter •

incrorrect except Exception

while continue number

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
.……..……………….…........…...…..…………………….……..……………………….………

while True: Enter A Num1 : 6

try: Enter A Num1 : 3


2.0
num1 = int(input('Enter A Num1 : '))
Enter A Num1 : 5
num2 = int(input('Enter A Num1 : '))
Enter A Num1 : 0
result=num1/num2
Cant divide on zero
print(result) Enter A Num1 : f
except ZeroDivisionError: Incorrect Number
print('Cant divide on zero') Enter A Num1 : 1

except ValueError: Enter A Num1 : g


Incorrect Number
print('Incorrect Number')

Download script try2.py from GitHub

try..except finally

try:
something_to_do.
except:
something_else.
finally:
do_whatever.

except try

finally

119
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

marks={'ahmed':20,'ali':19, Enter your name : ahmed


'mahmoud':10,'noor':18} 20
name=input('Enter your name : ') Enter your name : salah

try:mark=marks[name] user not found

except:mark='user not found'


finally:print(mark)

Download script try3.py from GitHub

dictionary •

value dict key

mark value •

key exception

user not found mark except

finally exception •

mark

exception

errors documentation

120
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

Modules ✓

Standard Library ✓

Packages ✓

PyPi ✓

PiP ✓

Packaging ✓

121
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

Modules

IDLE run

run >> run module

classes functions variables

import

libraries class files

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

def fact(n): >>> fact(5)


num = 1 120
while n >= 1: >>> fact(4)
num = num * n 24
n = n - 1 >>>
return num

call •

n fact •

1 while

num num

interactive interpreter run •

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 call •

factorial.fact()

print x •

fact

NameError

fact

124
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

from factorial import fact


x = fact(4)
print(x)

import object from module_name import module_name

module_name.object

import object •

object_name

import

factorial •

for fact2

def fact(n): >>> fact(5)


num = 1 120
while n >= 1:
>>> fact2(5)
num = num * n
n = n - 1 120
return num >>>
def fact2(n):
num = 1
for i in range(1,n+1):
num = num * i
return num

Download script factorial.py from GitHub

125
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

for while

n+1 for range •

import

factorial

from factorial import fact NameError: name 'fact2'


x1=fact(5) is not defined
x2=fact2(5)
print(x1)
print(x2)

fact2 error •

import fact,fact2 fact import

call import module import •

import factorial 120


x1= factorial.fact(5) 120
x2= factorial.fact2(5) >>
print(x1)
print(x2)

factorial •

import module as name

126
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

import factorial as f 120


x1= f.fact(5) 120
x2= f.fact2(5) >>
print(x1)
print(x2)

from module import * import •

import

import factorial import * 120


x1= fact(5) 120
x2= fact2(5) >>
print(x1)
print(x2)

127
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

The Python Standard Library

standard

Library

data types functions

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
.……..……………….…........…...…..…………………….……..……………………….………

stmplib ,sys time standard library

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
.……..……………….…........…...…..…………………….……..……………………….………

lib math built in •

>>> import math


>>> math.__file__
AttributeError: module 'math' has no attribute '__file__'

time

Lib math built-in time

>>> import time as t t import

>>> t.time() time


1538089706.9603162 1970 1 1

UTC

>>> t.ctime(0) ctime


'Thu Jan 1 02:00:00 1970'
>>> t.ctime(t.time())
1970 UTC 0
'Fri Sep 28 02:19:30 2018'
>>> t.ctime()
'Fri Sep 28 02:19:31 2018' time()

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

>>> import sys sys

>>> sys.builtin_module_names tuple


'_ast', '_bisect',
built in modules
'_blake2', '_codecs',
'_codecs_cn',...) sys time math

>>> sys.modules dict modules


built-in
>>> 'os' in sys.modules
in
True

>>> sys.path list path


import

>>> sys.platform platform


'win32'
linux win32

>>> sys.version
'3.6.3 (v3.6.3:2c5fed8..' version

sys sys

133
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

sys

command line sys

input •

sys_argv.py •

from sys import argv


try:
script=argv[0]
user =argv[1]
print('script name :',script)
print('user name :',user)
except:
print('no inputs from command line!')

Download script sys_argv.py from GitHub

exception run •

no inputs from command line

command line run •

python script.py value1 value2 value n..

python

argv list

134
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

argv[1] argv[0] •

exception

Hello World •

World argv[2] Hello argv[1] argv[0]

Hello

command line •

argv list import

sys

input

command line inputs

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

..POP post office protocol •

what-is-smtp-server

gmail yahoo

gmail yahoo account

gmail yahoo •

stmplib •

mail server

137
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

.Let less secure apps access your account

security security

Gmail •

smtp.mail.yahoo.com smtp server •

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

account mail server

server =smtplib.SMTP(server,port)
server.starttls()
server.login(your_login_email,your_password)

yahoo STMP •

stmp.gmail.com Gmail smtp.mail.yahoo.com

TLS 587 •

transparent security layer

starttls TLS 587 •

less secure login •

. 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

Download script mail.py from GitHub

140
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

dict con send

dict mail server,email,password

from mail import send


con={'server' : 'smtp.mail.yahoo.com',
'port' : '587',
'from' : '...@yahoo.com',
'pass' : '****',
'to' : '...@gmail.com',
'subject' : 'User'
}
fields={'name':'Python Programmer',
'Age':23,
'phone':'1234',
'message':'I Love Python ♥'
}

if send(con, fields):print('Done..')
else : print('failed..')

Download script send_email.py from GitHub

mail.py send import •

mail server con dictionary •

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

CMD command line pip

Terminal

pip

pip –version command line

command line

installing pip

145
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

PIP

pip install Package •

PyPi

pip install package_name

upgrade Packages •

pip install --upgrade package_name

Package •

pip uninstall package_name

pip •

pip install --upgrade pip

documentation

pip

. quickstart

146
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

PIP

pypi numpy

command line

successfully installed

import command line python interpreter

Package __file__

lib site-packages pip

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

import factorial import •

factorial __init__.py import

README.md facotrial •

GitHub

Markdown

LICENCE •

setup.py •

factorial pip

import factorial lib/site-packages

148
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

README.md •

#Factorial
factorial has magic function to calculate the factorial of any numbers ^_^

documentation readme GitHub •

md

html <h1> tag Header

. 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",
],
)

Download script setup.py from GitHub

setuptools import •

Packages

149
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

long_description README •

version factorial package name •

Author

long_description description •

README

packages •

package

setuptools packages = ['factorial']

find_package __init__.py

packaging

command line

wheel setuptools pip •

pip install --upgrade setuptools wheel

setuptools setup.py •

wheel Packaging

150
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

PyPi .whl

command line •

python setup.py sdist bdist_wheel

E package

wheels •

dist build

.whl dist •

PyPi

Package dist command line •

factorial-0.0.1-py3-none-any.whl .whl
151
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

pip install install •

successfully installed

. python interpreter

__file__

lib/site-packages/factorial

Package

PyPi Packages

Distutils - Tutorial packaging-projects

152
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

Variables ✓

Files ✓

Database ✓

153
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

Variables

Files

database

student class section percentage


ahmed 1 a 90
aly 2 b 80
adam 3 c 70

154
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

students data type

students dict dictionary

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
.……..……………….…........…...…..…………………….……..……………………….………

while loop insert call •

_class name input •

percent section class

key dict

name key students dict •

yes any more input •

break yes again

insert

call

Student Name : Ahmed


Student Class : 1
Student Section : A
Student Percentage : 90
Any More ? yes
Student Name : Ali
Student Class : 2
Student Section : B
Student Percentage : 80

students

{'Ahmed': {'class': '1', 'section': 'A', 'percent': '90'},


'Ali': {'class': '2', 'section': 'B', 'percent': '80'}}

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 •

value print name in students name

remove pop search

search call

Ahmed

Enter Student Name : ahmed


student not found
Enter Student Name : Ahmed
Name : Ahmed
class : 1
section : A
percent : 90

157
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

insert 1 •

keys 4 remove 3 search 2

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

1-Insert 2-Search 3-Remove 4-Students 0-Exit ? : 1


Student Name : Mahmoud
Student Class : 3
Student Section : C
Student Percentage : 97
Any More ? yes
Student Name : Noor
Student Class : 1
Student Section : B
Student Percentage : 88
Any More ? no
1-Insert 2-Search 3-Remove 4-Students 0-Exit ? : 4
['Mahmoud', 'Noor']
1-Insert 2-Search 3-Remove 4-Students 0-Exit ? : 2
Enter Student Name : Mahmoud
Name : Mahmoud
class : 3
section : C
percent : 97
1-Insert 2-Search 3-Remove 4-Students 0-Exit ? : 3
Enter Student Name : Noor
1-Insert 2-Search 3-Remove 4-Students 0-Exit ? : 4
['Mahmoud']

158
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

students run

Files

Databases

Files

File Object
file object

TextIOWrapper built in

access mode

methods object

read write

open file object

built-in function open io

159
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

import io
file_object = io.open(file_name, access_mode)

file_object = open(file_name, access_mode)

file_name •

access_mode •

access mode •

write read

string text file •

windows cp1252 UTF-8 encoding

binary file •

binary modes

access mode binary file text file

access mode

Access Mode Usage


r read only
w write only
read and write

w+

overwrite

160
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

read and write

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'>

E: test.txt x file object •

read and overwrite access mode •

open •

test.txt

interpreter •

close file object

File_oject.close()

161
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

I/O stream x.close() •

dir(x) TextIOWrapper methods

write 5

close seek tell read

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

write Hello Python ^_^ •


162
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

close ‫ا‬ •

close

x.write(' Hello Again ^_^')

w+ acces mode overwrite

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()
''

postion cursor interpreter read •

read

seek tell

postion tell

read 0 tell read open

tell

position seek

>>> x = open('E://test.txt','r')
>>> x.read() read
'Hello Again ^_^'
>>> x.read() read
''

>>> x.tell() position


15
tell

164
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

>>> x.seek(0) position


0
read seek
>>> x.read()
'Hello Again ^_^'

>>> x.seek(5)
5 seek
>>> x.tell()
5
>>> x.read() seek position
' Again ^_^'

readlines

tell seek write read object file

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

student dictionary save •

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={}

string students dict save •

students.txt

167
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

json string string dictionary •

dictionary

students.txt read •

try..except exception

students.py •

. {'ahmed': {'class': '1', 'section': 'B', 'percent': '90'} ahmed

dict structure string •

keys values dictionary

object execute eval •

students dictionary

read save

insert save •

insert save call remove

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
.……..……………….…........…...…..…………………….……..……………………….………

File system vs Database

files

eval dictionary structure

values keys dictionary

students parse

decode json

170
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

dict remove insert dict

str

SQL Databases

SQL

Structured Query Language

Oracle, DB2, and Microsoft SQL Server, MySQL

171
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

Database Server -1

Microsoft SQL Server MySQL Server

Interface Module -2

SQLite3

lightweight

serverless

SQLite

sqlite3 standard library

SQLite

Mysql Oracle Database Server SQL

sqlite3

sql import •

>>> import sqlite3 as sql

172
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

connect connection object •

>>> con=sql.connect("E://database.db")

E: •

database.db

methods con connection object •

cursor,commit,close

cursor

connection object

cursor cursor object

>>> import sqlite3 as sql


>>> con=sql.connect("E://database.db")
>>> cur=con.cursor()

173
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

methods cursor object

execute,fetchone,fetchall,rowcount

SQL quesries

sql server

sql

w3schools sql tutorial

CREATE TABLE

CREATE TABLE table_name (


column1 datatype,
column2 datatype,
column3 datatype,
)

CREATE TABLE •

174
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

MEDIUMTEXT TEXT INT,FLOAT •

LONGTEXT

MEDIUMTEXT text

LONGTEXT

VARCHAR •

VARCHAR(length)

VARCHAR VARCHAR TEXT •

text

TEXT

Database Servers

VARCHAR •

TEXT

CREATE TABLE user(


id int,
age int,
name text,
email text,
)

id,age,name,email 4 user •

175
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

id age name Email

cell Rows

unique id •

insert unique id •

INTEGER PRIMARY KEY

int

CREATE

CREATE TABLE IF NOT EXISTS table_name (


column1 datatype,
)

CREATE table_name •

IF NOT EXISTS •

CREATE

176
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

DROP TABLE

DROP

DROB TABLE table_name

INSERT INTO

INSERT INTO table_name (column1, column2, column3, ...)


VALUES (value1, value2, value3, ...)

INSERT INTO •

table_name

VALUES

cell

INSERT INTO user (age, name,email) VALUES


(20,'mahmoud','user@email.com')

age,name,email

id •

INTEGER PRIMARY KEY

quotes •

id age name Email


1 20 ahmed ahmed@email.com
177
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

UPDATE

UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;

SET UPDATE •

condition

UPDATE user SET name ='python' WHERE id=1;

1 id user •

python name

DELETE

DELETE FROM table_name WHERE condition;

DELETE FROM user WHERE name='python';

178
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

user •

python name

DELETE * FROM table_name;

SELECT

SELECT

SELECT column1, column2, ..FROM table_name;

SELECT * FROM table_name;

id name Age
1 mahmoud 23
2 ali 22
3 python 30

SELECT name FROM table_name;

name result set •

mahmoud,ali, python

179
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

SELECT * FROM table_name WHERE id=1

1 id •

id=1,name=mahmoud,age=20

SELECT * FROM table_name

execute

connection SQL queries

cursor object object

execute queries

cur.execute('SQL STRING')

SQL execute

180
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

commit

call connection Object

cur.execute('SQL STRING')
con.commit()

close

connection

connection object

con.close()

cur cursor object database.db •

>>> import sqlite3 as sql


>>> con=sql.connect("E://database.db")
>>> cur=con.cursor()

id,name,age user •

>>> cur.execute("CREATE TABLE user(id INTEGER PRIMARY KEY,name


VARCHAR(10),age INTEGER)")

commit name,age insert •

181
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

>>> cur.execute("INSERT INTO user(name,age)


VALUES('Mahmoud','23')")
>>> cur.execute("INSERT INTO user(name,age)
VALUES('Ahmed','22')")
>>> con.commit()

table SELECT * •

tuple list fetachall

>>> table=cur.execute('SELECT * FROM user')


>>> table.fetchall()
[(1, 'Mahmoud', 23), (2, 'Ahmed', 22)]
>>>

cell name id •

>>> cur.execute("SELECT * FROM user WHERE id=1").fetchall()


[(1, 'Mahmoud', 23)]
>>> cur.execute("SELECT name FROM user").fetchall()
[('Mahmoud',), ('Ahmed',)]
>>> cur.execute("SELECT name FROM user WHERE
id=2").fetchall()
[('Ahmed',)]

UPDATE •

>>> cur.execute('SELECT * FROM user').fetchall()


[(1, 'Mahmoud', 23), (2, 'Ahmed', 22)]
>>> cur.execute("UPDATE user SET name='python' WHERE id=2")
>>> con.commit()
>>> cur.execute("SELECT * FROM user").fetchall()
[(1, 'Mahmoud', 23), (2, 'python', 22)]

182
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

SQLite

File System

SQL

storages1.py

SQLite

cursor object connection object sqlite3 •

students

import sqlite3 as sql


con=sql.connect("database.db")
cur=con.cursor()
query="""CREATE TABLE IF NOT EXISTS students(
name VARCHAR(20),
class VARCHAR(5),
section VARCHAR(5),
percent int
)
"""
cur.execute(query)

students insert insert() •

not_found=cur.execute("SELECT name FROM students WHERE


name='%s'"%name).fetchall() == []
if not_found:
query="""INSERT INTO students(name,class,section,percent)
VALUES('%s','%s','%s','%s')"""%(name,_class,section,percent)
else:
query="""UPDATE students SET class='%s',section='%s',percent='%s'

183
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

WHERE name='%s' """%(_class,section,percent,name)

cur.execute(query)
con.commit()

name,class,section,percent insert •

INSERT INTO

INSERT UPDATE

name SELECT •

List setchall students

not_found []

False not_found True

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
.……..……………….…........…...…..…………………….……..……………………….………

for row in rows:


print('Name :',row[0])
print('Class :',row[1])
print('Section :',row[2])
print('Percent :',row[3])
return
print('student not found')

name •

name students SELECT

list setchall •

rows

row tuple rows iteration •

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 •

students DELETE FROM

name

185
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

def students():
col=cur.execute("SELECT name FROM students").fetchall()
for name in col:print(name[0])

dictionary students keys •

students name SELECT

tuple list fethall

iteration ('Ahmed',), ('Mahmoud',)

storages3.py

186
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

youtube-dl ✓

ffmpeg ✓

openCV ✓

tesseract ✓

187
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

youtube-dl

youtube-dl

documentation youtube-dl GitHub

188
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

pip youtub-dl

pip command line

pip install youtube-dl

command line .exe

pip Python Package

command line

command line

youtbe-dl command line •

189
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

command line •

youtube-dl video_url

youtube-dl

CLI

pip upgrade

pip install youtube-dl --upgrade

download release

190
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

channel playlist

GitHub documentation

FORMAT SELECTION

Youtube-dl

youtube-dl -f video_format video_url..

video quality format video

Video description Video exetention

best 3gp, aac, flv, m4a, mp3,


worst mp4, ogg, wav, webm
bestvideo
worstvideo
bestaudio
worstaudio

191
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

bestaudio

mp4

youtube-dl -f bestaudio video_url


youtube-dl -f mp4 video_url

F -F

youtube-dl –F video_format video_url..

–get-url •

video player

youtube-dl –-get-url video_url

url

192
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

youtube-dl

command line youtub-dl

Python Package

embedding-youtube-dl youtube-dl

import youtube_dl

ydl_opts = {}
ydl=youtube_dl.YoutubeDL(ydl_opts)

url=input('Paste Video URL : ')


ydl.download([url])

Download script youtube-dl.py from GitHub

ydl_opts •

dict

str list urls download •

input •
193
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

ydl_opts •

ydl_opts = {'format': 'bestvideo'}

ydl_opts = {'format': 'bestaudio'}

ydl_opts = {'format': 'mp4'}

command line

youtube_dl

194
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

youtuber youtbe-dl

windows executable C#

command line

195
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

ffmpeg

command line

ffmpeg

binary file executable file ffmpeg

command line

youtube-dl

ffmpeg command line

wrapper

ffmpy wrapper

ffmpeg-python

196
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

ffmpeg-python

pip

ffmpeg-python

pip install ffmpeg-python

ffmpeg

builds

ffmpeg.zeranoe.com

ffmpeg,ffplay,ffprobe bin

cmd command line ffmpeg •

ffmpeg

.. ffmpeg •

environment variables ffmpeg bin

command line

197
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

PATH

environment varaibles

environment

run variables

window+R

SystemPropertiesAdvanced

cmd

start SystemPropertiesAdvanced

Path environment variables

ffmpeg

ffmpeg.exe bin

environment variables path

198
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

Package Manager

ffmpeg command Line •

command line ffmpeg

command line ffmpeg

video editor

video converstion

ffmpeg -i input output

output gif input.mp4 •

ffmpeg -i input.mp4 output.gif

ffmpeg

documentation

199
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

command line ffmpeg

GitHub

https://ma7moud3ly.github.io/video.mp4

command line •

C:\Users\Mahmoud>E:

E:\>ffmpeg -i https://ma7moud3ly.github.io/video.mp4 image.gif

image.gif

ffmpeg-python

ffmpeg

pip ffmpeg-python environment path

import ffmpeg
input = ffmpeg.input('https://ma7moud3ly.github.io/video.mp4')
output = ffmpeg.output(input, 'image.gif')
ffmpeg.run(output)

Download script ffmpeg1.py from GitHub

200
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

object input •

input object output •

ffmpeg run •

flip

vflip hflip filp

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'))

Download script ffmpeg2.py from GitHub

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'))

Download script ffmpeg3.py from GitHub

drawtext

import ffmpeg
input = ffmpeg.input('https://ma7moud3ly.github.io/video.mp4')

text=input.drawtext(text='Pink Python ^_^',


fontcolor='red',
fontsize=30,
box=1,
boxcolor='black@0.5',
x='(w-text_w)/2',

202
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

y='(h-text_h)/2'
)

text=text.drawtext(text='By Mahmoud Aly',


fontcolor='white',
fontsize=15,
x='(w-text_w)/2',
y='((h-text_h)/2)+30'
)

output=ffmpeg.output(text, 'text.mp4')
ffmpeg.run(output)

Download script ffmpeg4.py from GitHub

drawtext •

box x,y fontcolor,fontsize

203
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

OpenCV

OpenCV

opencv

OpenCV (Open Source Computer Vision Library)

computer vision

objects

tag

..computer visio

openCv

pip command line

204
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

pip releases

pip install opencv-python

pip numpy

pip install numpy

numpy

OpenCV

pixels

Red Green Blue 3 RGB

0 8 8

255 0 255

w3schools RGB Calculator

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 list,tuple objects

numpy

OpenCV numpy

quickstart

207
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

narrays

ndarray numpy

>>> import numpy as np 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.shape shape


(3, 3)
>>> x.size
9 size

>>> 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:...

>>> np.matmul(x,y) matmul


array([[24, 24, 24],
(Row1,Col1)
[24, 24, 24]])
.Col1==Rw2 (Row2,Col2)

209
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

100X100

>>> import numpy as np


>>> white_img=np.ones((100,100,3),np.uint8)*255
>>> white_img[0,0]
array([255, 255, 255], dtype=uint8)
>>> white_img.shape
(100, 100, 3)
>>> white_img.size
30000

100 100 ones •

ones(100,100,3) 3

8 unsigned int np.uint8 •

3 [0,0] •

[255,255,255]

index

Digital Image Processing

OpenCV

210
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

OpenCV

>>> import numpy as np


>>> white_img=np.ones((100,100,3),np.uint8)*255
>>> import cv2
>>> cv2.imshow('white',white_img)

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)

Download script opencv.py from GitHub

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)

Download script opencv1.py from GitHub

212
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

green •

OpenCV (B,G,R) 0,255,0

RGB BGR

iteration 0,0,0 zeros •

0,255,0 img

shape[1] shape[0] shape •

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)

Download script opencv2.py from GitHub

213
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

400 X 400

8 3 400 400 size

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)

Download script opencv3.py from GitHub

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)

Download script opencv4.py from GitHub

OpenCv

tutorial_py_drawing_functions

218
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

Face Detection

face detection

face

opencv

Haar-cascade

haar cascade objects

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
.……..……………….…........…...…..…………………….……..……………………….………

Haar-cascade Detection in OpenCV


object OpenCV •

object features classifier

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)

Download script opencv5.py from GitHub

223
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

img1.jpg

small resize •

gray img •

smile_cascade face_cascade classifires •

gray detectMultiScale •

list lists faces list

rectangle x,y

smile •

gray crop face

face_color face_gray

detectMultiScale smile gray •

face_color smile_cascade

img puttext •

s faces len

224
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

Capture Video from Camera

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()

Download script opencv6.py from GitHub

video source VideoCapture •

while •

frames •

225
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

frame True bool read •

img frame

imshow •

if cv2.waitKey(1) & 0xFF == ord('q') •

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)

for (ex,ey,ew,eh) in smiles:


cv2.rectangle(face_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),1)
s=s+1
break

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

Download script opencv7.py from GitHub

usb

VideoCapture

227
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

OCR

Optical character recognition

computer

Artificial Intelligence vision

Optical_character_recognition

pdf

word

OCR Engine

tesseract ocr

text recognizer

command line 100

ios android C++

tesseract-ocr tesseract

tesseract

228
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

tesseract

command line •

tesseract

Program Files (x86) Program files Tesseract-OCR

tesseract CMD •

C:\Program Files (x86)\Tesseract-OCR

ffmpeg environment variables path

tessdata Tesseract-OCR

training data

tessdata Data-Files

229
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

command line

tesseract image_name output_file

eng output_file

tesseract image_name output_file -l language

Data-Files

command line

ocr.png

ocr.png

>tesseract ocr.png ocr

230
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

ocr ocr.png •

ocr.txt

tesseract

wrapper tesseractocr

pytesseract

pip •

pip install pytesseract

pillow •

pip install pillow

231
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

tesseract pillow pytesseract

command line ocr

from PIL import Image


from pytesseract import image_to_string

img = Image.open('ocr.png')
text = image_to_string(img)

print(text)

Download script ocr.py from GitHub

ocr.png •

image_to_string object open •

pytesseract

training

documentation

tesseract

232
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

Hosts ✓

web servers ✓

common gat interface CGI ✓

Apache server ✓

Framework ✓

Flask Framework ✓

Python Hosting ✓

233
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

ip address server

domain name

domain name •

http http request

response •

plain text

Graphical

html static •

request

234
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

html

html

server side

request •

request •

interpreter execute php,Python,Ruby,Ring

response

html

235
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

request •

.html page

.py request •

execute request

client side javascript •

BOM DOM html

236
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

server side

file database •

cookies sessions system

client side

Hosts

domain name

request

asp.net python php

OpenShift Heroku vps cloud hosting •

PythonAnyWhere Azure

shared hosting •

interface apache

shared hosting

Bluehost GoDaddy

237
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

web servers

Web_server

24 •

host

DNS domain name ip address

clients server

http/https

response requests

html

php,Python,Ruby

response execute

nginx apache http

hosts deploying

238
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

CGI

request CGI Common Gate Interface

html response

interpreter

interpreter interface

Apache server

http server

apache

build

releases

appserve xampserver wamp server

Bitname

239
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

php

apache server php

php interfaces

apachehaus

Apache24 apachehaus •

binaries bin •

cgi-bin •

CGI

httpd.conf conf •

240
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

Apache

bin command line •

command line httpd •

>cd apache24/bin

Apache24\bin>httpd

localhost •

Bitname xamp wamp •

241
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

Apache configuration

conf httpd.conf

AddHandler cgi-script •

# To use CGI scripts outside of ScriptAliased directories:


# (You will also need to add "ExecCGI" to the "Options" directive.)
AddHandler cgi-script .cgi .pl .py

.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

Linux interpreter location •

#!/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

howto apache CGI

CGI

file database froms

sessions cookies upload

CGI

flask frameworks

Django

244
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

Contact Form

html contct form

html

form inputs post request

GitHub contact.html html •

Download script contact.html from GitHub

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)

Download script contact.py from GitHub

form inputs cgi .. •

post request submit os

mail.py •

stmplib Packages

246
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

if os.environ['REQUEST_METHOD'] == 'POST' •

post request submit

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

file upload CGI

tutorialspoint tutorial session cookies

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

pip install Flask

falsk

flask.py app.py •

from flask import Flask


app = Flask(__name__)

@app.route('/')
def home():
return '<h1>Hello Flask</h1>'

app.run(debug=True)

command line IDLE flask

executable file app.py

249
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

http://127.0.0.1:5000

Flask(__name__) object •

__name__

routes route •

http://127.0.0.1:5000 •

route('/') main route

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

Hello Falsk home http://127.0.0.1:5000/index

route route •

route

run app.run(debug=True) •

debugging debug=True

app.py

refresh save

251
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

url variable

Get Request python name

http://127.0.0.1:5000/?name=python

<> route •

@app.route('/page/<name>/')
@app.route('/page/<name>/<age>/')
def page(name="",age=""):

page route •

age name name

route

252
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

about app.py

from flask import Flask


app = Flask(__name__)

@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)

about/Mahmoud/23 about/Mahmoud about

GET Request

253
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

html

template frameworks

html

x='World' CGI
print('<div>Hello %s</div>'%x)

string format print html

html tags

html CGI

file

jinja template engine Flask

html

html

html

render_template html

from flask import Flask,render_template


@app.route('/page/')
def page():
return render_template('page.html',msg='Hi ^_^')

254
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

page.html /page •

msg templates

page html •

<h1>Message From Python : {{ msg }}</h1>

{{variable_name}}

route html render_template

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>

age name about •

app.py

from flask import Flask,render_template


import time,platform
app = Flask(__name__)

@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)

render_template home.html home •

os time

url varaibles about •

about.html html age name

256
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

templates

jinja template engine flask

html tags

docs

<tag> {{variable_name}} </tag>

templates for if •

If condition for loop

{%if condition1%} {%for iteration_statement%}


<h1>HTML CODE1</h1> <h1>HTML CODE..</h1>
{%elif condition2%} {%endfor%}
<h1>HTML CODE2</h1>
{%else%}
<h1>HTML CODE3</h1>
{%endif%}

257
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

{% %} {{ }} •

: line indent syntax •

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 •

no information provided age

for iteration colors list •

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

<script src="{{url_for('static', filename='script.js')}}"></script>

<link rel="stylesheet" href="{{url_for('static', filename='style.css')}}">

<img src="{{url_for('static', filename='img.jpg')}}">

img js css url_for •

/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

alert btn id jquery •

msg

jquery.html route app.py

@app.route('/jquery/')
def jquery():
msg="Hello Flasker ^_^"
return render_template('jquery.html',msg=msg)

msg jquery.html /jquery •

261
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

html

html inputs

ajax http request form

form

inputs from tag html

method submit

POST/GET request fields

- app.py form.html templates •


- templates
-- home.html
-- about.html
-- jquery.hyml
-- form.html

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

post request submit •

action

form route

263
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

route app.py

from flask import request


@app.route('/form/', methods=['POST', 'GET'])
def form():
result=num1=num2=''
if request.method == 'POST':
num1=request.form['num1']
num2=request.form['num2']
opr =request.form['opr']
try:result=eval(num1+opr+num2)
except:result='Math Error'
return render_template('form.html',result=result,num1=num1,num2=num2)

post request import •

request.from request.method request

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
.……..……………….…........…...…..…………………….……..……………………….………

file input upload •

post form submit upload

upload request

request.script_root •

script_root

enctype="multipart/form-data" attribute from tag •

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

redirect session import •

from flask import Flask,render_template,request,session,redirect

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 •

"/" route redirect True isAdmin

admin home.html •

redirect True admin True

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

session is_admin admin •

login isAdmin

False True

home.html •

You Are the SuperUser Of the Website admin=True

logout

272
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

logout route logout

False session isAdmin

@app.route('/logout/')
def logout():
session['isAdmin']=False
return redirect(request.script_root+'/')

flask-test.zip

273
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

Falsk Falsk 3

Flask Contact From


Falsk Application CGI contact from

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

server shared hosting CGI

AddHandler cgi-script configuration Apache

CGI

Linux GoDaddy economy hosting

packages pip python3 python 2

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())

Download script test.py from GitHub

278
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

Linux python interpreter /usr/bin/python •

Content-type: text/html\n •

platform •

755 permission script •

internal error permission •

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 •

AddHandler cgi-script .cgi.py


Options +ExecCGI

file manager .htaccess •

show hidden files

htaccess 755 test.py permissions •

644

your_domain/python/test.py

280
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

python3

pip python3 economic host

openCV youtube-dl packages

Flask

how-to-install-and-configure-python-on-a-

ssh hosted-server

Linux terminal

ssh client openssh putty •

putty

ssh my account <<hosting <<cpanel •

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

tar xvzf Python-3.4.3.tgz •

cd Python-3.4.3 •

/home/.local •

./configure --prefix=$HOME/.local
build make install make •

shell python3 /home/.local/bin

environment variables

. terminal

environment variable python3 •

home directory bash_profile

283
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

vim •

file manager

home directory file manger c panel •

show hidden files

edit .bash_profile home •

export PATH="$HOME/.local/bin:$PATH"

Terminal •

source ~/.bash_profile
ssh client python3 •

284
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

[~/public_html]$ source ~/.bash_profile


[~/public_html]$ python3
Python 3.4.3 (default, Aug 6 2018, 12:43:02)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-18)] on Linux
>>> quit()
[~/public_html]$ pip3 --version
pip 6.0.8 (python 3.4)
[~/public_html]$ pip3 install –upgrade pip

package pip python3

pip upgrade •

Packages

CGI python3

python public_html

python3 CGI .htaccess

755 persmissios test2.py •

#!/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())

Download script test2.py from GitHub

285
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

python interpreter •

python2 python3

which Terminal python3 •

[~/public_html]$ which python


/usr/bin/python
[~/public_html]$ which python3
/home/my_usr_name/.local/bin/python3

3 interpreter •

286
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

Deploying Flask App

webserver

Apache

interpreter CGI command gate interface

Interpreter

webservers. SCGI FastCGI

WSGI web server gate way interface

Flask Apache Flask

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 •

Falsk app.py import •

CGI Falsk CGIHandler •

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

AddHandler cgi-script .cgi .pl .py


Options +ExecCGI
RewriteRule ^/?$ index.py/

289
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

755 index.py permissions •

rewrite .htaccess •

html php index.py

url/flask-test/index.py url/flask-test

numpy flask-OpenCV •

ssh client pip opencv-python

pythonanywhere

CGI

cloud hosting

Flask cloud

PythonAnywhere

290
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

PythonAnywhere

web dashboard •

Add a new web app

291
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

python Flask framework •

app.py

mysite Files •

app.py

292
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

run code editor edit •

online interpreter

save •

web Run reload

Configuration for web •

293
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

Flask

PythonAnywhere flask-test.zip

flask-test upload mysite Files •

Bash console extract •

GoDaddy ssh access

unzip file_name.zip open Bash console here •

~/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

files/mysite bash console •

reload web

web errors •

error.log log files

295
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

pip bash console pip packages

user

~ $ pip3.7 install youtube-dl --user

3.7 flask application •

Packages pip3.7

Falsk

--user package •

Package

PythonAnywhere

deploying flask

296
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

297
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

command console application

web applications line

graphical user interface GUI

GUI

platforms

GuiProgramming

Kivy

Kivy

cross platform

ios android Linux windows

mobile application desktop application

Download Kivy

298
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

cython pygame •

pip install cython


pip install pygame

installation-windows kivy

main.py

from kivy.app import App


from kivy.uix.button import Button
class myApp(App):
def build(self):
return Button(text='Hello From Kivy',color=(1,0,0,1))
myApp().run()

Download script main.py

App myApp •

run call run •

build myApp •

299
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

Hello Button build •

color text From Kivy

kivy color •

opacity alpha color = rgba(R,G,B,Alpha)

OpenCV 1 0 R,G,B •

255 : 0

Run

300
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

ios android Kivy

Kivy PC

kivy

kivy script •

Interpreter Kivy Launcher

play store Packaging •

packaging-ios packaging-android app store

Kivy Launcher

Kivy Launcher •

kivy •

- kivy
test
- test
- main.app
- android.txt

kivy test •

301
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

android.txt main.py test •

test/main.py

from kivy.app import App


from kivy.uix.button import Button
class myApp(App):
def build(self):
return Button(text='Hello From Kivy',color=(1,0,0,1))
myApp().run()

test/android.txt

title=Test
author=Pink Python
orientation=portrait

title android.test •

orientation Kivy Launcher

landscape portrait

android.txt main.py test •

Test Kivy Launcher .. kivy

test.zip

302
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

Window

minimize maximize

Config

303
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

Config •

from kivy.config import Config

Config.set('graphics', 'resizable', False)

Config.set('graphics', 'width','600')
Config.set('graphics', 'height','600')

1 auto fullscreen •

fake height width

borders

Config.set('graphics', 'fullscreen', 'auto')


Config.set('graphics', 'fullscreen', '1')
Config.set('graphics', 'fullscreen', 'fake')

left top •

Config.set('graphics', 'position', 'custom')


Config.set('graphics', 'top', '0')
Config.set('graphics', 'left', '0')

304
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

from kivy.core.window import Window


Window.clearcolor = (R,G,B,Alpha)

(0,0) 400 400 border •

from kivy.app import App


from kivy.uix.button import Button
from kivy.config import Config
from kivy.core.window import Window
Window.clearcolor = (1, 1, 1, 1)
Config.set('graphics', 'resizable', False)
Config.set('graphics', 'width','400')
Config.set('graphics', 'height','400')
Config.set('graphics', 'position', 'custom')
Config.set('graphics', 'top', '0')
Config.set('graphics', 'left', '0')

class myApp(App):
def build(self):
return Button(text='Hello From Kivy',color=(1,0,0,1))
myApp().run()

Download script main.py

window

api-kivy.config Config

305
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

Layouts

container

tools Texbox Button widgets

layouts kivy

layouts

Anchorlayout
anchorlayout

center right left

center bottom top

AnchorLayout •

from kivy.uix.anchorlayout import AnchorLayout

AnchorLayout object •

layout=AnchorLayout(anchor_x='center or left or right',


anchor_y='center or top or bottom'
)

306
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

Button AnchorLayout

from kivy.app import App


from kivy.uix.button import Button
from kivy.uix.anchorlayout import AnchorLayout
class myApp(App):
def build(self):
layout=AnchorLayout(anchor_x='center',anchor_y='center')
btn=Button(text='Button 1',

color=(1,0,0,1),size=(200,50),size_hint=(None,None))
layout.add_widget(btn)
return layout
myApp().run()

Download script main.py , for android anchor-layout.zip

AnchorLayout layout •

anchor_y=center anchor_x=center

btn •

.Button

layout btn add_widget •

307
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

anchorlayout

FloatLayout
position floatlayout

widgets

FloatLayout •

from kivy.uix.floatlayout import FloatLayout

FloatLayout object •

layout=FloatLayout()

pos FloatLayout •

(50,50) x,y

Button(text='Button', pos=(50,50))

308
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

FlaotLayout

from kivy.app import App


from kivy.uix.button import Button
from kivy.uix.floatlayout import FloatLayout
from kivy.config import Config
Config.set('graphics', 'resizable', False)
Config.set('graphics', 'width','400')
Config.set('graphics', 'height','400')

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()

Download script main.py , for android float-layout.zip

309
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

layout FlaotLayout object •

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}
)

Download script main.py , for android float-layout2.zip

311
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

BoxLayout
size anchor position

BoxLayout

BoxLayout •

from kivy.uix.boxlayout import BoxLayout

BoxLayout object •

layout=BoxLayout(orientation='horizontal')

layout=BoxLayout(orientation='vertical')

orientation •

312
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

BoxLayout •

orientation layout

from kivy.app import App


from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout
class myApp(App):
def build(self):
layout = BoxLayout(orientation='horizontal')
btn1 = Button(text='Button 1')
btn2 = Button(text='Button 2')
btn3 = Button(text='Button 3')
layout.add_widget(btn1)
layout.add_widget(btn2)
layout.add_widget(btn3)
return layout
myApp().run()

Download script main.py , for android box-layout.zip

vertical orientation

313
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

boxlayout boxlayout •

orientation box layout •

BoxLayout

0:1 x,y size_hint=(x,y)

50 100 BoxLayout

Button(text='Button', size_hint=(0.5 , 1))

from kivy.app import App


from kivy.uix.button import Button
from kivy.uix.boxlayout import 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()

Download script main.py , for android box-layout2.zip

315
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

Widgets

Label, Button, widgets

CheckBox, Image, Slider, Progress Bar, Text Input, Toggle button, Switch,
Video

Button

widgets

press

events release touch

Button import •

from kivy.uix.button import Button

Button object •

button=Button()

Button Attributes •

316
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

text

font_size

Color

background_color

id

constructor •

object attributes Button

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

function event on_touch

def press(instance):
print('pressed..')
btn=Button(on_press=press)

on_press event btn •

. instance press

press object

instance.id instance.text id

from kivy.app import App


from kivy.uix.button import Button
class myApp(App):
i=0
def press(self,instance):
instance.text=str(self.i)
self.i+=1
def build(self):
layout=BoxLayout()

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()

Download script main.py , for android button.zip

50 100 button

call on_press Press On Me text

text i increment press

api-kivy.uix.button Button

319
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

Label
label

import •

from kivy.uix.label import Label

Label object •

label=Label(text="I'm A Label")

text button Label •

font_size color

size_hint size

Button Label

i increment Label Button layout

Label

From kivy.app import App


from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.uix.boxlayout import BoxLayout

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()

Download script main.py , for android label.zip

321
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

TextInput

TextBox EditText

import •

from kivy.uix.textinput import TextInput

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(text='Hello world', multiline=False)


text.bind(on_text_validate=on_enter)

text TextInput •

def on_text(instance, value):


print('typing..',instance.text)
text = TextInput()
text.bind(text=on_text)

event text TextInput

from kivy.app import App


from kivy.uix.boxlayout import BoxLayout
from kivy.uix.textinput import TextInput
from kivy.uix.label import Label
from kivy.core.window import Window
Window.clearcolor = (1, 1, 1, 1)

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()

Download script main.py , for android textinput.zip

players List •

List text TextInput

Label

324
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

TextInput

api-kivy.uix.textinput

325
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

Image

Image

AsyncImage

import •

from kivy.uix.image import Image

from kivy.uix.image import AsyncImage

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
.……..……………….…........…...…..…………………….……..……………………….………

from kivy.app import App


from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
from kivy.uix.togglebutton import ToggleButton
from kivy.uix.image import AsyncImage
from kivy.core.window import Window
Window.clearcolor = (1, 1, 1, 1)
src=['https://ma7moud3ly.github.io/1.jpg',
'https://ma7moud3ly.github.io/2.jpg',
'https://ma7moud3ly.github.io/3.jpg',
'https://ma7moud3ly.github.io/4.jpg',
'https://ma7moud3ly.github.io/5.jpg']

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()

Download script main.py , for android image.zip

327
PINK PYTHON
.……..……………….…........…...…..…………………….……..……………………….………

AsyncImage

kivy Kivy

gallery

kivy-crash-course tutorial api-kivy.uix widgets

328
https://docs.python.org/3/

http://tutorialspoint.com/python

https://www.w3schools.com/python
PINK PYTHON 2018

break

You might also like