Start - Mastering Python
Start - Mastering Python
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
I love python
i love programming
print(1)
print(2)
1
2
if True:
print(1)
004 – Comments
# this is a comment
# -----------
# hola
# ------------
hi
'''
not multiline comment
'''
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'>
my value
my_value = "value"
print(my_value)
value
# print(name)
# name ="yay" will generate error
# must assign value first before printing
x = 10
x = "hello"
print(x) # dynamically typed language
hello
a, b, c = 1, 2, 3
print(a, b, c)
1 2 3
print("hello\bword")
hellword
print("hello\
python")
i love \python
print("hello \nworld")
hello
world
print("123456\rabcd")
abcd56
print("hello \tworld")
hello world
print("\x4F\x73")
Os
i love python
i love python
a = "first\
second\
third"
b = "A\
B\
C"
print(a)
print(b)
print(a + "\n"+b)
i love 1
011 – Strings
myStringOne = "this is 'signle quote'"
print(myStringOne)
Skip to main content
this is 'signle quote'
multi = """first
second
third
"""
print(multi)
first
second
third
test = '''
"First" second 'third'
'''
print(test)
i
n
t
yth
i love pyt
e pyt
e
i love python
i love python
i love python
ilv yhn
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#####
001
020
003
g = "aHmed"
print(g.lower())
Skip to main content
print(g.upper())
ahmed
AHMED
a = "I-love-python"
print(a.split("-"))
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#####
2
1
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
7
7
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())
print(f.splitlines())
g = "Hello\tWorld\tI\tLove\tPython"
print(g.expandtabs(5))
Skip to main content
Hello World I Love Python
True
False
True
False
True
False
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
Osama-Mohamed-Elsayed
Osama Mohamed Elsayed
Osama, Mohamed, Elsayed
<class 'str'>
print("My Name is: " + name + " and My Age is: " + age)
n = "Osama"
l = "Python"
y = 10
My Number is: 10
My Number is: 10.000000
My Number is: 10.00
n = "Osama"
l = "Python"
y = 10
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))
# 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))
# 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 10 20 30
Hello 20 30 10
Hello 30.000000 10.000000 20.000000
Hello 30.00 10.0000 20.00000
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))
# 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
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)
# 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
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
print(myAwesomeList)
print(myAwesomeList[1])
print(myAwesomeList[-1])
print(myAwesomeList[-3])
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])
print(myAwesomeList)
myAwesomeList[1] = 2
myAwesomeList[-1] = False
print(myAwesomeList)
myFriends.append("Alaa")
myFriends.append(100)
myFriends.append(150.200)
myFriends.append(True)
print(myFriends)
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)
y.sort(reverse=True)
print(y)
Sort can’t sort a list that contains both of strings and numbers.
[]
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))
('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
(1, 2, 3, 4, 5)
myAwesomeTupleFour[2] = "Three"
print(myAwesomeTupleFour)
Osama
True
('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)
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)}")
# 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
mySetTwo = {1, 2, 3, 4, 5, 6}
print(mySetTwo[0:3])
print(mySetThree)
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}
{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, 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)
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}
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', '
print(user['country'])
print(user.get("country"))
Egypt
Egypt
print(user.keys())
print(user.values())
print(languages)
print(languages['One'])
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)
{'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'}
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'])
{'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)
view = {
"name": "Osama",
"skill": "XBox"
}
allItems = view.items()
print(view)
view["age"] = 36
print(view)
print(allItems)
print(dict.fromkeys(a, b))
{'name': 'Ahmed'}
user["age"] = 21
print(me)
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.
True
name = "Ahmed"
print(name.isspace())
False
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
True
False
True
False
True
True
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
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
False
False
False
True
False
True
False
False
True
False
True
True
<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))
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))
print(set(c))
print(set(d))
print(set(e))
print(set(f))
print(dict(d))
print(dict(e))
fName = fName.strip().capitalize()
mName = mName.strip().capitalize()
lName = lName.strip().capitalize()
Osama
theUsername = theEmail[:theEmail.index("@")]
theWebsite = theEmail[theEmail.index("@") + 1:]
months = age * 12
weeks = months * 4
days = age * 365
hours = days * 24
minutes = hours * 60
seconds = minutes * 60
if uCountry == "Egypt":
else:
else:
else:
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")
movieRate = 18
age = 16
else:
Skip to main content
print("Movie S Good 4U And Happy Watching") # Condition If False
############################################################################
######### You Can Write The First Letter Or Full Name of The Time Unit #####
############################################################################
True
True
False
# List
friends = ["Ahmed", "Sayed", "Mahmoud"]
print("Osama" in friends)
print("Sayed" in friends)
print("Mahmoud" not in friends)
False
True
False
if myCountry in countriesOne:
else:
# Login
name = input("Please Type Your Name ").strip().capitalize()
# If Name is In Admin
if name in admins:
# Update Option
if option == 'Update' or option == 'U':
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:
admins.append(name)
print(admins)
else:
print("You Are Not Added.")
a = 10
print(a)
a += 1 # a = a + 1
else:
print("Loop is Done") # True Become False
while False:
a = 10
print(a)
a += 1 # a = a + 1
while False:
10
11
12
13
14
Loop is Done
a = 15
print(a)
a += 1 # a = a + 1
while False:
print("Will Not Print")
Loop is Done
['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
print(myF[a])
a += 1 # a = a + 1
else:
Os
Ah
Ga
Al
Ra
Sa
Ta
Ma
Mo
Wa
All Friends Printed To Screen.
a += 1 # a = a + 1
else:
#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.
index = 0
print(myFavouriteWebs[index])
mainPassword = "123"
else:
print("Correct Password")
myNumbers = [1, 2, 3, 4, 5]
print(myNumbers)
[1, 2, 3, 4, 5]
1
2
3
4
5
else:
else:
myName = "Osama"
O
s
a
m
a
myName = "Osama"
[ O ]
[ S ]
[ A ]
[ M ]
[ A ]
0
1
2
3
4
5
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
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'])
1
2
3
4
5
print(mySkills.items())
myUltimateSkills = {
"HTML": {
"Main": "80%",
"Pugjs": "80%"
},
"CSS": {
"Main": "90%",
"Sass": "70%"
}
}
def function_name():
dataFromFunction = function_name()
print(dataFromFunction)
def function_name():
function_name()
print(f"Hello {a}")
print(f"Hello {b}")
print(f"Hello {c}")
Hello Osama
Hello Ahmed
Hello Sayed
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
Hello Osama
Hello Ahmed
Hello Sayed
70
addition(20, "ahmed")
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
Hello Osama
Hello Ahmed
Hello Sayed
Hello Mahmoud
def say_hello(*peoples):
Hello ahmed
Hello darwish
print(f"{skill1}")
print(f"{skill2}")
print(f"{skill3}")
def show_details(*skills):
print(f"hello osama, your skills are: ")
Html
CSS
JS
def show_skills(*skills):
print(type(skills)) # tuple
<class 'tuple'>
Html
CSS
JS
def show_skills(**skills):
print(type(skills)) # dict
show_skills(**mySkills)
print("---------------")
<class 'dict'>
Html => 80%
Css => 70%
Js => 50%
Python => 80%
Go => 40%
---------------
<class 'dict'>
Html => 80%
CSS => 70%
JS => 50%
Hello osama
skills without progress are:
- html
- css
- js
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%
mySkills = {
'Go': "80%",
'Python': "50%",
'MySQL': "80%"
}
Hello Osama
Skills Without Progress are:
- Html
- CSS
- JS
Skills With Progress are:
- Go => 80%
- Python => 50%
- MySQL => 80%
x = 1
def one():
x = 2
print(f"variable in function scope: {x}")
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}")
x = 1
def one():
x = 2
print(f"variable in function one scope: {x}")
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}")
def one():
global t
t = 10
print(f"variable in function one scope: {t}")
def two():
print(f"variable in function two scope: {t}")
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:])
print(cleanWord("wwwoorrlldd"))
world
Skip to main content
def cleanWord(word):
if len(word) == 1:
return word
if word[0] == word[1]:
return cleanWord(word[1:])
print(cleanWord("wwwoorrlldd"))
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))
print(say_hello.__name__)
print(hello.__name__)
say_hello
hello
print(type(say_hello))
print(type(hello))
<class 'function'>
<class 'function'>
file = open(“D:\Python\Files\osama.txt”)
f:\github\python\Mastering-Python
print(os.path.dirname(os.path.abspath(file)))
os.chdir(os.path.dirname(os.path.abspath(file))) print(os.getcwd())
file = open(r”D:\Python\Files\nfiles\osama.txt”)
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()))
print(line)
Skip to main content
if line.startswith("07"):
break
myfile.close()
myfile.write("hello\n")
myfile.write("third line")
os.remove("D:\Python\Files\osama.txt")
x = [1, 2, 3, 4, []]
if any(x):
print("at least one is true")
else:
print("Theres No Any True Elements")
if any(x):
print("at least one is true")
else:
print("Theres No Any True Elements")
print(bin(100))
0b1100100
a = 1
b = 2
print(id(a))
print(id(b))
140715333358376
140715333358408
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
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
First Line
Second Line Third Line
100
100
10.19
10.19
32
2
-50
Osama
Skip to main content
-100
30
Z
100
print(a[:5])
print(a[slice(5)])
print(a[slice(2, 5)])
def formatText(text):
return f"- {text.strip().capitalize()}-"
print(myFormatedData)
- Osama-
- Ahmed-
- Osama-
- Ahmed-
- Osama-
- Ahmed-
- Osama-
- Ahmed-
19
20
100
def checkNumber(num):
if num == 0:
return num # wont work cuz 0 is falsy
def checkNumber(num):
if num == 0:
return True
0
0
0
0
def checkNumber(num):
return num > 10
19
20
100
def checkName(name):
return name.startswith("O")
print(person)
Osama
Omer
Omar
Othman
print(p)
Ahmed
Ameer
80
80
print(result)
80
Html
Css
Js
PHP
<class 'enumerate'>
(0, 'Html')
(1, 'Css')
(2, 'Js')
(3, 'PHP')
print(f"{counter} - {skill}")
0 - Html
1 - Css
2 - Js
3 - PHP
print(help(print))
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))
print(letter, end="")
orezlE
for s in reversed(mySkills):
print(s)
PHP
Js
Css
Html
import random
print(random)
import sys
print(sys.path)
['f:\\github\\python\\Mastering-Python', 'f:\\miniconda3\\envs\\py311\\pytho
sys.path.append(r”D:\Games”)
import elzero
print(dir(elzero))
ALias
import elzero as ee
ee.sayHello("Ahmed")
ee.sayHello("Osama")
ee.sayHowAreYou("Ahmed")
ee.sayHowAreYou("Osama")
ss("Osama")
pip - -version
pip list
import textwrap
output = '\n'.join(dir(pyfiglet))
print(textwrap.fill(output, width=80))
print(pyfiglet.figlet_format("Ahmed"))
_ _ _
/ \ | |__ _ __ ___ ___ __| |
/ _ \ | '_ \| '_ ` _ \ / _ \/ _` |
/ ___ \| | | | | | | | | __/ (_| |
/_/ \_\_| |_|_| |_| |_|\___|\__,_|
print(termcolor.colored("Ahmed", color="yellow"))
Ahmed
print(termcolor.colored(pyfiglet.figlet_format("Ahmed"), color="yellow"))
_ _ _
/ \ | |__ _ __ ___ ___ __| |
/ _ \ | '_ \| '_ ` _ \ / _ \/ _` |
/ ___ \| | | | | | | | | __/ (_| |
/_/ \_\_| |_|_| |_| |_|\___|\__,_|
output = '\n'.join(dir(datetime))
print(textwrap.fill(output, width=80))
import textwrap
output = '\n'.join(dir(datetime.datetime))
print(textwrap.fill(output, width=80))
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
0001-01-01 00:00:00
9999-12-31 23:59:59.999999
11:15:07.549813
11
15
7
00:00:00
23:59:59.999999
1982-10-25 00:00:00
1982-10-25 10:45:55.150364
import datetime
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
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"
O s a m a
myList = [1, 2, 3, 4, 5]
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
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())
myGen = myGenerator()
3
4
def sayHello():
print("Hello from sayHello function")
afterDecoration = myDecorator(sayHello)
afterDecoration()
Before
Hello from sayHello function
After
@myDecorator
def sayHello():
print("Hello from sayHello function")
sayHello()
@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
@myDecorator
def calculate(n1, n2):
print(n1 + n2)