100% found this document useful (1 vote)
731 views

Py Python Elzero Web School Part - 2

City level: It serves the main commercial centers and there is wholesale and half wholesale and retail trade.

Uploaded by

tik took
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
731 views

Py Python Elzero Web School Part - 2

City level: It serves the main commercial centers and there is wholesale and half wholesale and retail trade.

Uploaded by

tik took
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 70

# --------------------------

# -- Assignment Operators --

# --------------------------

#=

# +=

# -=

# *=

# /=

# **=

# %=

# //=

# --------------------------

x = 10 # Var One

y = 20 # Var Two

# Var One = Self [Operator] Var Two

# Var One [Operator]= Var Two

# x += y

x -= y

print(x)

# --------------------------

# -- Comparison Operators --

# --------------------------

# [ == ] Equal

# [ != ] Not Equal

# [ > ] Greater Than

# [ < ] Less Than

# [ >= ] Greater Than Or Equal

# [ <= ] Less Than Or Equal


# --------------------------

# Equal + Not Equal

print(100 == 100)

print(100 == 200)

print(100 == 100.00)

print("#" * 50)

print(100 != 100)

print(100 != 200)

print(100 != 100.00)

print("#" * 50)

# Greater Than + Less Than

print(100 > 100)

print(100 > 200)

print(100 > 100.00)

print(100 > 40)

print("#" * 50)

print(100 < 100)

print(100 < 200)

print(100 < 100.00)

print(100 < 40)

print("#" * 50)
# Greater Than Or Equal + Less Than Or Equal

print(100 >= 100)

print(100 >= 200)

print(100 >= 100.00)

print(100 >= 40)

print("#" * 50)

print(100 <= 100)

print(100 <= 200)

print(100 <= 100.00)

print(100 <= 40)

print("#" * 50)

# ---------------------

# -- Type Conversion --

# ----------------------

# str()

a = 10

print(type(a))

print(type(str(a)))

print("#" * 50)

# tuple()

c = "Osama" # String

d = [1, 2, 3, 4, 5] # List
e = {"A", "B", "C"} # Set

f = {"A": 1, "B": 2} # Dictionary

print(tuple(c))

print(tuple(d))

print(tuple(e))

print(tuple(f))

# list()

c = "Osama" # String

d = (1, 2, 3, 4, 5) # Tuple

e = {"A", "B", "C"} # Set

f = {"A": 1, "B": 2} # Dictionary

print(list(c))

print(list(d))

print(list(e))

print(list(f))

print("#" * 50)

# set()

c = "Osama" # String

d = (1, 2, 3, 4, 5) # Tuple

e = ["A", "B", "C"] # List

f = {"A": 1, "B": 2} # Dictionary

print(set(c))

print(set(d))

print(set(e))
print(set(f))

print("#" * 50)

# dict()

d = (("A", 1), ("B", 2), ("C", 3)) # Tuple

e = [["One", 1], ["Two", 2], ["Three", 3]] # List

print(dict(d))

print(dict(e))

# ----------------

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

# -- Practical Slice Email --

# ---------------------------

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

# email = "[email protected]"

# print(email[:email.index("@")])

# -------------------------------------

# -- Practical Your Age Full Details --

# -------------------------------------

# Input Age

age = int(input('What\'s Your Age ? ').strip())

# Get Age in All Time Units

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

# -- Control Flow --

# -- If, Elif, Else --

# -- Make Decisions --

# --------------------

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


# ---------------

# -- Nested If --

# ---------------

uName = "Osama"

isStudent = "Yes"

uCountry = "Egypt"

cName = "Python Course"

cPrice = 100

if uCountry == "Egypt" or uCountry == "KSA" or uCountry == "Qatar":

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


# ----------------------------------

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

# Short If

movieRate = 18

age = 18

if age < movieRate :

print("Movie S Not Good 4U") # Condition If True

else :

print("Movie S Good 4U And Happy Watching") # Condition If False

print("Movie S Not Good 4U" if age < movieRate else "Movie S Good 4U And Happy Watching")

# Condition If True | If Condition | Else | Condition If False


# -------------------------------------------------

# -- Calculate Age Advanced Version and Training --

# -------------------------------------------------

# Write A Very Beautiful Note

print("#" * 80)

print(" You Can Write The First Letter Or Full Name of The Time Unit ".center(80, '#'))

print("#" * 80)

# 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 Unit Months")

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

# --------------------------

# -- Membership Operators --

# --------------------------

# in

# not in

# --------------------------

# String

name = "Osama"

print("s" in name)

print("a" in name)

print("A" in name)

print("#" * 50)

# List

friends = ["Ahmed", "Sayed", "Mahmoud"]

print("Osama" in friends)

print("Sayed" in friends)

print("Mahmoud" not in friends)

print("#" * 50)

# Using In and Not In With Condition

countriesOne = ["Egypt", "KSA", "Kuwait", "Bahrain", "Syria"]


countriesOneDiscount = 80

countriesTwo = ["Italy", "USA"]

countriesTwoDiscount = 50

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

# ----------------------------------

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

print("Name Deleted")

print(admins)

# Wrong Option

else:

print("Wrong Option Choosed")

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

# -------------------

# -- Loop => While --

# -------------------

# while condition_is_true

# Code Will Run Until Condition Become False

# -----------------------

a=0

while a < 15:

print(a)

a += 1 # a = a + 1

print("Loop is Done") # True Become False

while False:

print("Will Not Print")


# ----------------------------

# -- Loop => While Training --

# ----------------------------

# while condition_is_true

# Code Will Run Until Condition Become False

# -----------------------

myF = ["Os", "Ah", "Ga", "Al", "Ra", "Sa", "Ta", "Ma", "Mo", "Wa"]

# print(len(myF)) # List Length [10]

a=0

while a < len(myF): # a < 10

print(f"#{str(a + 1).zfill(3)} {myF[a]}")

a += 1 # a = a + 1

else:

print("All Friends Printed To Screen.")

# print(myF[0])

# print(myF[1])

# print(myF[2])

# print(myF[3])

# print(myF[4])

# print(myF[5])

# print(myF[6])

# print(myF[7])

# print(myF[8])

# print(myF[9])
# ----------------------------

# -- Loop => While Training --

# -- Simple Bookmark Manage --

# ----------------------------

# Empty List To Fill Later

myFavouriteWebs = []

# Maximum Allowed Websites

maximumWebs = 5

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)

else:

print("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

# ----------------------------

# -- Loop => While Training --

# -- Simple Password Guess --

# ----------------------------

tries = 4

mainPassword = "Osama@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: ")

if tries == 0:

print("All Tries Is Finished.")

break

print("Will Not Print")

else:

print("Correct Password")

# -----------------

# -- Loop => For --

# -----------------

# 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, 6, 7, 8, 9]

for number in myNumbers:

# print(number * 17)

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

myName = "Osama"

for letter in myName:

print(f" [ {letter.upper()} ] ")

# -----------------

# -- Loop => For --

# -- Trainings --

# -----------------

# Range

myRange = range(1, 101)

for number in myRange:

print(number)

# Dictionary

mySkills = {
"Html": "90%",

"Css": "60%",

"PHP": "70%",

"JS": "80%",

"Python": "90%",

"MySQL": "60%"

print(mySkills['JS'])

print(mySkills.get("Python"))

for skill in mySkills:

# print(skill)

print(f"My Progress in Lang {skill} Is: {mySkills.get(skill)}")

# -----------------

# -- Loop => For --

# -- Nested Loop --

# -----------------

peoples = ["Osama", "Ahmed", "Sayed", "Ali"]

skills = ['Html', 'Css', 'Js']

for name in peoples: # Outer Loop

print(f"{name} Skills Is: ")

for skill in skills: # Inner Loop

print(f"- {skill}")
# Dictionary

peoples = {

"Osama": {

"Html": "70%",

"Css": "80%",

"Js": "70%"

},

"Ahmed": {

"Html": "90%",

"Css": "80%",

"Js": "90%"

},

"Sayed": {

"Html": "70%",

"Css": "60%",

"Js": "90%"

print(peoples["Osama"])

print(peoples["Ahmed"])

print(peoples["Sayed"])

print(peoples["Osama"]['Css'])

print(peoples["Ahmed"]['Css'])

print(peoples["Sayed"]['Css'])

for name in peoples:

print(f"Skills and Progress For {name} Is: ")


for skill in peoples[name]:

print(f"{skill.upper()} => {peoples[name][skill]}")

# ---------------------------

# -- Break, Continue, Pass --

# ---------------------------

myNumbers = [1, 2, 3, 5, 7, 10, 13, 14, 15, 19]

# Continue

for number in myNumbers:

if number == 13:

continue

print(number)

print("#" * 50)

# Break

for number in myNumbers:

if number == 13:

break

print(number)
print("#" * 50)

# Pass

for number in myNumbers:

if number == 13:

pass

print(number)

# ------------------------------

# -- Advanced Dictionary Loop --

# ------------------------------

mySkills = {

"HTML": "80%",

"CSS": "90%",

"JS": "70%",

"PHP": "80%"

print(mySkills.items())

#######################

for skill in mySkills:

print(f"{skill} => {mySkills[skill]}")

#######################
for skill_key, skill_progress in mySkills.items():

print(f"{skill_key} => {skill_progress}")

#######################

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


# -------------------------

# -- Function And Return --

# -------------------------

# [1] A Function is A Reusable Block Of Code Do A Task

# [2] A Function Run When You Call It

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

# ---------------------------------------

# -- Function Parameters And Arguments --

# ---------------------------------------

a, b, c = "Osama", "Ahmed", "Sayed"

print(f"Hello {a}")

print(f"Hello {b}")

print(f"Hello {c}")
# 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(n):

print(f"Hello {n}")

say_hello(a)

say_hello(b)

say_hello(c)

def addition(n1, n2):

print(n1 + n2)

addition(100, 300)

addition(-50, 100)

def addition(n1, n2):

if type(n1) != int or type(n2) != int:

print("Only Integers Allowed")

else:

print(n1 + n2)
addition(100, 500)

def full_name(first, middle, last):

print(f"Hello {first.strip().capitalize()} {middle.upper():.1s} {last.capitalize()}")

full_name(" osama ", 'mohamed', "elsayed")

# -------------------------------------------------

# -- Function Packing, Unpacking Arguments *Args --

# -------------------------------------------------

print(1, 2, 3, 4)

myList = [1, 2, 3, 5]

print(myList)

print(*myList)

def say_hello(*peoples): # n1, n2, n3, n4

for name in peoples:

print(f"Hello {name}")

say_hello("Osama", "Ahmed", "Sayed", "Mahmoud")

def show_details(name, *skills):

print(f"Hello {name} Your Skills Is: ")

for skill in skills:


print(skill)

show_details("Osama", "Html", "CSS", "JS")

show_details("Ahmed", "Html", "CSS", "JS", "Python", "PHP", "MySQL")

# ---------------------------------

# -- Function Default Parameters --

# ---------------------------------

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

# ----------------------------------------------------

# -- Function Packing, Unpacking Arguments **KWArgs --

# ----------------------------------------------------

def show_skills(*skills):

print(type(skills))

for skill in skills:

print(f"{skill}")
show_skills("Html", "CSS", "JS")

mySkills = {

'Html': "80%",

'Css': "70%",

'Js': "50%",

'Python': "80%",

"Go": "40%"

def show_skills(**skills):

print(type(skills))

for skill, value in skills.items():

print(f"{skill} => {value}")

show_skills(**mySkills)

# -----------------------------------------------------

# -- Function Packing, Unpacking Arguments Trainings --

# -----------------------------------------------------

myTuple = ("Html", "CSS", "JS")

mySkills = {

'Go': "80%",

'Python': "50%",

'MySQL': "80%"

}
def show_skills(name, *skills, **skillsWithProgres):

print(f"Hello {name} \nSkills Without Progress Is: ")

for skill in skills:

print(f"- {skill}")

print("Skills With Progress Is: ")

for skill_key, skill_value in skillsWithProgres.items():

print(f"- {skill_key} => {skill_value}")

show_skills("Osama", *myTuple, **mySkills)

# --------------------

# -- Function Scope --

# --------------------

x = 1 # Global Scope

def one():

global x

x=2

print(f"Print Variable From Function Scope {x}")

def two():
x = 10

print(f"Print Variable From Function Scope {x}")

one()

print(f"Print Variable From Global Scope {x}")

two()

print(f"Print Variable From Global Scope After One Function Is Called {x}")

# ------------------------

# -- Function Recursion --

# ------------------------

# ---------------------------------------------------------------------

# -- To Understand Recursion, You Need to First Understand Recursion --

# ---------------------------------------------------------------------

# Test Word [ WWWoooorrrldd ] # print(x[1:])

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"Print Before Return {word}")

return word[0] + cleanWord(word[1:])

# Stash [ World ]

print(cleanWord("WWWoooorrrldd"))

# ------------------------

# -- Function => lambda --

# -- Anonymous Function --

# ------------------------

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

# [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}"

hello = lambda name, age : f"Hello {name} your Age Is: {age}"

print(say_hello("Ahmed", 36))

print(hello("Ahmed", 36))

print(say_hello.__name__)

print(hello.__name__)

print(type(hello))
# -------------------

# -- File Handling --

# -------------------

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

# --------------------------------------------------

import os

# Main Current Working Directory

print(os.getcwd())

# Directory For The Opened File

print(os.path.dirname(os.path.abspath(__file__)))

# Change Current Working Directory

os.chdir(os.path.dirname(os.path.abspath(__file__)))

print(os.getcwd())

print(os.path.abspath(__file__))

file = open(r"D:\Python\Files\nfiles\osama.txt")

file = open("D:\Python\Files\osama.txt")
# --------------------------------

# -- File Handling => Read File --

# --------------------------------

myFile = open("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.readline())

print(myFile.readlines())

print(myFile.readlines(50))

print(type(myFile.readlines()))

for line in myFile:

print(line)

if line.startswith("07"):

break

# Close The File

myFile.close()
# -----------------------------------------------

# -- File Handling => Write and Append In File --

# -----------------------------------------------

myFile = open("D:\Python\Files\osama.txt", "w")

myFile.write("Hello\n")

myFile.write("Third Line")

myFile = open(r"D:\Python\Files\fun.txt", "w")

myFile.write("Elzero Web School\n" * 1000)

myList = ["Oasma\n", "Ahmed\n", "Sayed\n"]

myFile = open("D:\Python\Files\osama.txt", "w")

myFile.writelines(myList)

myFile = open("D:\Python\Files\osama.txt", "a")

myFile.write("Elzero")

# -------------------------------------

# -- File Handling => Important Info --

# -------------------------------------

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

# -- File Handling => Important Info --

# -------------------------------------

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

# ------------------------

# -- Built In Functions --

# ------------------------

# all()

# any()

# bin()

# id()

# ------------------------

x = [1, 2, 3, 4, []]

if all(x):

print("All Elements Is True")


# ------------------------

# -- Built In Functions --

# ------------------------

# sum()

# round()

# range()

# print()

# ------------------------

# sum(iterable, start)

a = [1, 10, 19, 40]

print(sum(a))

print(sum(a, 40))

# round(number, numofdigits)

print(round(150.501))

print(round(150.554, 2))

# range(start, end, step)

print(list(range(0)))

print(list(range(10)))

print(list(range(0, 20, 2)))

# print()

print("Hello @ Osama @ How @ Are @ You")

print("Hello", "Osama", "How", "Are", "You", sep=" | ")

print("First Line", end=" ")

print("Second Line")

print("Third Line")

else:
print("Theres At Least One Element Is False")

x = [0, 0, []]

if any(x):

print("There's At Least One Element is True")

else:

print("Theres No Any True Elements")

print(bin(100))

a=1

b=2

print(id(a))

print(id(b))

# ------------------------

# -- Built In Functions --

# ------------------------

# abs()

# pow()

# min()

# max()

# slice()

# ------------------------

# abs()
print(abs(100))

print(abs(-100))

print(abs(10.19))

print(abs(-10.19))

print("#" * 50)

# pow(base, exp, mod) => Power

print(pow(2, 5)) # 2 * 2 * 2 * 2 * 2

print(pow(2, 5, 10)) # (2 * 2 * 2 * 2 * 2) % 10

print("#" * 50)

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

print("#" * 50)

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

print("#" * 50)

# slice(start, end, step)

a = ["A", "B", "C", "D", "E", "F"]

print(a[:5])
print(a[slice(5)])

print(a[slice(2, 5)])

# -------------------------------

# -- Built In Functions => 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

# ---------------------------------------------------------------

# Use Map With Predefined Function

def formatText(text):

return f"- {text.strip().capitalize()} -"

myTexts = [" OSama ", "AHMED", " sAYed "]

myFormatedData = map(formatText, myTexts)

print(myFormatedData)

for name in list(map(formatText, myTexts)):

print(name)

print("#" * 50)

# Use Map With Lambda Function


def formatText(text):

return f"- {text.strip().capitalize()} -"

myTexts = [" OSama ", "AHMED", " sAYed "]

for name in list(map((lambda text: f"- {text.strip().capitalize()} -"), myTexts)):

print(name)

# ----------------------------------

# -- Built In Functions => 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

# [5] The Function Need To Return Boolean Value

# ---------------------------------------------------------------

# Example 1

def checkNumber(num):

return num > 10

myNumbers = [0, 0, 1, 19, 10, 20, 100, 5, 0]

myResult = filter(checkNumber, myNumbers)

for number in myResult:

print(number)
print("#" * 50)

# Example 2

def checkName(name):

return name.startswith("O")

myTexts = ["Osama", "Omer", "Omar", "Ahmed", "Sayed", "Othman"]

myReturnedData = filter(checkName, myTexts)

for person in myReturnedData:

print(person)

print("#" * 50)

# Example 3

myNames = ["Osama", "Omer", "Omar", "Ahmed", "Sayed", "Othman", "Ameer"]

for p in filter(lambda name: name.startswith("A"), myNames):

print(p)
# ----------------------------------

# -- Built In Functions => 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 Element And So On

# [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 = [1, 8, 2, 9, 100]

result = reduce(sumAll, numbers)

result = reduce(lambda num1, num2: num1 + num2, numbers)

print(result)

# ((((1 + 8) + 2) + 9) + 100)
# ------------------------

# -- Built In Functions --

# ------------------------

# enumerate()

# help()

# reversed()

# ------------------------

# enumerate(iterable, start=0)

mySkills = ["Html", "Css", "Js", "PHP"]

mySkillsWithCounter = enumerate(mySkills, 20)

print(type(mySkillsWithCounter))

for counter, skill in mySkillsWithCounter:

print(f"{counter} - {skill}")

print("#" * 50)

# help()

print(help(print))

print("#" * 50)

# reversed(iterable)

myString = "Elzero"
print(reversed(myString))

for letter in reversed(myString):

print(letter)

for s in reversed(mySkills):

print(s)

# ---------------------------------

# -- Modules => 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 Main Module

import random

print(random)

print(f"Print Random Float Number {random.random()}")

# Show All Functions Inside Module

print(dir(random))

# Import One Or Two Functions From Module

from random import randint, random

print(f"Print Random Float {random()}")

print(f"Print Random Integer {randint(100, 900)}")


# -----------------------------------

# -- Modules => Create Your Module --

# -----------------------------------

import sys

sys.path.append(r"D:\Games")

print(sys.path)

import elzero

print(dir(elzero))

elzero.sayHello("Ahmed")

elzero.sayHello("Osama")

elzero.sayHello("Mohamed")

elzero.sayHowAreYou("Ahmed")

elzero.sayHowAreYou("Osama")

elzero.sayHowAreYou("Mohamed")

# Alias

import elzero as ee

ee.sayHello("Ahmed")

ee.sayHello("Osama")

ee.sayHello("Mohamed")

ee.sayHowAreYou("Ahmed")

ee.sayHowAreYou("Osama")

ee.sayHowAreYou("Mohamed")

from elzero import sayHello


sayHello("Osama")

from elzero import sayHello as ss

ss("Osama")

# ------------------------------------------

# -- Modules => 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/"

# ---------------------------------------------------------------------

import termcolor

import pyfiglet

print(dir(pyfiglet))

print(pyfiglet.figlet_format("Elzero"))

print(termcolor.colored("Elzero", color="yellow"))

print(termcolor.colored(pyfiglet.figlet_format("Elzero"), color="yellow"))

# -----------------------------------

# -- Date and Time => Introduction --

# -----------------------------------
import datetime

# print(dir(datetime))

# print(dir(datetime.datetime))

# Print The Current Date and Time

print(datetime.datetime.now())

print("#" * 40)

# Print The Current Year

print(datetime.datetime.now().year)

# Print The Current Month

print(datetime.datetime.now().month)

# Print The Current Day

print(datetime.datetime.now().day)

print("#" * 40)

# Print Start and End Of Date

print(datetime.datetime.min)

print(datetime.datetime.max)

print("#" * 40)

# print(dir(datetime.datetime.now()))

# Print The Current Time

print(datetime.datetime.now().time())
print("#" * 40)

# Print The Current Time Hour

print(datetime.datetime.now().time().hour)

# Print The Current Time Minute

print(datetime.datetime.now().time().minute)

# Print The Current Time Second

print(datetime.datetime.now().time().second)

print("#" * 40)

# Print Start and End Of Time

print(datetime.time.min)

print(datetime.time.max)

print("#" * 40)

# Print Specific Date

print(datetime.datetime(1982, 10, 25))

print(datetime.datetime(1982, 10, 25, 10, 45, 55, 150364))

print("#" * 40)

myBirthDay = datetime.datetime(1982, 10, 25)

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


# ----------------------------------

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

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

# --------------------------

# -- 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 next() Method Return 1 Element At A Time

# [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"

myList = [1, 2, 3, 4, 5]

for letter in myString:

print(letter, end=" ")

for number in myList:

print(number, end=" ")

myIterator = iter(myString)

print(next(myIterator))

print(next(myIterator))

print(next(myIterator))

print(next(myIterator))

print(next(myIterator))

print(next(myIterator))

for letter in iter("Elzero"):

print(letter, end=" ")


# ----------------

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

myGen = myGenerator()

print(next(myGen), end=" ")

print("Hello From Python")

print(next(myGen), end=" ")

for number in myGen:

print(number)

# -------------------------

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

@myDecorator

def sayHello():

print("Hello From Say Hello Function")

@myDecorator

def sayHowAreYou():

print("Hello From Say How Are You Function")

afterDecoration = myDecorator(sayHello)

afterDecoration()

sayHello()

print("#" * 50)

sayHowAreYou()
# --------------------------------------------

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

def myDecoratorTwo(func): # Decorator

def nestedFunc(num1, num2): # Any Name Its Just For Decoration

print("Coming From Decorator Two")

func(num1, num2) # Execute Function

return nestedFunc # Return All Data

@myDecorator

@myDecoratorTwo

def calculate(n1, n2):

print(n1 + n2)

calculate(-5, 90)
# ----------------------------------------

# -- Decorators => Practical Speed Test --

# ----------------------------------------

from time import time

def myDecorator(func): # Decorator

def nestedFunc(*numbers): # Any Name Its Just For Decoration

for number in numbers:

if number < 0:

print("Beware One Of The Numbers Is Less Than Zero")

func(*numbers) # Execute Function

return nestedFunc # Return All Data

@myDecorator

def calculate(n1, n2, n3, n4):

print(n1 + n2 + n3 + n4)

calculate(-5, 90, 50, 150)

def speedTest(func):

def wrapper():
start = time()

func()

end = time()

print(f"Function Running Time Is: {end - start}")

return wrapper

@speedTest

def bigLoop():

for number in range(1, 20000):

print(number)

bigLoop()

# ----------------------------------------------------

# -- Practical => Loop on Many Iterators With Zip() --

# ----------------------------------------------------

# zip() Return A Zip Object Contains All Objects

# zip() Length Is The Length of Lowest Object

# ------------------------------------------------

list1 = [1, 2, 3, 4, 5]

list2 = ["A", "B", "C", "D"]

tuple1 = ("Man", "Woman", "Girl", "Boy")

dict1 = {"Name": "Osama", "Age": 36, "Country": "Egypt", "Skill": "Python"}

for item1, item2, item3, item4 in zip(list1, list2, tuple1, dict1):


print("List 1 Item =>", item1)

print("List 2 Item =>", item2)

print("Tuple 1 Item =>", item3)

print("Dict 1 Key =>", item4, "Value =>", dict1[item4])

ultimateList = zip(list1, list2)

print(ultimateList)

for item in ultimateList:

print(item)

# -------------------------------------------------

# -- Practical => Image Manipulation With Pillow --

# -------------------------------------------------

from PIL import Image

# Open The Image

myImage = Image.open("D:\Python\Files\game.jpg")

# Show The Image

myImage.show()

# My Cropped Image

myBox = (300, 300, 800, 800)

myNewImage = myImage.crop(myBox)

# Show The New Image

myNewImage.show()

# My Converted Mode Image

myConverted = myImage.convert("L")

myConverted.show()
# --------------------------------------------

# -- Doc String & Commenting vs Documenting --

# --------------------------------------------

# [1] Documentation String For Class, Module or Function

# [2] Can Be Accessed From The Help and Doc Attributes

# [3] Made For Understanding The Functionality of The Complex Code

# [4] Theres One Line and Multiple Line Doc Strings

# -------------------------------------------------

def elzero_function(name):

"""

Elzero Function

It Say Hello From Elzero

Parameter:

name => Person Name That Use Function

Return:

Return Hello Message To The Person

"""

print(f"Hello {name} From Elzero")

elzero_function("Ahmed")

print(dir(elzero_function))

print(elzero_function.__doc__)

help(elzero_function)

# -----------------------------------------------

# -- Installing And Use Pylint For Better Code --

# -----------------------------------------------
"""

This is My Module

To Create Function

To Say Hello

"""

def say_hello(name):

'''This Function Only Say Hello To Someone'''

msg = "Hello"

return f"{msg} {name}"

say_hello("Ahmed")

# -----------------------------------

# -- Errors And Exceptions Raising --

# -----------------------------------

# [1] Exceptions Is A Runtime Error Reporting Mechanism

# [2] Exception Gives You The Message To Understand The Problem

# [3] Traceback Gives You The Line To Look For The Code in This Line

# [4] Exceptions Have Types (SyntaxError, IndexError, KeyError, Etc...)

# [5] Exceptions List https://docs.python.org/3/library/exceptions.html

# [6] raise Keyword Used To Raise Your Own Exceptions

# -----------------------------------------------------------------

x = -10

if x < 0:

raise Exception(f"The Number {x} Is Less Than Zero")

print("This Will Not Print Because The Error")


else:

print(f"{x} Is Good Number and Ok")

print('Print Message After If Condition')

y = 10

if type(y) != int:

raise ValueError("Only Numbers Allowed")

print('Print Message After If Condition')

# -----------------------------------

# -- Exceptions Handling --

# -- Try | Except | Else | Finally --

# -----------------------------------

# Try => Test The Code For Errors

# Except => Handle The Errors

# ----------------------------

# Else => If No Errors

# Finally => Run The Code

# ------------------------

number = int(input("Write Your Age: "))

print(number)

print(type(number))

try: # Try The Code and Test Errors


number = int(input("Write Your Age: "))

print("Good, This Is Integer From Try")

except: # Handle The Errors If Its Found

print("Bad, This is Not Integer")

else: # If Theres No Errors

print("Good, This Is Integer From Else")

finally:

print("Print From Finally Whatever Happens")

try:

# print(10 / 0)

# print(x)

print(int("Hello"))

except ZeroDivisionError:

print("Cant Divide")

except NameError:

print("Identifier Not Found")

except ValueError:

print("Value Error Elzero")

except:

print("Error Happens")
# -----------------------------------

# -- Exceptions Handling --

# -- Try | Except | Else | Finally --

# -- Advanced Example --

# -----------------------------------

the_file = None

the_tries = 5

while the_tries > 0:

try: # Try To Open The File

print("Enter The File Name With Absolute Path To Open")

print(f"You Have {the_tries} Tries Left")

print("Example: D:\Python\Files\yourfile.extension")

file_name_and_path = input("File Name => : ").strip()

the_file = open(file_name_and_path, 'r')

print(the_file.read())

break

except FileNotFoundError:

print("File Not Found Please Be Sure The Name is Valid")


the_tries -= 1

except:

print("Error Happen")

finally:

if the_file is not None:

the_file.close()

print("File Closed.")

else:

print("All Tries Is Done")

# --------------------

# -- Debugging Code --

# --------------------

my_list = [1, 2, 3]

my_dictionary = {"Name": "Osama", "Age": 36, "Country": "Egypt"}

for num in my_list:

print(num)

for key, value in my_dictionary.items():


print(f"{key} => {value}")

def function_one_one():

print("Hello From Function One")

function_one_one()

# ------------------

# -- Type Hinting --

# ------------------

def say_hello(name) -> str:

print(f"Hello {name}")

say_hello("Ahmed")

def calculate(n1, n2) -> str:

print(n1 + n2)

calculate(10, 40)

# ----------------------------------

# -- Regular Expressions => Intro --

# ----------------------------------

# [1] Sequence of Characters That Define A Search Pattern

# [2] Regular Expression is Not In Python Its General Concept

# [3] Used In [Credit Card Validation, IP Address Validation, Email Validation]

# [4] Test RegEx "https://pythex.org/"

# [5] Characters Sheet "https://www.debuggex.com/cheatsheet/regex/python"


# ----------------------------------------

# -- Regular Expressions => Quantifiers --

# ----------------------------------------

#* 0 or more

#+ 1 or more

#? 0 or 1

# {2} Exactly 2

# {2, 5} Between 2 and 5

# {2,} 2 or more

# (,5} Up to 5

# -------------

# -----------------------------------------------------------------------

# -- Regular Expressions => Characters Classes Training's --

# -----------------------------------------------------------------------

# [0-9]

# [^0-9]

# [A-Z]

# [^A-Z]

# [a-z]

# [^a-z]

# ---------------------------------------

# -- Regular Expressions => Assertions --

# ---------------------------------------

#^ Start of String

#$ End of string

# -------------------------

# Match Email

# [A-z0-9\.]+@[A-z0-9]+\.[A-z]+

# ^[A-z0-9\.]+@[A-z0-9]+\.(com|net|org|info)$
# ----------------------------------------------------

# -- Regular Expressions => Logical Or And Escaping --

# ----------------------------------------------------

#| Or

#\ Escape Special Characters

# () Separate Groups

# -----------------------------

# (\d-|\d\)|\d>) (\w+)

# (\d{3}) (\d{4}) (\d{3}|\(\d{3}\))

# ^(https?://)(www\.)?(\w+)\.(net|org|com|info|me)$

# ---------------------------------------------------------

# -- Regular Expressions => Re Module Search And FindAll --

# ---------------------------------------------------------

# search() => Search A String For A Match And Return A First Match Only

# findall() => Returns A List Of All Matches and Empty List if No Match

# ---------------------------------------------------------------------

# Email Pattern => [A-z0-9\.]+@[A-z0-9]+\.(com|net|org|info)

# ----------------------------------------------------------

import re

my_search = re.search(r"[A-Z]{2}", "OOsamaEElzero")

print(my_search)

print(my_search.span())

print(my_search.string)

print(my_search.group())

is_email = re.search(r"[A-z0-9\.]+@[A-z0-9]+\.(com|net)", "[email protected]")


if is_email:

print("This is A Valid Email")

print(is_email.span())

print(is_email.string)

print(is_email.group())

else:

print("This is Not A Valid Email")

email_input = input("Please Write Your Email: ")

search = re.findall(r"[A-z0-9\.]+@[A-z0-9]+\.com|net", email_input)

empty_list = []

if search != []:

empty_list.append(search)

print("Email Added")

else:

print("Invalid Email")

for email in empty_list:

print(email)
# ----------------------------------------------------

# -- Regular Expressions => Re Module Split And Sub --

# ----------------------------------------------------

# split(Pattern, String, MaxSplit) => Return A List Of Elements Splitted On Each Match

# sub(Pattern, Replace, String, ReplaceCount) => Replace Matches With What You Want

# ---------------------------------------------------------------------

import re

string_one = "I Love Python Programming Language"

search_one = re.split(r"\s", string_one, 1)

print(search_one)

print("#" * 50)

string_two = "How-To_Write_A_Very-Good-Article"

search_two = re.split(r"-|_", string_two)

print(search_two)

print("#" * 50)

# Get Words From URL

for counter, word in enumerate(search_two, 1):

if len(word) == 1:

continue
print(f"Word Number: {counter} => {word.lower()}")

print("#" * 50)

my_string = "I Love Python"

print(re.sub(r"\s", "-", my_string, 1))

# ------------------------------------------------------

# -- Regular Expressions => Group Trainings And Flags --

# ------------------------------------------------------

import re

my_web = "https://www.elzero.org:8080/category.php?article=105?name=how-to-do"

search = re.search(r"(https?)://(www)?\.?(\w+)\.(\w+):?(\d+)?/?(.+)", my_web)

print(search.group())

print(search.groups())

for group in search.groups():

print(group)

print(f"Protocol: {search.group(1)}")

print(f"Sub Domain: {search.group(2)}")

print(f"Domain Name: {search.group(3)}")

print(f"Top Level Domain: {search.group(4)}")

print(f"Port: {search.group(5)}")

print(f"Query String: {search.group(6)}")

You might also like