Start
Contents
Start
Week 1
Week 2
Week 3 Print to PDF
Week 4
Week 5
Week 6
Week 7
Week 8
Week 9
Week 10
Week 11
Week 12
Week 13
Week 14
Week 15
Week 16
Week 17
Week 18
003 – Syntax And Your First App
print("I love python")
I love python
Skip to main content
print("i love programming")
i love programming
print(1)
print(2)
1
2
if True:
print(1)
004 – Comments
# this is a comment
# -----------
# hola
# ------------
print("hi") # inline comment
hi
# print("ignore this code")
'''
not multiline comment
'''
'\n not multiline comment\n'
Skip to main content
006 – Some Data Types Overview
type(10)
# all data in python is object
int
type(10.1)
float
type("hello")
str
type([1, 2, 3])
list
type((1, 2, 3))
tuple
print(type({"one": 1}))
<class 'dict'>
print(type(1 == 1))
<class 'bool'>
Skip to main content
007 – Variables Part One
# syntax => [variable name][assignment operator][value]
myVariable = "my value"
print(myVariable)
my value
my_value = "value"
print(my_value)
value
# print(name)
# name ="yay" will generate error
# must assign value first before printing
name = "baka" # single word
myName = "baka" # camelCase
my_name = "baka" # snake_case
008 – Variables Part Two
Source Code : Original Code You Write it in Computer
Translation : Converting Source Code Into Machine Language
Compilation : Translate Code Before Run Time
Run-Time : Period App Take To Executing Commands
Interpreted : Code Translated On The Fly During Executionm
x = 10
x = "hello"
print(x) # dynamically typed language
hello
help("keywords") # reserved words
Skip to main content
Here is a list of the Python keywords. Enter any keyword to get more help.
False class from or
None continue global pass
True def if raise
and del import return
as elif in try
assert else is while
async except lambda with
await finally nonlocal yield
break for not
a, b, c = 1, 2, 3
print(a, b, c)
1 2 3
009 – Escape Sequences Characters
Escape Sequences Characters
\b => Back Space
\newline => Escape New Line + \
\ => Escape Back Slash
‘ => Escape Single Quotes
” => Escape Double Quotes
\n => Line Feed
\r => Carriage Return
\t => Horizontal Tab
\xhh => Character Hex Value
print("hello\bword")
hellword
print("hello\
python")
Skip to main content
hellopython
print("i love \\python")
i love \python
print("i love sinqle quote \"")
i love sinqle quote "
print("hello \nworld")
hello
world
print("123456\rabcd")
abcd56
print("hello \tworld")
hello world
print("\x4F\x73")
Os
010 – Concatenation And Trainings
msg = "i love"
lang = "python" Skip to main content
print(msg + " "+lang)
i love python
full = msg + " " + lang
print(full)
i love python
a = "first\
second\
third"
b = "A\
B\
C"
print(a)
print(b)
first second third
A B C
print(a + "\n"+b)
first second third
A B C
print("hi"+1) will produce an error
print(msg + " 1")
i love 1
011 – Strings
myStringOne = "this is 'signle quote'"
print(myStringOne)
Skip to main content
this is 'signle quote'
myStringTwo = "This is Double Quotes"
print(myStringTwo)
This is Double Quotes
myStringThree = 'This is Single Quote "Test"'
print(myStringThree)
This is Single Quote "Test"
myStringFour = "This is Double Quotes 'Test'"
print(myStringFour)
This is Double Quotes 'Test'
multi = """first
second
third
"""
print(multi)
first
second
third
test = '''
"First" second 'third'
'''
print(test)
"First" second 'third'
012 – Strings – Indexing and Slicing
Skip to main content
[1] All Data in Python is Object
[2] Object Contain Elements
[3] Every Element Has Its Own Index
[4] Python Use Zero Based Indexing ( Index Start From Zero )
[5] Use Square Brackets To Access Element
[6] Enable Accessing Parts Of Strings, Tuples or Lists
# index access single item
string = "i love python"
print(string[0])
print(string[-1])
print(string[9])
i
n
t
# slicing access multiple sequence items
# [start:end]
# [start:end:steps]
print(string[8:11])
print(string[:10])
print(string[5:10])
print(string[5])
print(string[:])
print(string[0::1])
print(string[::1])
print(string[::2])
yth
i love pyt
e pyt
e
i love python
i love python
i love python
ilv yhn
013 – Strings Methods Part 1
a = " i love python "
print(len(a))
print(a.strip())
Skip to main content
print(a.rstrip())
print(a.lstrip())
18
i love python
i love python
i love python
a = " hi "
print(a.strip())
hi
a = "#####hola#####"
print(a.strip("#"))
print(a.rstrip("#"))
print(a.lstrip("#"))
hola
#####hola
hola#####
b = "I Love 2d Graphics and 3g Technology and python"
print(b.title())
print(b.capitalize())
I Love 2D Graphics And 3G Technology And Python
I love 2d graphics and 3g technology and python
c, d, e = "1", "20", "3"
print(c.zfill(3))
print(d.zfill(3))
print(e.zfill(3))
001
020
003
g = "aHmed"
print(g.lower())
Skip to main content
print(g.upper())
ahmed
AHMED
014 – Strings Methods Part 2
a = "I love python"
print(a.split())
['I', 'love', 'python']
a = "I-love-python"
print(a.split("-"))
['I', 'love', 'python']
a = "I-love-python"
print(a.split("-", 1))
['I', 'love-python']
d = "I-love-python"
print(d.rsplit("-", 1))
['I-love', 'python']
e = "ahmed"
print(e.center(15))
print(e.center(15, "#"))
ahmed
#####ahmed#####
Skip to main content
f = "I and me and ahmed"
print(f.count("and"))
print(f.count("and", 0, 10)) # start and end
2
1
g = "I love Python"
print(g.swapcase())
i LOVE pYTHON
print(g.startswith("i"))
print(g.startswith("I"))
print(g.startswith("l", 2, 12)) # start from second index
False
True
True
print(g.endswith("n"))
print(g.endswith("e", 2, 6))
True
True
015 – Strings Methods Part 3
a = "I Love Python"
print(a.index("P")) # Index Number 7
print(a.index("P", 0, 10)) # Index Number 7
# print(a.index("P", 0, 5)) # Through Error
7
7
Skip to main content
b = "I Love Python"
print(b.find("P")) # Index Number 7
print(b.find("P", 0, 10)) # Index Number 7
print(b.find("P", 0, 5)) # -1
7
7
-1
c = "ahmed"
print(c.rjust(10))
print(c.rjust(10, "#"))
ahmed
#####ahmed
d = "ahmed"
print(d.ljust(10))
print(d.ljust(10, "#"))
ahmed
ahmed#####
e = """First Line
Second Line
Third Line"""
print(e.splitlines())
['First Line', 'Second Line', 'Third Line']
f = "First Line\nSecond Line\nThird Line"
print(f.splitlines())
['First Line', 'Second Line', 'Third Line']
g = "Hello\tWorld\tI\tLove\tPython"
print(g.expandtabs(5))
Skip to main content
Hello World I Love Python
one = "I Love Python And 3G"
two = "I Love Python And 3g"
print(one.istitle())
print(two.istitle())
True
False
three = " "
four = ""
print(three.isspace())
print(four.isspace())
True
False
five = 'i love python'
six = 'I Love Python'
print(five.islower())
print(six.islower())
True
False
# to check if i can use a name as a variable
seven = "osama_elzero"
eight = "OsamaElzero100"
nine = "Osama--Elzero100"
print(seven.isidentifier())
print(eight.isidentifier())
print(nine.isidentifier())
True
True
False
x = "AaaaaBbbbbb"
y = "AaaaaBbbbbb111"
Skip to main content
print(x.isalpha())
print(y.isalpha())
True
False
u = "AaaaaBbbbbb"
z = "AaaaaBbbbbb111"
print(u.isalnum())
print(z.isalnum())
True
True
016 – Strings Methods Part 4
# replace(Old Value, New Value, Count)
a = "Hello One Two Three One One"
print(a.replace("One", "1"))
print(a.replace("One", "1", 1))
print(a.replace("One", "1", 2))
Hello 1 Two Three 1 1
Hello 1 Two Three One One
Hello 1 Two Three 1 One
myList = ["Osama", "Mohamed", "Elsayed"]
print("-".join(myList))
print(" ".join(myList))
print(", ".join(myList))
print(type(", ".join(myList)))
Osama-Mohamed-Elsayed
Osama Mohamed Elsayed
Osama, Mohamed, Elsayed
<class 'str'>
017 – Strings Formatting Old Way
Skip to main content
name = "Osama"
age = 36
rank = 10
print("My Name is: " + name)
My Name is: Osama
print("My Name is: " + name + " and My Age is: " + age)
type error, cant concatenate string with int
print("My Name is: %s" % "Osama")
print("My Name is: %s" % name)
print("My Name is: %s and My Age is: %d" % (name, age))
print("My Name is: %s and My Age is: %d and My Rank is: %f" % (name, age, ra
My Name is: Osama
My Name is: Osama
My Name is: Osama and My Age is: 36
My Name is: Osama and My Age is: 36 and My Rank is: 10.000000
n = "Osama"
l = "Python"
y = 10
print("My Name is %s Iam %s Developer With %d Years Exp" % (n, l, y))
My Name is Osama Iam Python Developer With 10 Years Exp
# control flow point number
myNumber = 10
print("My Number is: %d" % myNumber)
print("My Number is: %f" % myNumber)
print("My Number is: %.2f" % myNumber)
My Number is: 10
My Number is: 10.000000
My Number is: 10.00
Skip to main content
# Truncate string
myLongString = "Hello People of Elzero Web School I Love You All"
print("Message is %s" % myLongString)
print("Message is %.5s" % myLongString)
Message is Hello People of Elzero Web School I Love You All
Message is Hello
018 – Strings Formatting New Way
name = "Osama"
age = 36
rank = 10
print("My Name is: " + name)
My Name is: Osama
print("My Name is: {}".format("Osama"))
print("My Name is: {}".format(name))
print("My Name is: {} My Age: {}".format(name, age))
print("My Name is: {:s} Age: {:d} & Rank is: {:f}".format(name, age, rank))
My Name is: Osama
My Name is: Osama
My Name is: Osama My Age: 36
My Name is: Osama Age: 36 & Rank is: 10.000000
{:s} => String {:d} => Number {:f} => Float
n = "Osama"
l = "Python"
y = 10
print("My Name is {} Iam {} Developer With {:d} Years Exp".format(n, l, y))
My Name is Osama Iam Python Developer With 10 Years Exp
Skip to main content
# Control Floating Point Number
myNumber = 10
print("My Number is: {:d}".format(myNumber))
print("My Number is: {:f}".format(myNumber))
print("My Number is: {:.2f}".format(myNumber))
My Number is: 10
My Number is: 10.000000
My Number is: 10.00
# Truncate String
myLongString = "Hello Peoples of Elzero Web School I Love You All"
print("Message is {}".format(myLongString))
print("Message is {:.5s}".format(myLongString))
print("Message is {:.13s}".format(myLongString))
Message is Hello Peoples of Elzero Web School I Love You All
Message is Hello
Message is Hello Peoples
# format money
myMoney = 500162350198
print("My Money in Bank Is: {:d}".format(myMoney))
print("My Money in Bank Is: {:_d}".format(myMoney))
print("My Money in Bank Is: {:,d}".format(myMoney))
My Money in Bank Is: 500162350198
My Money in Bank Is: 500_162_350_198
My Money in Bank Is: 500,162,350,198
{:&d} will produce an error
# ReArrange Items
a, b, c = "One", "Two", "Three"
print("Hello {} {} {}".format(a, b, c))
print("Hello {1} {2} {0}".format(a, b, c))
print("Hello {2} {0} {1}".format(a, b, c))
Hello One Two Three
Hello Two Three One
Hello Three One Two
Skip to main content
x, y, z = 10, 20, 30
print("Hello {} {} {}".format(x, y, z))
print("Hello {1:d} {2:d} {0:d}".format(x, y, z))
print("Hello {2:f} {0:f} {1:f}".format(x, y, z))
print("Hello {2:.2f} {0:.4f} {1:.5f}".format(x, y, z))
Hello 10 20 30
Hello 20 30 10
Hello 30.000000 10.000000 20.000000
Hello 30.00 10.0000 20.00000
# Format in Version 3.6+
myName = "Osama"
myAge = 36
print("My Name is : {myName} and My Age is : {myAge}")
print(f"My Name is : {myName} and My Age is : {myAge}")
My Name is : {myName} and My Age is : {myAge}
My Name is : Osama and My Age is : 36
019 – Numbers
# Integer
print(type(1))
print(type(100))
print(type(10))
print(type(-10))
print(type(-110))
<class 'int'>
<class 'int'>
<class 'int'>
<class 'int'>
<class 'int'>
# Float
print(type(1.500))
print(type(100.99))
print(type(-10.99))
print(type(0.99))
print(type(-0.99))
Skip to main content
<class 'float'>
<class 'float'>
<class 'float'>
<class 'float'>
<class 'float'>
# Complex
myComplexNumber = 5+6j
print(type(myComplexNumber))
print("Real Part Is: {}".format(myComplexNumber.real))
print("Imaginary Part Is: {}".format(myComplexNumber.imag))
<class 'complex'>
Real Part Is: 5.0
Imaginary Part Is: 6.0
[1] You Can Convert From Int To Float or Complex
[2] You Can Convert From Float To Int or Complex
[3] You Cannot Convert Complex To Any Type
print(100)
print(float(100))
print(complex(100))
100
100.0
(100+0j)
print(10.50)
print(int(10.50))
print(complex(10.50))
10.5
10
(10.5+0j)
print(10+9j)
# print(int(10+9j)) error
(10+9j)
Skip to main content
020 – Arithmetic Operators
[+] Addition
[-] Subtraction
[*] Multiplication
[/] Division
[%] Modulus
[**] Exponent
[//] Floor Division
# Addition
print(10 + 30)
print(-10 + 20)
print(1 + 2.66)
print(1.2 + 1.2)
40
10
3.66
2.4
# Subtraction
print(60 - 30)
print(-30 - 20)
print(-30 - -20)
print(5.66 - 3.44)
30
-50
-10
2.22
# Multiplication
print(10 * 3)
print(5 + 10 * 100)
print((5 + 10) * 100)
30
1005
1500
Skip to main content
# Division
print(100 / 20)
print(int(100 / 20))
5.0
5
# Modulus
print(8 % 2)
print(9 % 2)
print(20 % 5)
print(22 % 5)
0
1
0
2
# Exponent
print(2 ** 5)
print(2 * 2 * 2 * 2 * 2)
print(5 ** 4)
print(5 * 5 * 5 * 5)
32
32
625
625
# Floor Division
print(100 // 20)
print(119 // 20)
print(120 // 20)
print(140 // 20)
print(142 // 20)
5
5
6
7
7
Skip to main content
021 – Lists
[1] List Items Are Enclosed in Square Brackets
[2] List Are Ordered, To Use Index To Access Item
[3] List Are Mutable => Add, Delete, Edit
[4] List Items Is Not Unique
[5] List Can Have Different Data Types
myAwesomeList = ["One", "Two", "One", 1, 100.5, True]
print(myAwesomeList)
print(myAwesomeList[1])
print(myAwesomeList[-1])
print(myAwesomeList[-3])
['One', 'Two', 'One', 1, 100.5, True]
Two
True
1
print(myAwesomeList[1:4])
print(myAwesomeList[:4])
print(myAwesomeList[1:])
['Two', 'One', 1]
['One', 'Two', 'One', 1]
['Two', 'One', 1, 100.5, True]
print(myAwesomeList[::1])
print(myAwesomeList[::2])
['One', 'Two', 'One', 1, 100.5, True]
['One', 'One', 100.5]
print(myAwesomeList)
myAwesomeList[1] = 2
myAwesomeList[-1] = False
print(myAwesomeList)
['One', 'Two', 'One', 1, 100.5, True]
['One', 2, 'One', 1, 100.5, False]
Skip to main content
myAwesomeList[0:3] = []
print(myAwesomeList)
[1, 100.5, False]
myAwesomeList[0:2] = ["A", "B"]
print(myAwesomeList)
['A', 'B', False]
022 – Lists Methods Part 1
myFriends = ["Osama", "Ahmed", "Sayed"]
myOldFriends = ["Haytham", "Samah", "Ali"]
print(myFriends)
print(myOldFriends)
['Osama', 'Ahmed', 'Sayed']
['Haytham', 'Samah', 'Ali']
myFriends.append("Alaa")
myFriends.append(100)
myFriends.append(150.200)
myFriends.append(True)
print(myFriends)
['Osama', 'Ahmed', 'Sayed', 'Alaa', 100, 150.2, True]
myFriends.append(myOldFriends)
print(myFriends)
['Osama', 'Ahmed', 'Sayed', 'Alaa', 100, 150.2, True, ['Haytham', 'Samah', '
print(myFriends[2])
print(myFriends[6])
print(myFriends[7]) Skip to main content
Sayed
True
['Haytham', 'Samah', 'Ali']
print(myFriends[7][2])
Ali
a = [1, 2, 3, 4]
b = ["A", "B", "C"]
print(a)
[1, 2, 3, 4]
a.extend(b)
print(a)
[1, 2, 3, 4, 'A', 'B', 'C']
x = [1, 2, 3, 4, 5, "Osama", True, "Osama", "Osama"]
x.remove("Osama")
print(x)
[1, 2, 3, 4, 5, True, 'Osama', 'Osama']
y = [1, 2, 100, 120, -10, 17, 29]
y.sort()
print(y)
[-10, 1, 2, 17, 29, 100, 120]
y.sort(reverse=True)
print(y)
[120, 100, 29, 17, 2, 1, -10]
Skip to main content
m = ["A", "Z", "C"]
m.sort()
print(m)
['A', 'C', 'Z']
Sort can’t sort a list that contains both of strings and numbers.
z = [10, 1, 9, 80, 100, "Osama", 100]
z.reverse()
print(z)
[100, 'Osama', 100, 80, 9, 1, 10]
023 – Lists Methods Part 2
a = [1, 2, 3, 4]
a.clear()
print(a)
[]
b = [1, 2, 3, 4]
c = b.copy()
print(b)
print(c)
[1, 2, 3, 4]
[1, 2, 3, 4]
b.append(5)
print(b)
print(c)
[1, 2, 3, 4, 5]
[1, 2, 3, 4]
Skip to main content
d = [1, 2, 3, 4, 3, 9, 10, 1, 2, 1]
print(d.count(1))
e = ["Osama", "Ahmed", "Sayed", "Ramy", "Ahmed", "Ramy"]
print(e.index("Ramy"))
f = [1, 2, 3, 4, 5, "A", "B"]
print(f)
f.insert(0, "Test")
f.insert(-1, "Test")
print(f)
[1, 2, 3, 4, 5, 'A', 'B']
['Test', 1, 2, 3, 4, 5, 'A', 'Test', 'B']
g = [1, 2, 3, 4, 5, "A", "B"]
print(g.pop(-3))
024 – Tuples Methods Part 1
[1] Tuple Items Are Enclosed in Parentheses
[2] You Can Remove The Parentheses If You Want
[3] Tuple Are Ordered, To Use Index To Access Item
[4] Tuple Are Immutable => You Cant Add or Delete
[5] Tuple Items Is Not Unique
[6] Tuple Can Have Different Data Types
[7] Operators Used in Strings and Lists Available In Tuples
myAwesomeTupleOne = ("Osama", "Ahmed")
myAwesomeTupleTwo = "Osama", "Ahmed"
Skip to main content
print(myAwesomeTupleOne)
print(myAwesomeTupleTwo)
('Osama', 'Ahmed')
('Osama', 'Ahmed')
print(type(myAwesomeTupleOne))
print(type(myAwesomeTupleTwo))
<class 'tuple'>
<class 'tuple'>
myAwesomeTupleThree = (1, 2, 3, 4, 5)
print(myAwesomeTupleThree[0])
print(myAwesomeTupleThree[-1])
print(myAwesomeTupleThree[-3])
1
5
3
# Tuple Assign Values
myAwesomeTupleFour = (1, 2, 3, 4, 5)
print(myAwesomeTupleFour)
(1, 2, 3, 4, 5)
myAwesomeTupleFour[2] = "Three"
print(myAwesomeTupleFour)
‘tuple’ object does not support item assignment
myAwesomeTupleFive = ("Osama", "Osama", 1, 2, 3, 100.5, True)
print(myAwesomeTupleFive[1])
print(myAwesomeTupleFive[-1])
Osama
True
Skip to main content
025 – Tuples Methods Part 2
myTuple1 = ("Osama",)
myTuple2 = "Osama",
print(myTuple1)
print(myTuple2)
('Osama',)
('Osama',)
print(type(myTuple1))
print(type(myTuple2))
<class 'tuple'>
<class 'tuple'>
print(len(myTuple1))
print(len(myTuple2))
1
1
a = (1, 2, 3, 4)
b = (5, 6)
c = a + b
d = a + ("A", "B", True) + b
print(c)
print(d)
(1, 2, 3, 4, 5, 6)
(1, 2, 3, 4, 'A', 'B', True, 5, 6)
myString = "Osama"
myList = [1, 2]
myTuple = ("A", "B")
print(myString * 6)
print(myList * 6)
print(myTuple * 6)
Skip to main content
OsamaOsamaOsamaOsamaOsamaOsama
[1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2]
('A', 'B', 'A', 'B', 'A', 'B', 'A', 'B', 'A', 'B', 'A', 'B')
a = (1, 3, 7, 8, 2, 6, 5, 8)
print(a.count(8))
b = (1, 3, 7, 8, 2, 6, 5)
print("The Position of Index Is: {:d}".format(b.index(7)))
print(f"The Position of Index Is: {b.index(7)}")
The Position of Index Is: 2
The Position of Index Is: 2
# Tuple Destruct
a = ("A", "B", 4, "C")
x, y, _, z = a
print(x)
print(y)
print(z)
A
B
C
026 – Set
[1] Set Items Are Enclosed in Curly Braces
[2] Set Items Are Not Ordered And Not Indexed
[3] Set Indexing and Slicing Cant Be Done
[4] Set Has Only Immutable Data Types (Numbers, Strings, Tuples) List and Dict Are Not
[5] Set Items Is Unique
# Not Ordered And Not Indexed
Skip to main content
mySetOne = {"Osama", "Ahmed", 100}
print(mySetOne)
{'Osama', 'Ahmed', 100}
print(mySetOne[0]) will produce an error.
Slicing Cant Be Done
mySetTwo = {1, 2, 3, 4, 5, 6}
print(mySetTwo[0:3])
Will also produce an error.
Has Only Immutable Data Types
mySetThree = {"Osama", 100, 100.5, True, [1, 2, 3]}
Error, unhashable type: ‘list’
mySetThree = {"Osama", 100, 100.5, True, (1, 2, 3)}
print(mySetThree)
{True, 'Osama', 100.5, 100, (1, 2, 3)}
# Items are Unique
mySetFour = {1, 2, "Osama", "One", "Osama", 1}
print(mySetFour)
{1, 2, 'One', 'Osama'}
027 – Set Methods Part 1
a = {1, 2, 3}
a.clear()
print(a)
Skip to main content
set()
b = {"One", "Two", "Three"}
c = {"1", "2", "3"}
x = {"Zero", "Cool"}
print(b | c)
print(b.union(c))
print(b.union(c, x))
{'2', 'One', '3', 'Two', 'Three', '1'}
{'2', 'One', '3', 'Two', 'Three', '1'}
{'2', 'One', '3', 'Two', 'Cool', 'Three', '1', 'Zero'}
d = {1, 2, 3, 4}
d.add(5)
d.add(6)
print(d)
{1, 2, 3, 4, 5, 6}
e = {1, 2, 3, 4}
f = e.copy()
print(e)
print(f)
e.add(6)
print(e)
print(f)
{1, 2, 3, 4}
{1, 2, 3, 4}
{1, 2, 3, 4, 6}
{1, 2, 3, 4}
g = {1, 2, 3, 4}
g.remove(1)
# g.remove(7) will remove an error
print(g)
{2, 3, 4}
Skip to main content
h = {1, 2, 3, 4}
h.discard(1)
h.discard(7) # wont produce an error
print(h)
{2, 3, 4}
i = {"A", True, 1, 2, 3, 4, 5}
print(i.pop())
True
j = {1, 2, 3}
k = {1, "A", "B", 2}
j.update(['Html', "Css"])
j.update(k)
print(j)
{1, 2, 3, 'Html', 'B', 'A', 'Css'}
028 – Set Methods Part 2
a = {1, 2, 3, 4}
b = {1, 2, 3, "Osama", "Ahmed"}
print(a)
print(a.difference(b)) # a - b
print(a)
{1, 2, 3, 4}
{4}
{1, 2, 3, 4}
c = {1, 2, 3, 4}
d = {1, 2, "Osama", "Ahmed"}
print(c)
c.difference_update(d) # c - d
print(c)
Skip to main content
{1, 2, 3, 4}
{3, 4}
e = {1, 2, 3, 4, "X", "Osama"}
f = {"Osama", "X", 2}
print(e)
print(e.intersection(f)) # e & f
print(e)
{1, 2, 3, 4, 'X', 'Osama'}
{'Osama', 2, 'X'}
{1, 2, 3, 4, 'X', 'Osama'}
g = {1, 2, 3, 4, "X", "Osama"}
h = {"Osama", "X", 2}
print(g)
g.intersection_update(h) # g & h
print(g)
{1, 2, 3, 4, 'X', 'Osama'}
{'Osama', 2, 'X'}
i = {1, 2, 3, 4, 5}
j = {0, 3, 4, 5}
print(i)
print(i.symmetric_difference(j)) # i ^ j
print(i)
{1, 2, 3, 4, 5}
{0, 1, 2}
{1, 2, 3, 4, 5}
i = {1, 2, 3, 4, 5}
j = {0, 3, 4, 5}
print(i)
i.symmetric_difference_update(j) # i ^ j
print(i)
{1, 2, 3, 4, 5}
{0, 1, 2}
Skip to main content
029 – Set Methods Part 3
a = {1, 2, 3, 4}
b = {1, 2, 3}
c = {1, 2, 3, 4, 5}
print(a.issuperset(b))
print(a.issuperset(c))
True
False
d = {1, 2, 3, 4}
e = {1, 2, 3}
f = {1, 2, 3, 4, 5}
print(d.issubset(e))
print(d.issubset(f))
False
True
g = {1, 2, 3, 4}
h = {1, 2, 3}
i = {10, 11, 12}
print(g.isdisjoint(h))
print(g.isdisjoint(i))
False
True
030 – Dictionary
[1] Dict Items Are Enclosed in Curly Braces
[2] Dict Items Are Contains Key : Value
[3] Dict Key Need To Be Immutable => (Number, String, Tuple) List Not Allowed
[4] Dict Value Can Have Any Data Types
[5] Dict Key Need To Be Unique
[6] Dict Is Not Ordered You Access Its Element With Key
Skip to main content
user = {
"name": "Osama",
"age": 36,
"country": "Egypt",
"skills": ["Html", "Css", "JS"],
"rating": 10.5
}
print(user)
{'name': 'Osama', 'age': 36, 'country': 'Egypt', 'skills': ['Html', 'Css', '
user = {
"name": "Osama",
"age": 36,
"country": "Egypt",
"skills": ["Html", "Css", "JS"],
"rating": 10.5,
"name": "Ahmed"
}
print(user)
{'name': 'Ahmed', 'age': 36, 'country': 'Egypt', 'skills': ['Html', 'Css', '
Notice that it prints Ahmed not Osama as it is defined later.
print(user['country'])
print(user.get("country"))
Egypt
Egypt
print(user.keys())
dict_keys(['name', 'age', 'country', 'skills', 'rating'])
print(user.values())
dict_values(['Ahmed', 36, 'Egypt', ['Html', 'Css', 'JS'], 10.5])
Skip to main content
languages = {
"One": {
"name": "Html",
"progress": "80%"
},
"Two": {
"name": "Css",
"progress": "90%"
},
"Three": {
"name": "Js",
"progress": "90%"
}
}
print(languages)
{'One': {'name': 'Html', 'progress': '80%'}, 'Two': {'name': 'Css', 'progres
print(languages['One'])
{'name': 'Html', 'progress': '80%'}
print(languages['Three']['name'])
Js
print(len(languages))
print(len(languages["Two"]))
frameworkOne = {
"name": "Vuejs", Skip to main content
"progress": "80%"
}
frameworkTwo = {
"name": "ReactJs",
"progress": "80%"
}
frameworkThree = {
"name": "Angular",
"progress": "80%"
}
allFramework = {
"one": frameworkOne,
"two": frameworkTwo,
"three": frameworkThree
}
print(allFramework)
{'one': {'name': 'Vuejs', 'progress': '80%'}, 'two': {'name': 'ReactJs', 'pr
031 – Dictionary Methods Part 1
user = {
"name": "Osama"
}
print(user)
user.clear()
print(user)
{'name': 'Osama'}
{}
member = {
"name": "Osama"
}
print(member)
member["age"] = 36
print(member)
member.update({"country": "Egypt"})
print(member)
# Both ways are equivalent.
{'name': 'Osama'}
{'name': 'Osama', 'age': 36}
{'name': 'Osama', 'age': 36, 'country': 'Egypt'}
Skip to main content
main = {
"name": "Osama"
}
b = main.copy()
print(b)
main.update({"skills": "Fighting"})
print(main)
print(b)
{'name': 'Osama'}
{'name': 'Osama', 'skills': 'Fighting'}
{'name': 'Osama'}
print(main.keys())
dict_keys(['name', 'skills'])
print(main.values())
dict_values(['Osama', 'Fighting'])
032 – Dictionary Methods Part 2
user = {
"name": "Osama"
}
print(user)
user.setdefault("name", "Ahmed")
user.setdefault("age", 36)
print(user)
{'name': 'Osama'}
{'name': 'Osama', 'age': 36}
print(user.setdefault("name", "Ahmed"))
Osama
Skip to main content
member = {
"name": "Osama",
"skill": "PS4"
}
print(member)
member.update({"age": 36})
print(member)
print(member.popitem())
print(member)
{'name': 'Osama', 'skill': 'PS4'}
{'name': 'Osama', 'skill': 'PS4', 'age': 36}
('age', 36)
{'name': 'Osama', 'skill': 'PS4'}
view = {
"name": "Osama",
"skill": "XBox"
}
allItems = view.items()
print(view)
{'name': 'Osama', 'skill': 'XBox'}
view["age"] = 36
print(view)
{'name': 'Osama', 'skill': 'XBox', 'age': 36}
print(allItems)
dict_items([('name', 'Osama'), ('skill', 'XBox'), ('age', 36)])
a = ('MyKeyOne', 'MyKeyTwo', 'MyKeyThree')
b = "X"
print(dict.fromkeys(a, b))
{'MyKeyOne': 'X', 'MyKeyTwo': 'X', 'MyKeyThree': 'X'}
Skip to main content
user = {
"name": "Ahmed"
}
me = user
print(me)
{'name': 'Ahmed'}
user["age"] = 21
print(me)
{'name': 'Ahmed', 'age': 21}
Notice that me got updated because me and user share the same data.
033 – Boolean
[1] In Programming You Need to Known Your If Your Code Output is True Or False
[2] Boolean Values Are The Two Constant Objects False + True.
name = " "
print(name.isspace())
True
name = "Ahmed"
print(name.isspace())
False
print(100 > 200)
print(100 > 100)
print(100 > 90)
Skip to main content
False
False
True
print(bool("Osama"))
print(bool(100))
print(bool(100.95))
print(bool(True))
print(bool([1, 2, 3, 4, 5]))
True
True
True
True
True
print(bool(0))
print(bool(""))
print(bool(''))
print(bool([]))
print(bool(False))
print(bool(()))
print(bool({}))
print(bool(None))
False
False
False
False
False
False
False
False
034 – Boolean Operators
name = "ahmed"
age = 21
print(name == "ahmed" and age == 21)
True
Skip to main content
print(name == "ahmed" and age > 21)
False
print(name == "ahmed" or age > 21)
True
print(name == "mohamed" or age > 21)
False
print(not age > 21)
True
print(not (name == "ahmed" and age > 21))
True
035 – Assignment Operators
x = 10
y = 20
x = x+y
print(x)
30
A better way
a = 10
b = 20 Skip to main content
a += b
print(a)
30
x = 30
y = 20
x = x-y
print(x)
10
a = 30
b = 20
a -= b
print(a)
10
Var One = Self [Operator] Var Two
Var One [Operator]= Var Two
036 – Comparison Operators
[ == ] Equal
[ != ] Not Equal
[ > ] Greater Than
[ < ] Less Than
[ >= ] Greater Than Or Equal
[ <= ] Less Than Or Equal
print(100 == 100)
print(100 == 200)
print(100 == 100.00)
True
False
True
Skip to main content
print(100 != 100)
print(100 != 200)
print(100 != 100.00)
False
True
False
print(100 > 100)
print(100 > 200)
print(100 > 100.00)
print(100 > 40)
False
False
False
True
print(100 < 100)
print(100 < 200)
print(100 < 100.00)
print(100 < 40)
False
True
False
False
print(100 >= 100)
print(100 >= 200)
print(100 >= 100.00)
print(100 >= 40)
True
False
True
True
print(100 <= 100)
print(100 <= 200)
print(100 <= 100.00)
print(100 <= 40)
Skip to main content
True
True
True
False
037 – Type Conversion
a = 10
print(type(a))
print(type(str(a)))
<class 'int'>
<class 'str'>
c = "Osama"
d = [1, 2, 3, 4, 5]
e = {"A", "B", "C"}
f = {"A": 1, "B": 2}
print(tuple(c))
print(tuple(d))
print(tuple(e))
print(tuple(f))
('O', 's', 'a', 'm', 'a')
(1, 2, 3, 4, 5)
('B', 'A', 'C')
('A', 'B')
c = "Osama"
d = (1, 2, 3, 4, 5)
e = {"A", "B", "C"}
f = {"A": 1, "B": 2}
print(list(c))
print(list(d))
print(list(e))
print(list(f))
['O', 's', 'a', 'm', 'a']
[1, 2, 3, 4, 5]
['B', 'A', 'C']
['A', 'B']
Skip to main content
c = "Osama"
d = (1, 2, 3, 4, 5)
e = ["A", "B", "C"]
f = {"A": 1, "B": 2}
print(set(c))
print(set(d))
print(set(e))
print(set(f))
{'m', 's', 'O', 'a'}
{1, 2, 3, 4, 5}
{'B', 'A', 'C'}
{'B', 'A'}
d = (("A", 1), ("B", 2), ("C", 3))
e = [["One", 1], ["Two", 2], ["Three", 3]]
print(dict(d))
print(dict(e))
{'A': 1, 'B': 2, 'C': 3}
{'One': 1, 'Two': 2, 'Three': 3}
038 – User Input
fName = input('What\'s Is Your First Name?')
mName = input('What\'s Is Your Middle Name?')
lName = input('What\'s Is Your Last Name?')
fName = fName.strip().capitalize()
mName = mName.strip().capitalize()
lName = lName.strip().capitalize()
print(f"Hello {fName} {mName:.1s} {lName} Happy To See You.")
Hello Ahmed H Darwish Happy To See You.
039 – Practical – Email Slice
email = "
[email protected]"
Skip to main content
print(email[:email.index("@")])
Osama
theName = input('What\'s Your Name ?').strip().capitalize()
theEmail = input('What\'s Your Email ?').strip()
theUsername = theEmail[:theEmail.index("@")]
theWebsite = theEmail[theEmail.index("@") + 1:]
print(f"Hello {theName} Your Email Is {theEmail}")
print(f"Your Username Is {theUsername} \nYour Website Is {theWebsite}")
Your Username Is ahmed
Your Website Is mail.com
040 – Practical – Your Age In Full Details
age = int(input('What\'s Your Age ? ').strip())
months = age * 12
weeks = months * 4
days = age * 365
hours = days * 24
minutes = hours * 60
seconds = minutes * 60
print('You Lived For:')
print(f"{months} Months.")
print(f"{weeks:,} Weeks.")
print(f"{days:,} Days.")
print(f"{hours:,} Hours.")
print(f"{minutes:,} Minutes.")
print(f"{seconds:,} Seconds.")
You Lived For:
252 Months.
1,008 Weeks.
Skip to main content
7,665 Days.
183,960 Hours.
11,037,600 Minutes.
662,256,000 Seconds.
041 - Control Flow If, Elif, Else
uName = "Osama"
uCountry = "Kuwait"
cName = "Python Course"
cPrice = 100
if uCountry == "Egypt":
print(f"Hello {uName} Because You Are From {uCountry}")
print(f"The Course \"{cName}\" Price Is: ${cPrice - 80}")
elif uCountry == "KSA":
print(f"Hello {uName} Because You Are From {uCountry}")
print(f"The Course \"{cName}\" Price Is: ${cPrice - 60}")
elif uCountry == "Kuwait":
print(f"Hello {uName} Because You Are From {uCountry}")
print(f"The Course \"{cName}\" Price Is: ${cPrice - 50}")
else:
print(f"Hello {uName} Because You Are From {uCountry}")
print(f"The Course \"{cName}\" Price Is: ${cPrice - 30}")
Hello Osama Because You Are From Kuwait
The Course "Python Course" Price Is: $50
042 - Control Flow Nested If and Trainings
uName = "Osama"
isStudent = "Yes"
uCountry = "Egypt"
cName = "Python Course"
cPrice = 100
if uCountry == "Egypt" or uCountry == "KSA" or uCountry == "Qatar":
Skip to main content
if isStudent == "Yes":
print(f"Hi {uName} Because U R From {uCountry} And Student")
print(f"The Course \"{cName}\" Price Is: ${cPrice - 90}")
else:
print(f"Hi {uName} Because U R From {uCountry}")
print(f"The Course \"{cName}\" Price Is: ${cPrice - 80}")
elif uCountry == "Kuwait" or uCountry == "Bahrain":
print(f"Hi {uName} Because U R From {uCountry}")
print(f"The Course \"{cName}\" Price Is: ${cPrice - 50}")
else:
print(f"Hi {uName} Because U R From {uCountry}")
print(f"The Course \"{cName}\" Price Is: ${cPrice - 30}")
Hi Osama Because U R From Egypt And Student
The Course "Python Course" Price Is: $10
043 – Control Flow – Ternary Conditional
Operator
country = "A"
if country == "Egypt":
print(f"The Weather in {country} Is 15")
elif country == "KSA":
print(f"The Weather in {country} Is 30")
else:
print("Country is Not in The List")
Country is Not in The List
movieRate = 18
age = 16
if age < movieRate:
print("Movie S Not Good 4U") # Condition If True
else:
Skip to main content
print("Movie S Good 4U And Happy Watching") # Condition If False
Movie S Not Good 4U
print("Movie S Not Good 4U" if age <
movieRate else "Movie S Good 4U And Happy Watching")
Movie S Not Good 4U
Condition If True | If Condition | Else | Condition If False
044 – Calculate Age Advanced Version And
Training
print("#" * 80)
print(" You Can Write The First Letter Or Full Name of The Time Unit ".cente
print("#" * 80)
############################################################################
######### You Can Write The First Letter Or Full Name of The Time Unit #####
############################################################################
# Collect Age Data
age = input("Please Write Your Age").strip()
# Collect Time Unit Data
unit = input("Please Choose Time Unit: Months, Weeks, Days ").strip().lower(
# Get Time Units
months = int(age) * 12
weeks = months * 4
days = int(age) * 365
if unit == 'months' or unit == 'm':
print("You Choosed The Skip
Unitto Months")
main content
print(f"You Lived For {months:,} Months.")
elif unit == 'weeks' or unit == 'w':
print("You Choosed The Unit Weeks")
print(f"You Lived For {weeks:,} Weeks.")
elif unit == 'days' or unit == 'd':
print("You Choosed The Unit Days")
print(f"You Lived For {days:,} Days.")
You Choosed The Unit Days
You Lived For 7,665 Days.
045 – Membership Operators
# String
name = "Osama"
print("s" in name)
print("a" in name)
print("A" in name)
True
True
False
# List
friends = ["Ahmed", "Sayed", "Mahmoud"]
print("Osama" in friends)
print("Sayed" in friends)
print("Mahmoud" not in friends)
False
True
False
# Using In and Not In With Condition
countriesOne = ["Egypt", "KSA", "Kuwait", "Bahrain", "Syria"]
countriesOneDiscount = 80
countriesTwo = ["Italy", "USA"]
countriesTwoDiscount = 50
Skip to main content
myCountry = "Italy"
if myCountry in countriesOne:
print(f"Hello You Have A Discount Equal To ${countriesOneDiscount}")
elif myCountry in countriesTwo:
print(f"Hello You Have A Discount Equal To ${countriesTwoDiscount}")
else:
print("You Have No Discount")
Hello You Have A Discount Equal To $50
046 - Practical Membership Control
# List Contains Admins
admins = ["Ahmed", "Osama", "Sameh", "Manal", "Rahma", "Mahmoud", "Enas"]
# Login
name = input("Please Type Your Name ").strip().capitalize()
# If Name is In Admin
if name in admins:
print(f"Hello {name}, Welcome Back.")
option = input("Delete Or Update Your Name ?").strip().capitalize()
# Update Option
if option == 'Update' or option == 'U':
theNewName = input("Your New Name Please ").strip().capitalize()
admins[admins.index(name)] = theNewName
print("Name Updated.")
print(admins)
# Delete Option
elif option == 'Delete' or option == 'D':
admins.remove(name)
Skip to main content
print("Name Deleted")
print(admins)
# Wrong Option
else:
print("Wrong Option Choosed")
# If Name is not In Admin
else:
status = input("Not Admin, Add You Y, N ? ").strip().capitalize()
if status == "Yes" or status == "Y":
print("You Have Been Added")
admins.append(name)
print(admins)
else:
print("You Are Not Added.")
Hello Ahmed, Welcome Back.
Name Deleted
['Osama', 'Sameh', 'Manal', 'Rahma', 'Mahmoud', 'Enas']
047 - Loop – While and Else
while condition_is_true
Code Will Run Until Condition Become False```
a = 10
while a < 15:
print(a)
a += 1 # a = a + 1
else:
print("Loop is Done") # True Become False
while False:
print("Will Not Print")
Skip to main content
10
11
12
13
14
Loop is Done
a = 10
while a < 15:
print(a)
a += 1 # a = a + 1
print("Loop is Done") # True Become False
while False:
print("Will Not Print")
10
11
12
13
14
Loop is Done
a = 15
while a < 15:
print(a)
a += 1 # a = a + 1
print("Loop is Done") # True Become False
while False:
print("Will Not Print")
Loop is Done
048 – Loop – While Trainings
Skip to main content
myF = ["Os", "Ah", "Ga", "Al", "Ra", "Sa", "Ta", "Ma", "Mo", "Wa"]
print(myF)
['Os', 'Ah', 'Ga', 'Al', 'Ra', 'Sa', 'Ta', 'Ma', 'Mo', 'Wa']
print(myF[0])
print(myF[1])
print(myF[2])
print(myF[9])
Os
Ah
Ga
Wa
print(len(myF))
10
a = 0
while a < len(myF): # a < 10
print(myF[a])
a += 1 # a = a + 1
else:
print("All Friends Printed To Screen.")
Os
Ah
Ga
Al
Ra
Sa
Ta
Ma
Mo
Wa
All Friends Printed To Screen.
Skip to main content
a = 0
while a < len(myF): # a < 10
# a+1 to make zfill start with 001
print(f"#{str(a + 1).zfill(2)} {myF[a]}")
a += 1 # a = a + 1
else:
print("All Friends Printed To Screen.")
#01 Os
#02 Ah
#03 Ga
#04 Al
#05 Ra
#06 Sa
#07 Ta
#08 Ma
#09 Mo
#10 Wa
All Friends Printed To Screen.
049 – Loop – While Trainings Bookmark
Manager
# Empty List To Fill Later
myFavouriteWebs = []
# Maximum Allowed Websites
maximumWebs = 2
while maximumWebs > 0:
# Input The New Website
web = input("Website Name Without https:// ")
# Add The New Website To The List
myFavouriteWebs.append(f"https://{web.strip().lower()}")
# Decrease One Number From Allowed Websites
maximumWebs -= 1 # maximumWebs = maximumWebs - 1
# Print The Add Message
print(f"Website Added, {maximumWebs} Places Left")
# Print The List
print(myFavouriteWebs) Skip to main content
else:
print("Bookmark Is Full, You Cant Add More")
Website Added, 1 Places Left
['https://elzero.org']
Website Added, 0 Places Left
['https://elzero.org', 'https://']
Bookmark Is Full, You Cant Add More
# Check If List Is Not Empty
if len(myFavouriteWebs) > 0:
# Sort The List
myFavouriteWebs.sort()
index = 0
print("Printing The List Of Websites in Your Bookmark")
while index < len(myFavouriteWebs):
print(myFavouriteWebs[index])
index += 1 # index = index + 1
Printing The List Of Websites in Your Bookmark
https://
https://elzero.org
050 – Loop – While Trainings Password
Guess
tries = 2
mainPassword = "123"
inputPassword = input("Write Your Password: ")
while inputPassword != mainPassword: # True
tries -= 1 # tries = tries - 1
print(f"Wrong Password, { 'Last' if tries == 0 else tries } Chance Left"
inputPassword = input("Write Your Password: ")
Skip to main content
if tries == 0:
print("All Tries Is Finished.")
break # exits the loop
print("Will Not Print") # will not be printed
else:
print("Correct Password")
Wrong Password, 1 Chance Left
Wrong Password, Last Chance Left
All Tries Is Finished.
051 – Loop – For And Else
for item in iterable_object :
Do Something With Item
item Is A Vairable You Create and Call Whenever You Want
item refer to the current position and will run and visit all items to the end
iterable_object => Sequence [ list, tuples, set, dict, string of charcaters, etc … ]
myNumbers = [1, 2, 3, 4, 5]
print(myNumbers)
[1, 2, 3, 4, 5]
for number in myNumbers:
print(number)
1
2
3
4
5
# check if the number is even.
for number in myNumbers:
Skip to main content
if number % 2 == 0: # Even
print(f"The Number {number} Is Even.")
else:
print(f"The Number {number} Is Odd.")
else:
print("The Loop Is Finished")
The Number 1 Is Odd.
The Number 2 Is Even.
The Number 3 Is Odd.
The Number 4 Is Even.
The Number 5 Is Odd.
The Loop Is Finished
myName = "Osama"
for letter in myName:
print(letter)
O
s
a
m
a
myName = "Osama"
for letter in myName:
print(f" [ {letter.upper()} ] ")
[ O ]
[ S ]
[ A ]
[ M ]
[ A ]
052 – Loop – For Trainings
myRange = range(0, 6)
Skip to main content
for number in myRange:
print(number)
0
1
2
3
4
5
for number in range(6):
print(number)
0
1
2
3
4
5
mySkills = {
"Html": "90%",
"Css": "60%",
"PHP": "70%",
"JS": "80%",
"Python": "90%",
"MySQL": "60%"
}
print(mySkills['JS'])
print(mySkills.get("Python"))
80%
90%
# looping on dictionary
# will print the keys
for skill in mySkills:
print(skill)
Html
Css
PHP
JS
Skip to main content
Python
MySQL
for skill in mySkills:
print(f"My Progress in Lang {skill} Is: {mySkills[skill]}")
My Progress in Lang Html Is: 90%
My Progress in Lang Css Is: 60%
My Progress in Lang PHP Is: 70%
My Progress in Lang JS Is: 80%
My Progress in Lang Python Is: 90%
My Progress in Lang MySQL Is: 60%
053 – Loop – For Nested Loop
people = ["Osama", "Ahmed", "Sayed", "Ali"]
skills = ['Html', 'Css', 'Js']
for name in people: # Outer Loop
print(f"{name} Skills are: ")
for skill in skills: # Inner Loop
print(f"- {skill}")
Osama Skills are:
- Html
- Css
- Js
Ahmed Skills are:
- Html
- Css
- Js
Sayed Skills are:
- Html
- Css
- Js
Ali Skills are:
- Html
- Css
- Js
people = {
"Osama": {
"Html": "70%",
"Css": "80%",
"Js": "70%" Skip to main content
},
"Ahmed": {
"Html": "90%",
"Css": "80%",
"Js": "90%"
},
"Sayed": {
"Html": "70%",
"Css": "60%",
"Js": "90%"
}
}
print(people["Ahmed"])
print(people["Ahmed"]['Css'])
{'Html': '90%', 'Css': '80%', 'Js': '90%'}
80%
for name in people:
print(f"Skills and Progress For {name} are: ")
for skill in people[name]:
print(f"{skill.upper()} => {people[name][skill]}")
Skills and Progress For Osama are:
HTML => 70%
CSS => 80%
JS => 70%
Skills and Progress For Ahmed are:
HTML => 90%
CSS => 80%
JS => 90%
Skills and Progress For Sayed are:
HTML => 70%
CSS => 60%
JS => 90%
054 – Break, Continue, Pass
myNumbers = [1, 2, 3, 4, 5]
for number in myNumbers:
if number == 2:
continue # skips this number
print(number)
Skip to main content
1
3
4
5
for number in myNumbers:
if number == 2:
break # will stop the loop
print(number)
for number in myNumbers:
if number == 2:
pass # will add a feature later, go on for now
print(number)
1
2
3
4
5
055 – Loop Advanced Dictionary
mySkills = {
"HTML": "80%",
"CSS": "90%",
"JS": "70%",
"PHP": "80%"
}
print(mySkills.items())
dict_items([('HTML', '80%'), ('CSS', '90%'), ('JS', '70%'), ('PHP', '80%')])
for skill in mySkills:
print(f"{skill} => {mySkills[skill]}")
Skip to main content
HTML => 80%
CSS => 90%
JS => 70%
PHP => 80%
for skill_key, skill_progress in mySkills.items():
print(f"{skill_key} => {skill_progress}")
HTML => 80%
CSS => 90%
JS => 70%
PHP => 80%
myUltimateSkills = {
"HTML": {
"Main": "80%",
"Pugjs": "80%"
},
"CSS": {
"Main": "90%",
"Sass": "70%"
}
}
for main_key, main_value in myUltimateSkills.items():
print(f"{main_key} Progress Is: ")
for child_key, child_value in main_value.items():
print(f"- {child_key} => {child_value}")
HTML Progress Is:
- Main => 80%
- Pugjs => 80%
CSS Progress Is:
- Main => 90%
- Sass => 70%
056 – Function and Return
[1] A Function is A Reusable Block Of Code Do A Task
[2] A Function Run When You Call It
Skip to main content
[3] A Function Accept Element To Deal With Called [Parameters]
[4] A Function Can Do The Task Without Returning Data
[5] A Function Can Return Data After Job is Finished
[6] A Function Create To Prevent DRY
[7] A Function Accept Elements When You Call It Called [Arguments]
[8] There’s A Built-In Functions and User Defined Functions
[9] A Function Is For All Team and All Apps
def function_name():
return "Hello Python From Inside Function"
dataFromFunction = function_name()
print(dataFromFunction)
Hello Python From Inside Function
def function_name():
print("Hello Python From Inside Function")
function_name()
Hello Python From Inside Function
057 – Function Parameters And Arguments
a, b, c = "Osama", "Ahmed", "Sayed"
print(f"Hello {a}")
print(f"Hello {b}")
print(f"Hello {c}")
Hello Osama
Hello Ahmed
Hello Sayed
Skip to main content
# def => Function Keyword [Define]
# say_hello() => Function Name
# name => Parameter
# print(f"Hello {name}") => Task
# say_hello("Ahmed") => Ahmed is The Argument
def say_hello(name):
print(f"Hello {name}")
say_hello("ahmed")
Hello ahmed
def say_hello(n):
print(f"Hello {n}")
say_hello("ahmed")
Hello ahmed
a, b, c = "Osama", "Ahmed", "Sayed"
say_hello(a)
say_hello(b)
say_hello(c)
Hello Osama
Hello Ahmed
Hello Sayed
def addition(n1, n2):
print(n1 + n2)
addition(20, 50) # must be two arguements
70
def addition(n1, n2):
if type(n1) != int or type(n2) != int:
Skip to main content
print("Only integers allowed")
else:
print(n1 + n2)
addition(20, "ahmed")
Only integers allowed
def full_name(first, middle, last):
print(
f"Hello {first.strip().capitalize()} {middle.upper():.1s} {last.capi
full_name(" osama ", 'mohamed', "elsayed")
Hello Osama M Elsayed
058 – Function Packing, Unpacking
Arguments
print(1, 2, 3, 4)
1 2 3 4
myList = [1, 2, 3, 4]
print(myList) # list
print(*myList) # unpack the list
[1, 2, 3, 4]
1 2 3 4
def say_hello(n1, n2, n3, n4):
peoples = [n1, n2, n3, n4]
for name in peoples:
print(f"Hello {name}")
Skip to main content
say_hello("Osama", "Ahmed", "Sayed", "Mahmoud") # must be 4 names
Hello Osama
Hello Ahmed
Hello Sayed
Hello Mahmoud
def say_hello(*peoples):
for name in peoples:
print(f"Hello {name}")
say_hello("ahmed", "darwish") # any number of people
Hello ahmed
Hello darwish
def show_details(skill1, skill2, skill3):
print(f"hello osama, your skills are: ")
print(f"{skill1}")
print(f"{skill2}")
print(f"{skill3}")
show_details("html", "css", "js") # must be three
hello osama, your skills are:
html
css
js
def show_details(*skills):
print(f"hello osama, your skills are: ")
for skill in skills:
print(skill)
show_details("html", "css", "js", "python")
hello osama, your skills are:
html
css Skip to main content
js
python
def show_details(name, *skills):
print(f"hello {name}, your skills are: ")
for skill in skills:
print(skill, end=" ")
show_details("ahmed", "html", "css", "js", "python")
show_details("osama", "js")
hello ahmed, your skills are:
html css js python hello osama, your skills are:
js
059 - Function Default Parameters
def say_hello(name, age, country):
print(f"Hello {name} Your Age is {age} and Your Country Is {country}")
say_hello("Osama", 36, "Egypt")
say_hello("Mahmoud", 28, "KSA") # must enter 3 arguements
Hello Osama Your Age is 36 and Your Country Is Egypt
Hello Mahmoud Your Age is 28 and Your Country Is KSA
def say_hello(name="Unknown", age="Unknown", country="Unknown"):
print(f"Hello {name} Your Age is {age} and Your Country Is {country}")
say_hello("Osama", 36, "Egypt")
say_hello("Mahmoud", 28, "KSA")
say_hello("Sameh", 38)
say_hello("Ramy")
say_hello() # prints unknown if not provided
# if you provide only one default,it must be the last parameter
# def say_hello(name="Unknown", age, country): error
Skip to main content
Hello Osama Your Age is 36 and Your Country Is Egypt
Hello Mahmoud Your Age is 28 and Your Country Is KSA
Hello Sameh Your Age is 38 and Your Country Is Unknown
Hello Ramy Your Age is Unknown and Your Country Is Unknown
Hello Unknown Your Age is Unknown and Your Country Is Unknown
060 – Function Packing, Unpacking Keyword
Arguments
def show_skills(*skills):
for skill in skills:
print(f"{skill}")
show_skills("Html", "CSS", "JS")
Html
CSS
JS
def show_skills(*skills):
print(type(skills)) # tuple
for skill in skills:
print(f"{skill}")
show_skills("Html", "CSS", "JS")
<class 'tuple'>
Html
CSS
JS
def show_skills(**skills):
print(type(skills)) # dict
for skill, value in skills.items():
print(f"{skill} => {value}")
mySkills = { Skip to main content
'Html': "80%",
'Css': "70%",
'Js': "50%",
'Python': "80%",
"Go": "40%"
}
show_skills(**mySkills)
print("---------------")
show_skills(Html="80%", CSS="70%", JS="50%")
<class 'dict'>
Html => 80%
Css => 70%
Js => 50%
Python => 80%
Go => 40%
---------------
<class 'dict'>
Html => 80%
CSS => 70%
JS => 50%
061 – Function Packing, Unpacking
Arguments Trainings
def show_skills(name, *skills):
print(f"Hello {name}\nskills without progress are: ")
for skill in skills:
print(f"- {skill}")
show_skills("osama", "html", "css", "js")
Hello osama
skills without progress are:
- html
- css
- js
def show_skills(name, *skills, **skillsWithProgres):
print(f"Hello {name} \nSkills Without Progress are: ")
Skip to main content
for skill in skills:
print(f"- {skill}")
print("Skills With Progress are: ")
for skill_key, skill_value in skillsWithProgres.items():
print(f"- {skill_key} => {skill_value}")
show_skills("osama")
print("-----------")
show_skills("Osama", "html", "css", "js", python="50%")
Hello osama
Skills Without Progress are:
Skills With Progress are:
-----------
Hello Osama
Skills Without Progress are:
- html
- css
- js
Skills With Progress are:
- python => 50%
myTuple = ("Html", "CSS", "JS")
mySkills = {
'Go': "80%",
'Python': "50%",
'MySQL': "80%"
}
show_skills("Osama", *myTuple, **mySkills)
Hello Osama
Skills Without Progress are:
- Html
- CSS
- JS
Skills With Progress are:
- Go => 80%
- Python => 50%
- MySQL => 80%
062 – Function Scope
x = 1
Skip to main content
print(f"varible in global scope: {x}")
varible in global scope: 1
x = 1
def one():
x = 2
print(f"variable in function scope: {x}")
print(f"varible in global scope: {x}")
one()
varible in global scope: 1
variable in function scope: 2
x = 1
def one():
x = 2
print(f"variable in function one scope: {x}")
def two():
x = 4
print(f"variable in function two scope: {x}")
print(f"varible in global scope: {x}")
one()
two()
varible in global scope: 1
variable in function one scope: 2
variable in function two scope: 4
x = 1
def one():
x = 2
print(f"variable in function one scope: {x}")
def two(): Skip to main content
print(f"variable in function two scope: {x}") # from global
print(f"varible in global scope: {x}")
one()
two()
varible in global scope: 1
variable in function one scope: 2
variable in function two scope: 1
x = 1
def one():
global x
x = 2
print(f"variable in function one scope: {x}")
def two():
x = 4
print(f"variable in function two scope: {x}")
print(f"varible in global scope: {x}")
one()
two()
print(f"varible in global scope after function one: {x}")
varible in global scope: 1
variable in function one scope: 2
variable in function two scope: 4
varible in global scope after function one: 2
def one():
global t
t = 10
print(f"variable in function one scope: {t}")
def two():
print(f"variable in function two scope: {t}")
# print(f"varible in global scope: {x}") error
one()
Skip to main content
two()
print(f"varible in global scope after function one: {t}")
variable in function one scope: 10
variable in function two scope: 10
varible in global scope after function one: 10
063 – Function Recursion
x = "wooorrldd"
print(x[1:])
ooorrldd
def cleanWord(word):
if len(word) == 1:
return word
if word[0] == word[1]:
return cleanWord(word[1:])
return word
print(cleanWord("wwwoorrlldd"))
woorrlldd
def cleanWord(word):
if len(word) == 1:
return word
if word[0] == word[1]:
return cleanWord(word[1:])
return word[0] + cleanWord(word[1:])
# Stash [ World ]
print(cleanWord("wwwoorrlldd"))
world
Skip to main content
def cleanWord(word):
if len(word) == 1:
return word
print(f"print start function {word}")
if word[0] == word[1]:
print(f"print before condition {word}")
return cleanWord(word[1:])
print(f"before return {word}")
print("-----------------------")
return word[0] + cleanWord(word[1:])
# Stash [ World ]
print(cleanWord("wwwoorrlldd"))
print start function wwwoorrlldd
print before condition wwwoorrlldd
print start function wwoorrlldd
print before condition wwoorrlldd
print start function woorrlldd
before return woorrlldd
-----------------------
print start function oorrlldd
print before condition oorrlldd
print start function orrlldd
before return orrlldd
-----------------------
print start function rrlldd
print before condition rrlldd
print start function rlldd
before return rlldd
-----------------------
print start function lldd
print before condition lldd
print start function ldd
before return ldd
-----------------------
print start function dd
print before condition dd
world
064 – Function Lambda
[1] It Has No Name
[2] You Can Call It Inline Without Defining It
[3] You Can Use It In Return Data From Another Function
Skip to main content
[4] Lambda Used For Simple Functions and Def Handle The Large Tasks
[5] Lambda is One Single Expression not Block Of Code
[6] Lambda Type is Function
def say_hello(name, age): return f"Hello {name} your Age Is: {age}"
print(say_hello("Ahmed", 36))
def hello(name, age): return f"Hello {name} your Age Is: {age}"
print(hello("Ahmed", 36))
Hello Ahmed your Age Is: 36
Hello Ahmed your Age Is: 36
print(say_hello.__name__)
print(hello.__name__)
say_hello
hello
print(type(say_hello))
print(type(hello))
<class 'function'>
<class 'function'>
065 - Files Handling – Part 1 Intro
“a” Append Open File For Appending Values, Create File If Not Exists
“r” Read [Default Value] Open File For Read and Give Error If File is Not Exists
“w” Write Open File For Writing, Create File If Not Exists
“x” Create Create File, Give Error If File Exists
file = open(“D:\Python\Files\osama.txt”)
Skip to main content
import os # operating system
print(os.getcwd()) # main current working directory
f:\github\python\Mastering-Python
print(os.path.abspath(file)) # absolute path of file
directory for the opened files
print(os.path.dirname(os.path.abspath(file)))
change current working directory
os.chdir(os.path.dirname(os.path.abspath(file))) print(os.getcwd())
r will make sure \n is not treated as new line
file = open(r”D:\Python\Files\nfiles\osama.txt”)
066 – Files Handling Part 2 – Read Files
myfile = open(r"D:\Python\Files\osama.txt", "r")
print(myfile) # file data object
print(myfile.name)
print(myfile.mode)
print(myfile.encoding)
print(myfile.read())
print(myfile.read(5))
print(myfile.readline(5))
print(myfile.readline())
print(myfile.readlines(50))
print(myfile.readlines())
print(type(myfile.readlines()))
for line in myfile:
print(line)
Skip to main content
if line.startswith("07"):
break
myfile.close()
067 – Files Handling Part 3 – Write And
Append In Files
myfile = open(r"D:\Python\Files\osama.txt", "w")
myfile.write("hello\n")
myfile.write("third line")
myfile.write("elzero web school\n" * 1000)
mylist = ["osama\n", "ahmed\n", "sayed\n"]
myfiles.writelines(mylist)
myfile = open(r"D:\Python\Files\osama.txt", "a")
myfile.write("osama")
068 – Files Handling Part 4 – Important
Informations
import os
myFile = open("D:\Python\Files\osama.txt", "a")
myFile.truncate(5)
myFile = open("D:\Python\Files\osama.txt", "a")
print(myFile.tell())
myFile = open("D:\Python\Files\osama.txt", "r")
myFile.seek(11)
print(myFile.read())
os.remove("D:\Python\Files\osama.txt")
069 – Built In Functions Part 1
x = [1, 2, 3, 4, []]
Skip to main content
if all(x):
print("All Elements Is True")
else:
print("at least one is false")
at least one is false
x = [1, 2, 3, 4, []]
if any(x):
print("at least one is true")
else:
print("Theres No Any True Elements")
at least one is true
x = [False, 0, {}, (), []]
if any(x):
print("at least one is true")
else:
print("Theres No Any True Elements")
Theres No Any True Elements
print(bin(100))
0b1100100
a = 1
b = 2
print(id(a))
print(id(b))
140715333358376
140715333358408
070 - Built In Functions Part 2
Skip to main content
# sum(iterable, start)
a = [1, 10, 19, 40]
print(sum(a))
print(sum(a, 5))
70
75
# round(number, numofdigits)
print(round(150.499))
print(round(150.555, 2))
print(round(150.554, 2))
150
150.56
150.55
# range(start, end, step)
print(list(range(0)))
print(list(range(10)))
print(list(range(0, 10, 2)))
[]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 2, 4, 6, 8]
# print()
print("Hello Osama")
print("Hello", "Osama")
Hello Osama
Hello Osama
print("Hello @ Osama @ How @ Are @ You")
print("Hello", "Osama", "How", "Are", "You", sep=" @ ")
Skip to main content
Hello @ Osama @ How @ Are @ You
Hello @ Osama @ How @ Are @ You
print("First Line", end="\n")
print("Second Line", end=" ")
print("Third Line")
First Line
Second Line Third Line
071 - Built In Functions Part 3
# abs()
print(abs(100))
print(abs(-100))
print(abs(10.19))
print(abs(-10.19))
100
100
10.19
10.19
# pow(base, exp, mod)
print(pow(2, 5))
print(pow(2, 5, 10))
32
2
# min(item, item , item, or iterator)
myNumbers = (1, 20, -50, -100, 100)
print(min(1, 10, -50, 20, 30))
print(min("X", "Z", "Osama"))
print(min(myNumbers))
-50
Osama
Skip to main content
-100
# max(item, item , item, or iterator)
myNumbers = (1, 20, -50, -100, 100)
print(max(1, 10, -50, 20, 30))
print(max("X", "Z", "Osama"))
print(max(myNumbers))
30
Z
100
# slice(start, end, step)
a = ["A", "B", "C", "D", "E", "F"]
print(a[:5])
print(a[slice(5)])
print(a[slice(2, 5)])
['A', 'B', 'C', 'D', 'E']
['A', 'B', 'C', 'D', 'E']
['C', 'D', 'E']
072 – Built In Functions Part 4 – Map
[1] Map Take A Function + Iterator
[2] Map Called Map Because It Map The Function On Every Element
[3] The Function Can Be Pre-Defined Function or Lambda Function
# map with predefined function
def formatText(text):
return f"- {text.strip().capitalize()}-"
myTexts = ["osama", "ahmed"]
myFormatedData = map(formatText, myTexts)
print(myFormatedData)
Skip to main content
<map object at 0x000002B95FCDA3E0>
for name in map(formatText, myTexts):
print(name)
- Osama-
- Ahmed-
for name in list(map(formatText, myTexts)):
print(name)
- Osama-
- Ahmed-
# map with lambda
myTexts = ["osama", "ahmed"]
for name in list(map(lambda text: f"- {text.strip().capitalize()}-", myTexts
print(name)
- Osama-
- Ahmed-
# map with lambda
myTexts = ["osama", "ahmed"]
for name in list(map((lambda text: f"- {text.strip().capitalize()}-"), myTex
print(name)
- Osama-
- Ahmed-
073 - Built In Functions Part 5 – Filter
[1] Filter Take A Function + Iterator
[2] Filter Run A Function On Every Element
[3] The Function Can Be Pre-Defined Function or Lambda Function
[4] Filter Out All Elements For Which The Function Return True
Skip to main content
[5] The Function Need To Return Boolean Value
def checkNumber(num):
if num > 10:
return num
myNumbers = [1, 19, 10, 20, 100, 5]
myResult = filter(checkNumber, myNumbers)
for number in myResult:
print(number)
19
20
100
def checkNumber(num):
if num == 0:
return num # wont work cuz 0 is falsy
myNumbers = [0, 0, 1, 19, 10, 20, 100, 5, 0, 0]
myResult = filter(checkNumber, myNumbers)
for number in myResult:
print(number)
def checkNumber(num):
if num == 0:
return True
myNumbers = [0, 0, 1, 19, 10, 20, 100, 5, 0, 0]
myResult = filter(checkNumber, myNumbers)
for number in myResult:
print(number)
0
0
0
0
def checkNumber(num):
return num > 10
Skip to main content
myNumbers = [1, 19, 10, 20, 100, 5]
myResult = filter(checkNumber, myNumbers)
for number in myResult:
print(number)
19
20
100
def checkName(name):
return name.startswith("O")
myTexts = ["Osama", "Omer", "Omar", "Ahmed", "Sayed", "Othman"]
myReturnedData = filter(checkName, myTexts)
for person in myReturnedData:
print(person)
Osama
Omer
Omar
Othman
myNames = ["Osama", "Omer", "Omar", "Ahmed", "Sayed", "Othman", "Ameer"]
for p in filter(lambda name: name.startswith("A"), myNames):
print(p)
Ahmed
Ameer
074 – Built In Functions Part 6 – Reduce
[1] Reduce Take A Function + Iterator
[2] Reduce Run A Function On FIrst and Second Element And Give Result
[3] Then Run Function On Result And Third Element
[4] Then Run Function On Rsult And Fourth
Skip Element
to main And So On
content
[5] Till One ELement is Left And This is The Result of The Reduce
[6] The Function Can Be Pre-Defined Function or Lambda Function
from functools import reduce
def sumAll(num1, num2):
return num1 + num2
numbers = [5, 10, 15, 20, 30]
result = reduce(sumAll, numbers)
print(result)
print(((((5+10)+15)+20)+30))
80
80
result = reduce(lambda num1, num2: num1 + num2, numbers)
print(result)
80
075 – Built In Functions Part 7
# enumerate(iterable, start=0)
mySkills = ["Html", "Css", "Js", "PHP"]
for skill in mySkills:
print(skill)
Html
Css
Js
PHP
mySkillsWithCounter = enumerate(mySkills, 00)
print(type(mySkillsWithCounter))
Skip to main content
for skill in mySkillsWithCounter:
print(skill)
<class 'enumerate'>
(0, 'Html')
(1, 'Css')
(2, 'Js')
(3, 'PHP')
mySkillsWithCounter = enumerate(mySkills, 00)
for counter, skill in mySkillsWithCounter:
print(f"{counter} - {skill}")
0 - Html
1 - Css
2 - Js
3 - PHP
print(help(print))
Help on built-in function print in module builtins:
print(*args, sep=' ', end='\n', file=None, flush=False)
Prints the values to a stream, or to sys.stdout by default.
sep
string inserted between values, default a space.
end
string appended after the last value, default a newline.
file
a file-like object (stream); defaults to the current sys.stdout.
flush
whether to forcibly flush the stream.
None
# reversed(iterable)
myString = "Elzero"
print(reversed(myString))
Skip to main content
<reversed object at 0x000002B95FCDA560>
for letter in reversed(myString):
print(letter, end="")
orezlE
for s in reversed(mySkills):
print(s)
PHP
Js
Css
Html
076 – Modules Part 1 – Intro And Built In
Modules
[1] Module is A File Contain A Set Of Functions
[2] You Can Import Module in Your App To Help You
[3] You Can Import Multiple Modules
[4] You Can Create Your Own Modules
[5] Modules Saves Your Time
import random
print(random)
<module 'random' from 'f:\\miniconda3\\envs\\py311\\Lib\\random.py'>
print(f"random float number {random.random()}")
random float number 0.8022768368311108
Skip to main content
# show all functions inside module
import random
print(dir(random))
['BPF', 'LOG4', 'NV_MAGICCONST', 'RECIP_BPF', 'Random', 'SG_MAGICCONST', 'Sy
# import functions from module
from random import randint, random
print(f"random integer: {randint(100,900)}")
print(f"float number: {random()}")
random integer: 484
float number: 0.9107908848337325
to import all functions from a module
from random import *
077 - Modules – Part 2 – Create Your Module
first, create your functions in a file (ex: elzero) then:
import sys
print(sys.path)
['f:\\github\\python\\Mastering-Python', 'f:\\miniconda3\\envs\\py311\\pytho
to add other path (games):
sys.path.append(r”D:\Games”)
import elzero
print(dir(elzero))
elzero.sayHello("Ahmed") Skip to main content
elzero.sayHello("Osama")
elzero.sayHowAreYou("Ahmed")
elzero.sayHowAreYou("Osama")
ALias
import elzero as ee
ee.sayHello("Ahmed")
ee.sayHello("Osama")
ee.sayHowAreYou("Ahmed")
ee.sayHowAreYou("Osama")
from elzero import sayHello
sayHello("Osama")
from elzero import sayHello as ss
ss("Osama")
078 - Modules – Part 3 – Install External
Packages
[1] Module vs Package
[2] External Packages Downloaded From The Internet
[3] You Can Install Packages With Python Package Manager PIP
[4] PIP Install the Package and Its Dependencies
[5] Modules List “https://docs.python.org/3/py-modindex.html”
[6] Packages and Modules Directory “https://pypi.org/”
[7] PIP Manual “https://pip.pypa.io/en/stable/reference/pip_install/”
pip - -version
pip list
pip install termcolor pyfiglet
pip install –user pip –upgrade Skip to main content
import termcolor
import pyfiglet
import textwrap
output = '\n'.join(dir(pyfiglet))
print(textwrap.fill(output, width=80))
COLOR_CODES CharNotPrinted DEFAULT_FONT Figlet FigletBuilder FigletError
FigletFont FigletProduct FigletRenderingEngine FigletString FontError
FontNotFound InvalidColor OptionParser RESET_COLORS SHARED_DIRECTORY __autho
__builtins__ __cached__ __copyright__ __doc__ __file__ __loader__ __name__
__package__ __path__ __spec__ __version__ color_to_ansi figlet_format main o
parse_color pkg_resources print_figlet print_function re shutil sys
unicode_literals unicode_string version zipfile
print(pyfiglet.figlet_format("Ahmed"))
_ _ _
/ \ | |__ _ __ ___ ___ __| |
/ _ \ | '_ \| '_ ` _ \ / _ \/ _` |
/ ___ \| | | | | | | | | __/ (_| |
/_/ \_\_| |_|_| |_| |_|\___|\__,_|
print(termcolor.colored("Ahmed", color="yellow"))
Ahmed
print(termcolor.colored(pyfiglet.figlet_format("Ahmed"), color="yellow"))
_ _ _
/ \ | |__ _ __ ___ ___ __| |
/ _ \ | '_ \| '_ ` _ \ / _ \/ _` |
/ ___ \| | | | | | | | | __/ (_| |
/_/ \_\_| |_|_| |_| |_|\___|\__,_|
Skip to main content
079 - Date And Time – Introduction
import textwrap
import datetime
output = '\n'.join(dir(datetime))
print(textwrap.fill(output, width=80))
MAXYEAR MINYEAR UTC __all__ __builtins__ __cached__ __doc__ __file__ __loade
__name__ __package__ __spec__ date datetime datetime_CAPI sys time timedelta
timezone tzinfo
import textwrap
output = '\n'.join(dir(datetime.datetime))
print(textwrap.fill(output, width=80))
__add__ __class__ __delattr__ __dir__ __doc__ __eq__ __format__ __ge__
__getattribute__ __getstate__ __gt__ __hash__ __init__ __init_subclass__ __l
__lt__ __ne__ __new__ __radd__ __reduce__ __reduce_ex__ __repr__ __rsub__
__setattr__ __sizeof__ __str__ __sub__ __subclasshook__ astimezone combine c
date day dst fold fromisocalendar fromisoformat fromordinal fromtimestamp ho
isocalendar isoformat isoweekday max microsecond min minute month now replac
resolution second strftime strptime time timestamp timetuple timetz today
toordinal tzinfo tzname utcfromtimestamp utcnow utcoffset utctimetuple weekd
year
# Print The Current Date and Time
print(datetime.datetime.now())
2023-04-22 11:15:04.780122
print(datetime.datetime.now().year)
print(datetime.datetime.now().month)
print(datetime.datetime.now().day)
2023
4
22
# print start and end of date
Skip to main content
print(datetime.datetime.min)
print(datetime.datetime.max)
0001-01-01 00:00:00
9999-12-31 23:59:59.999999
# Print The Current Time
print(datetime.datetime.now().time())
print(datetime.datetime.now().time().hour)
print(datetime.datetime.now().time().minute)
print(datetime.datetime.now().time().second)
11:15:07.549813
11
15
7
# Print Start and End Of Time
print(datetime.time.min)
print(datetime.time.max)
00:00:00
23:59:59.999999
# Print Specific Date
print(datetime.datetime(1982, 10, 25))
print(datetime.datetime(1982, 10, 25, 10, 45, 55, 150364))
1982-10-25 00:00:00
1982-10-25 10:45:55.150364
myBirthDay = datetime.datetime(2001, 10, 17)
dateNow = datetime.datetime.now()
print(f"My Birthday is {myBirthDay} And ", end="")
print(f"Date Now Is {dateNow}")
print(f" I Lived For {dateNow - myBirthDay}")
print(f" I Lived For {(dateNow - myBirthDay).days} Days.")
My Birthday is 2001-10-17 00:00:00 And Date Now Is 2023-04-22 11:15:10.22777
I Lived For 7857 days, 11:15:10.227776
Skip to main content
I Lived For 7857 Days.
080 - Date And Time – Format Date
https://strftime.org/
import datetime
myBirthday = datetime.datetime(1982, 10, 25)
print(myBirthday)
print(myBirthday.strftime("%a"))
print(myBirthday.strftime("%A"))
print(myBirthday.strftime("%b"))
print(myBirthday.strftime("%B"))
1982-10-25 00:00:00
Mon
Monday
Oct
October
print(myBirthday.strftime("%d %B %Y"))
print(myBirthday.strftime("%d, %B, %Y"))
print(myBirthday.strftime("%d/%B/%Y"))
print(myBirthday.strftime("%d - %B - %Y"))
print(myBirthday.strftime("%B - %Y"))
25 October 1982
25, October, 1982
25/October/1982
25 - October - 1982
October - 1982
081 - Iterable vs Iterator
Iterable
[1] Object Contains Data That Can Be Iterated Upon
[2] Examples (String, List, Set, Tuple, Dictionary)
Iterator
[1] Object Used To Iterate Over Iterable Using
Skip to mainnext() Method Return 1 Element At A Time
content
[2] You Can Generate Iterator From Iterable When Using iter() Method
[3] For Loop Already Calls iter() Method on The Iterable Behind The Scene
[4] Gives “StopIteration” If Theres No Next Element
myString = "Osama"
for letter in myString:
print(letter, end=" ")
O s a m a
myList = [1, 2, 3, 4, 5]
for number in myList:
print(number, end=" ")
1 2 3 4 5
myNumber = 100.50
for part in myNumber:
print(part) # error
my_name = "ahmed"
my_iterator = iter(my_name)
print(next(my_iterator))
print(next(my_iterator))
print(next(my_iterator))
print(next(my_iterator))
print(next(my_iterator))
a
h
m
e
d
for letter in "Elzero":
print(letter, end=" ")
E l z e r o Skip to main content
for letter in iter("Elzero"):
print(letter, end=" ")
E l z e r o
082 - Generators
[1] Generator is a Function With “yield” Keyword Instead of “return”
[2] It Support Iteration and Return Generator Iterator By Calling “yield”
[3] Generator Function Can Have one or More “yield”
[4] By Using next() It Resume From Where It Called “yield” Not From Begining
[5] When Called, Its Not Start Automatically, Its Only Give You The Control
def myGenerator():
yield 1
yield 2
yield 3
yield 4
print(myGenerator())
<generator object myGenerator at 0x000002B95FD35850>
myGen = myGenerator()
print(next(myGen), end=" ")
print("Hello From Python")
print(next(myGen), end=" ")
1 Hello From Python
2
for number in myGen:
print(number)
3
4
Skip to main content
083 - Decorators – Intro
[1] Sometimes Called Meta Programming
[2] Everything in Python is Object Even Functions
[3] Decorator Take A Function and Add Some Functionality and Return It
[4] Decorator Wrap Other Function and Enhance Their Behaviour
[5] Decorator is Higher Order Function (Function Accept Function As Parameter)
def myDecorator(func): # Decorator
def nestedfunc(): # Any Name Its Just For Decoration
print("Before") # Message From Decorator
func() # Execute Function
print("After") # Message From Decorator
return nestedfunc # Return All Data
def sayHello():
print("Hello from sayHello function")
afterDecoration = myDecorator(sayHello)
afterDecoration()
Before
Hello from sayHello function
After
def myDecorator(func): # Decorator
def nestedfunc(): # Any Name Its Just For Decoration
print("Before") # Message From Decorator
func() # Execute Function
print("After") # Message From Decorator
return nestedfunc # Return All Data
@myDecorator
def sayHello():
print("Hello from sayHello function")
sayHello()
Skip to main content
Before
Hello from sayHello function
After
def myDecorator(func): # Decorator
def nestedfunc(): # Any Name Its Just For Decoration
print("Before") # Message From Decorator
func() # Execute Function
print("After") # Message From Decorator
return nestedfunc # Return All Data
@myDecorator
def sayHello():
print("Hello from sayHello function")
def sayHowAreYou():
print("Hello From Say How Are You Function")
sayHello()
sayHowAreYou()
Before
Hello from sayHello function
After
Hello From Say How Are You Function
084 - Decorators – Function with Parameters
def myDecorator(func): # Decorator
def nestedFunc(num1, num2): # Any Name Its Just For Decoration
if num1 < 0 or num2 < 0:
print("Beware One Of The Numbers Is Less Than Zero")
func(num1, num2) # Execute Function
return nestedFunc # Return All Data
@myDecorator
def calculate(n1, n2):
print(n1 + n2)
Skip to main content