My Python Dictionary

Download as pdf or txt
Download as pdf or txt
You are on page 1of 49

My python Dictionary.

• Vid 1:
Introduction and what’s python..
Python is a very strong programming language
Pros:
-Can do any thing
-Free and open source
-interpreted
-interactive (you can see output in the terminal)
-easy to install
-clean code easily
-easy error handling and debugging
-cross platform (reference for os library)
-expressive
-OOP
-integrated
-modules and packages
-lib and plugins, pip
-memory management (Garbage Collection)
-multi purposes
-community
-growing fast
-basic knowledge

Usages:
-web dev (Django, flask)
-Games (pygame)
-Desktop (pygui, tkinter)
-hacking
-machine learning & data science
-ai
-automation, web scraping(requests, selenium)
-android game
• Vid 2:
What I Need ?(prequests)
▪ Text editor (vs code recommended)
▪ Python installed
▪ Vs code python extension
▪ Cmd basic commands
▪ Path knowledge

• Vid 3:
Syntax and first app
▪ Presentation to print function
o print("this is the first line of code")
o print("Hello world")

▪ When you can use semi colon


o Print("you can do it");print("many codes on one line")
▪ What is indentation
o The spaces left before a block of code to define that
this code belongs to a certain heading like if
statements or loops
▪ Quick view for debugging
o Python offers a great built in debugger which tells
you where the error is and why it happened
• Vid 4:
Comments
▪ Single line comment
o # this is a comment
▪ Multiple line comments
o # this is line one
o # this is line two
Note: there is no multi line comment in python
Inline comments # this is an inline comment
▪ Prevent running code
o # Print("this won’t be printed")
▪ Using strings to make multiple line comments ( not
convention) also called documentation and it’s used to
explain what a certain function or a block of code do
o """
o this is some sort of documentation
o Actually this is a string
o In this string ‘ and “ are escaped , also \ doesn’t do a
ny thing
o """
• Vid 5:
Dealing with data
▪ Why we need different types of data
▪ Intro to string , num, Booleans
o "this is a string"
o 'this is also a string'
o 123 # integer
o 6,823 #float
o True #bool
• Vid 6:
o Some Data Types Overviews
▪ The type function
o print(type(10))
>>> class ‘int’
▪ Every type in python is a class and every element is an
object
▪ # Integers , float >>
▪ 1, 3, 3.6, 78.23
▪ # Strings >>
▪ 'this is my string', "this is also a string"
▪ # Lists
▪ [ ‘these’, ‘are’ , 2, ‘lists’, [‘it’, “can”, True, “have” , “l
ists”]]
▪ # tuples
▪ (“tuple” , “is” , “same” , “as” ,[1, 3, 5, “I mean list”, ] ,
‘but you can’t change’)
▪ # Dictionary
▪ {"key":"value"}
▪ # Bool
▪ True, False

o Code
print(type(10)) # int => Integer
print(type(100.9)) # float => Floating Point Number
print(type("Hello Python")) # str => String
print(type([1, 2, 3, 4, 5])) # list => List
print(type((1, 2, 3, 4, 5))) # tuple => Tuple
print(type({"One": 1, "Two": 2, "Three": 3})) #
dict => Dictionary
print(type(2 == 2)) # bool => Boolean

• Vid 7:
Variables Part One
▪ When you need to use a variable
▪ Syntax name = value
o Name = "ahmed"
o Age = 20
▪ Available chars to start a variable name with (a-z , A-Z)
underscore
▪ Can’t use special chars or key words
▪ It’s case sensitive
▪ Can’t use variable before declaration
▪ You can use camelCase style and snake_case style for
naming
• Vid 8:
Variables part two
▪ Source code: this is the code which the developer types
▪ Translation: translating the source code into machine code
▪ Compilation: compiling the source code before the
execution of the code
▪ Runtime: the time which the code run in
▪ Interpreted: doesn’t need to be compiled before running (
compiled in the runtime)
▪ Python is dynamically typed language: you can change the
data types in the same variable during the runtime
▪ To get the key words you can use help(“keywords”)
▪ Declaring multiple vars a, b, c = 1, 2, 3
• Vid 9:
Escape sequences chars
▪ \b Back Space
▪ my_string = 'this is back space\b'
▪ \ escape new line
▪ my_string = 'this is my \
▪ new line escaping '
▪ \\ escape back slash
▪ my_string = 'this is back slash\\'
▪ \’ , \” escape the quotes
▪ my_string = 'this is single \' quote'
▪ my_string = 'this is double \' quotes'
▪ \n new line (line feed)
▪ my_string = 'this is new line\n'
▪ \r carriage return
▪ print('123456\ahmed')
>>> ahmed56
▪ \t tab
▪ my_string = 'this is tab \t'
▪ \xhh chars hex value
▪ You can find all characters here
• Vid 10:
Concatenation and training
▪ first_string = 'my name is'
▪ second_one = ' ahmed'
▪ concatenated_string = first_string + second_one
▪ print(concatenated_string)
▪ >>>> my name is ahmed
▪ can’t concatenate string with int
▪ you can do it with formatting (later)

• Vid 11:
Strings
▪ You can use single or double quotes with the same result
▪ first_string = 'my string'
▪ second_one = "my string"
▪ You can use triple quotes to write multiple lines
▪ first_string = """
▪ this is a string
▪ this string could be typed on multiple lines
▪ back slash \ is escaped automatically
▪ """
▪ print(first_string)
▪ Triple quotes also escape special chars
• Vid 12:
Indexing and slicing
▪ Python uses zero based indexing
▪ Use square brackets [] with positive or negative to index
from the end
o Name = "ahmed"
o print(Name[0])
>>> a
o print(Name[-1])
>>> d
▪ Use square brackets with [start:end:steps] to access
multiple
o print(Name[2:5])
>>> med
o print(Name[0:3:2])
>>> am
▪ Default values [0:end:1]

• Vid 13:
Strings methods part 1
▪ print(len("this is a string"))
>>> 16
▪ rstirp() lstrip() strip() >> removes spaces , from right, left,
both
o spaces = " this is a string with spaces "
o
o print(spaces.strip())
o print(spaces.lstrip())
o print(spaces.rstrip())
o >>> this is a string with spaces
this is a string with spaces
this is a string with spaces
o available param remove certain char or repeated
sequence
▪ spaces = "-------this is a string with dashes------"

▪ print(spaces.strip("-"))
▪ print(spaces.lstrip("-"))
▪ print(spaces.rstrip("-"))
o >>> this is a string with dashes
o this is a string with dashes------
o -------this is a string with dashes
▪ title() makes first letter capital and letters after nums capital
▪ myString = "this is a title string"

▪ print(myString.title())
▪ >>> This Is A Title String
▪ capitalize() make first char capital
▪ myString = "this is a capitalized string"
▪ print(myString.capitalize())
▪ >>> This is a capitalized string
▪ zfill() fills the string with zeros to get some width
o required param width, char to fill wit
▪ myString = "15"
▪ print(myString.zfill(5))
o >>> 00015
▪ upper() make every char capital
▪ print(myString.upper())
o >>> THIS IS A CAPITALIZED STRING
▪ lower() make every char small
▪ myString = "WHEN WE write A STring like THIs "
▪ print(myString.lower())
▪ >>> when we write a string like this
• Vid 14:
Strings methods part 2
▪ Split() splits with space
▪ myString = "WHEN WE write A STring like THIs "
▪ print(myString.split())
▪ >>> ['WHEN', 'WE', 'write', 'A', 'STring', 'like', 'THIs']
o Note: this function returns a list and you can loop over
it(later)
o Available param sep to split with
o myString = "WHEN-WE-write-A-STring-like-THIs "
o print(myString.split(sep='-'))
o >>> ['WHEN', 'WE', 'write', 'A', 'STring', 'like', 'THIs']
o Maxsplit to split only specific amount and keep the left
the same
o print(myString.split(sep='-', maxsplit=3))
>>> ['WHEN', 'WE', 'write', 'A-STring-like-THIs']
o rsplit() does the same from the right
▪ center(width) fill the string with spaces to be specific length
▪ myString = "string"
▪ print(myString.center(10, '-'))
o >>> --string--
▪ required param width , optional param fillchar
▪ count() returns number of specific sequence repeating
▪ print(myString.count('w'))
o >>>3
▪ swapcase() swap cases for every char
▪ myString = "When We Write A String Like This"
▪ print(myString.swapcase())
o >>> wHEN wE wRITE a sTRING lIKE tHIS
▪ startswith(prefix) return bool we can use start, end
▪ myString = "When We Write A String Like This"
▪ print(myString.startswith('When'))
o >>>True
▪ endswith(suffix) same
print(myString.endswith('is')) >>> True
• Vid 15:
String methods part 3
▪ Index(“sub”) returns index of a char or error
▪ Find(“sub”) returns index of sub or -1
▪ myString = "When We Write A String Like This"
▪ print(myString.index('is'))
▪ print(myString.find('is'))

▪ rjust(), ljust() justify the string with number of chars right or
left
▪ splitlines() split string lines and return list
▪ expandtabs() controls the tab size
▪ istitle(), isspace(), islower(), isidentifier(),isalpha(), isalnum()
o these functions return true or false based on the given
string and simply applies what it’s name say

• Vid 16:
String methods part 4
▪ Replace() replaces a given string in the self with another given
string
o Available param count
▪ myString = "When We Write A String Like This"
▪ print(myString.replace("We", "you"))
o >>>When you Write A String Like This
▪ Join() takes an iterable and put the string between every
item in it
▪ myString = ['When', 'We', 'Write', 'A', 'String', 'Like', 'This']
▪ print(", ".join(myString))
▪ When, We, Write, A, String, Like, This
• Vid 17:
String formatting old way
▪ We can use the % placeholder then after the string you can
put the varible you want or a tuple of vars
o Name , age, money , lastName= "ahmed", 20, 120.5, "Yasser"
o print("my name is %s and my age is %d" % (Name, age))
o >>> my name is ahmed and my age is 20
▪ %s for strings %d for int digits %f for floats
▪ You can control the digits of floats with %.nf where n is the
number of digits after the . you need
print("My name is %s and my age is %d and I have %.2f pounds" % (
Name, age, money))

o
▪ You can control the number of chars in string with %.ns
where n is the number of chars
print("my initials are %.1s . %.1s" % (Name, lastName))

o >>> my initials are a . Y


• Vid 18:
Strings formatting new way
▪ Format() this method takes the string or var you want to put
in the string between two {}
▪ print("my name is {} and my age is {}".format(Name, age))
▪ You can use{:s} , {:d}, {:f} with the same result as the old way
▪ print("my initials are {:.1s} . {:.1s}".format(Name, lastName))
▪ {:.2f} is the same as %.2f also for {:5s} and %.5s
▪ You can format digits like money with _ or ,etc {:,d}
▪ You can use indexing in the string placeholder to change the
order of formatting
▪ print('hello {1} {0:.4s} {2:s} '.format('this second', 'first', '
and last'))
▪ You can use f string f’this is my f string {var}’
▪ print(f"my name is {Name} and my age is {age}")
• Vid 19:
Numbers
▪ Int , float, complex
▪ Can access complex parts with attributes .real , .imag
▪ Can convert using float() , int(), complex() functions
▪ Can’t convert from complex
• Vid 20:
Arithmetic Operators
▪ + , - , *, / for basics
▪ Mathematical orders are valid () then * \ then - +
▪ % mod is valid and returns the reminder of the division
▪ ** n gives the power of n
▪ \\ floor division means the integer from division
• Vid 21:
Lists
▪ Lists are created by []
▪ myList = [12, 5, 78, 2]
▪ Lists are ordered and its elements are not unique
▪ Lists are mutable , you can edit a list
▪ They can have different data types inside
▪ You can slice and get a specific item from a list with []
▪ print(myList[0])
▪ >>>12
▪ myList[0] = 5
▪ print(myList[0])
▪ >>>5

• Vid 22:
Lists methods
▪ append() add one element to the the tail of the list
▪ myList = [32,68, 3, 8, 0,3]
▪ myList.append(8)
▪ print(myList)
▪ >>> [32, 68, 3, 8, 0, 3, 8]
▪ two dimensional lists are valid
▪ mySecList = [
▪ [2, 5,78, 4, 9, 3, 3],
▪ [5, 7, 93,2, 8, 2, 8],
▪ ['this', 'is' , 'a', 'list']
▪ ]
▪ extend() add elements in a given list to the self list
▪ mySecList.extend(myList)
▪ print(mySecList)
▪ >>>[[2, 5, 78, 4, 9, 3, 3], [5, 7, 93, 2, 8, 2, 8], ['this', 'is', 'a',
'list'], 32, 68, 3, 8, 0, 3]
▪ Note: if you need to put the new list in the bigger list as a
whole list not each element individually you can use the
append method
▪ remove() removes the first given element from the list or
error
▪ myList = [32,68, 3, 8, 0,3]
▪ myList.remove(3)
▪ print(myList)
▪ >>>[32, 68, 8, 0, 3]
▪ sort() sorts the list from smaller to bigger (int or str)
o available parameter reversed=true
▪ myList.sort()
▪ print(myList)
▪ >>> [0, 3, 3, 8, 32, 68]
▪ reverse() reverse the list, it may contain any type of elements
▪ myList.reverse()
▪ >>>[3, 0, 8, 3, 68, 32]

• Vid 23:
Lists methods part 2
▪ Clear() clears all elements in a list
▪ Copy() returns a shallow copy (independent) of all elements
in a list
▪ Count() returns a number of occurrence
▪ Index() returns the index of a given element or value error
▪ Insert(index, object) inserts object before a given index
▪ Pop() remove and return item in given index
• Vid 24:
Tuples part 1
▪ Create a tuple with ()
▪ Can create a tuple like this 2, 4 (without brackets)
▪ Indexes are valid in tuples
▪ Tuples are immutable , you can’t edit a tuple
▪ Tuples items can be any type and not unique
• Vid 25
Tuples and methods part 2
▪ You can declare a tuple with single element using comma like
“this is tuple”,
▪ You can concatenate tuples with + sign
▪ You can easily multiply a string, tuple or list in an integer to
get the elements repeated with the same type
▪ Count() same as list
▪ Index() same as list
▪ Tuple destruct , you can assign tuples values to variables like
this
o a, b, c, = (“A”, “B”, “C”)
▪ use _ to ignore additional values
o a, b, _, d = (“a”, “b”, “c”, “d”)
• Vid 26:
Sets
▪ Create sets in curly braces {}
▪ Sets are not ordered or indexed
▪ Slicing is not valid
▪ Can’t include mutable data types cause it’s unhashable
▪ Every item in a set is unique
• Vid 27:
Sets methods
▪ Clear() same as list
▪ Union() groups two sets together , you can use |
▪ Add() adds only one element to the set
▪ Copy() same as list
▪ Remove() same as list , gives an error incase not found
▪ Discard() remove with no errro if not found
▪ Pop() returns a random element
▪ Update() updates a set with a unioun of itself and other,
accept list
• Vid 28:
Set methods part 2
▪ Difference() returns the elements in the self set and not in the
given one you can use a - b
▪ Difference_update() same as difference but updates the original
set
▪ Intersection() returns the elements that appear in both sets ,
you can use a & b
▪ Intersection_update() updates the original
▪ Symmetric_difference() gives the elements only one set you can
use a ^ b
▪ Symmetric_difference_update() updates the original
• Vid 29:
Set methods part 3
▪ Issuperset() returns true or false if all elements in a given set are
in the original
▪ Issubset() returns true or false if all elements in the original set
are in the given set
▪ Isdisjoint() returns true or false if all elements in a given set are
not in the original
• Vid 30:
Dictionary
▪ You can create dict with {:} the : separate between key and value
▪ Key must be immutable (hashable) type
▪ Keys must be unique
▪ dicts aren’t orderd
▪ you can access values with dict[key] or dict.get(key)
▪ you can access dict.keys() or dict.values()
▪ you can have two dimensional dicts
▪ access dict in dict with two square brackets [key1][key2]
• Vid 31:
Dictionaries methods part 1
▪ Clear() same as lists
▪ Update() you can give it a key and assign a value
o update({‘ahmed’: ‘dev’})
o dict[‘new key’] = ‘new value’
▪ copy() same as list
• Vid 32:
Dictionaries methods part 2
▪ Setdefault() returns a value of a given key or a given value if not
found, returns None if not given and not found
▪ Popitem() returns the latest added item , used to return a
random item in older versions
▪ Items() return a list of tuples with a deep copy of the dict
▪ Dict.fromkeys(iterablekeys, value) creates a dict from keys with
a given value
• Vid 33:
Bool
▪ You need to check if code is true or false
▪ Bool is only two constant objects True, False
▪ Any datatype without any value returns False else True, None is
False
• Vid 34:
Boolean operators
▪ And >> both the must be true
▪ Or >> either one be true
▪ Not >> returns the reverse of the logic
• Vid 35:
Assignment operators
▪ They are operators that restore the result in the same original
variable
▪ +=, -=, *= , /= , **= , //=, %=
• Vid 36:
Comparison operators
▪ They are operators that are use to compare objects
▪ == , != , < , > , <= , >= ,
▪ Return a bool value(True, False)
• Vid 37:
Type conversion
▪ Python is dynamically typed language
▪ Str() you can convert to a string using this funcion
▪ Tuple() function allow you to convert to s tuple
▪ Set() same
▪ List() same
▪ Note : when you convert any type to a set it loses its order
▪ Note: when you convert a dict to any type it only returns it’s key
and discard the values
▪ Dict() function requires a key and value in the operator to work
so you can use nested list or tuple also sets are not available
cause they are unhashable
• Vid 38:
User input
▪ You can use the input() function to get a string from the user
▪ You can assign it to a variable
• Vid 39:
Practical slice email
▪ You can get the index of the @ sign by email.index(‘@’)
▪ Then you can slice this mail with email[:email.indes(‘@’)]
▪ Then the website would be email[email.index(‘@’) + 1:]
▪ Note: you can chain methods
• Vid 40:
Practical your age full details
▪ You can convert the input string to int with int() function
▪ To get months multiply by 12
▪ To get weeks multiply months by 4
▪ To get days multiply years by 365
▪ To get hours multiply days by 24
▪ To get minutes by 60 also seconds
▪ You can use {:,} to format these strings in a better way
• Vid 41:
o Control flow | if, else, elif
▪ You can use if conditions to make decisions based on some
thing in your code (bool)
▪ Syntax : if condition :
Stement
▪ Else: defines what will happen when the if condition doesn’t
occur
▪ Elif condition: give another condition to decide base on it
what to do and you can use as many as you need

• Vid 42:
Nested if
▪ You can use multiple if conditions inside each other

• Vid 43:
Ternary conditional operator
▪ This is the same logic of the normal if but with a short syntax
▪ print(“this is valid” if isValid else “this is not valid”)
▪ statement when true if condition else statement
• Vid 44:
Calculate age advanced version
▪ Input the data of the user then the unit which he chose
▪ Based on this unit made if conditions chose which type of
data to show up to the user
• Vid 45:
Membership operators
▪ In returns true if the element in the iterable
▪ Not in does the reverse
• Vid 46:
Practical membership control
▪ Given a list of names , take name of user from input and
check if the name in the list
▪ Inupt an option to delete or update this name
▪ Use if condition to decide what to do
▪ You can update the list like this
o Admins[admins.index(“ahmed”)] = “Mostafa”
▪ You can delete using the remove() method
▪ If the user name not in the list input his name and append() it
to the list
• Vid 47:
o Loop while and Else
▪ While condition_is_true
code will run
▪ Make sure not to create an infinite loop
▪ Else in this case happens when ever we break our loop
• Vid 48:
o While training
▪ Having a list you can get its length with len() function
▪ So creating a var = 0 and looping while this var is less than
this list’s length and increase the counter with one every loop
▪ You can use the counter as variable in the loop to count
elemements in the loop
• Vid 49:
o Loop training book mark manager
• Vid 50:
o While training password guess
▪ With a given password
▪ And a start allowed tries
▪ While input(“guess a password”) != password:
tries -= 1
▪ Learned break statement
▪ Else would get executed only if the condition is false, not
braked
• Vid 51:
o For loops
▪ For item in iterable
▪ You can access each item in this iterabe with the name you
chose as a variable
▪ Else in for loops almost useless
▪ If condition and while loops can be put into a for loop
• Vid52:
o For loops training
▪ The function range() returns an iterable class range which you
can loop over
▪ Range doesn’t include the given num in the iterable and
starts from 0 so you can use it with indexing
▪ Looping over a dictionary gives the keys of this dict

• myRange = range(1, 101)

• mySkills = {

• "Html": "90%",

• "Css": "60%",

• "PHP": "70%",

• "JS": "80%",

• "Python": "90%",

• "MySQL": "60%"
• }

• for skill in mySkills:


• print(f"My Progress in Lang {skill} \
Is:{mySkills.get(skill)}")
o
• Vid 53:
o Nested for loops
▪ You can put a for loop into another for loop so you can loop
over a 2d list or 2d dict for example
o myList = [[2, 4, 7, 8, ], [23, 7, 0, 3, 3], [46, 90, 4, 3]]
o for I in myList:
for j in i:
print(j)
>>>2
>>>4
>>>7
>>>8
>>>12
>>>7
>>>0
>>>3
>>>3
>>>46
>>>90
>>>4
>>>3
• Vid 54
o Break continue pass
▪ Break is a keyword which can help you to stop you loop and
get out of it and you can use it under certain condition using
if
▪ Continue is a keyword which can help you to skip a round of
your loop in a certain line and you can use it with a certain
condition
▪ Pass is a keyword which can help you pass a required block of
code which you may haven’t implemented yet of didn’t think
of it’s logic yet , to make sure your code will run without any
errors
• Vid 55:
o Loop advanced dictionaries
▪ You can get the items of a dictionaty with the method items()
▪ This method returns a list with tuples of the key and value
so..
▪ We can loop over both the key and value in a dictionary at
the same time
▪ myDict = {
▪ 'one': 1,
▪ 'two':2,
▪ 'three':3,
▪ 'four':4
▪ }
▪ for key, val in myDict.items():
▪ print(key, val)
>>>one 1
two 2
three 3
four 4
▪ You can also use nested loop if you have a nested dict
• Vid 56:
o Functinos and returns
▪ A function is a code of block which you can reuse by calling
this function
▪ Functions can accept an element to deal with call
parameter
▪ When you pass a function an element to deal with it’s
called an argument
▪ A function can return a value to deal with or not
▪ There are built in functions and user defined functions
def my_function():

print('this is from the function')

my_function()

>>> this is from the function

▪ It’s preferred to return the value so you would be able to


control it outside the function
▪ def my_function():
▪ return('this is from the function')

▪ print(my_function())

>>>this is from the function


• Vid 57:
o Functions with parameters
▪ Functions can deal with parameters and use it in different
ways
• def say_hello(n):

• print(f"Hello {n}")

• say_hello("ahmed")
• say_hello("youssof")
• say_hello("saad")
>>> Hello ahmed
Hello youssof
Hello saad

▪ we can also pass different data types to the function


▪ def addition(n1, n2):
▪ return n1+n2 if type(n1) == int and type(n2) == int els
e 'this is not an int

▪ print(addition(4, 5))
▪ >>> 9
▪ print(addition(4, "this is string"))
▪ >>> this is not an int
• Vid 58:
o Packing and unpacking arguments
▪ We noticed that a function like the print function can be
used with one argument
• print(7)
>>>7
or with multiple args
print(7, 4, 7, 23, 'also with strings', ['or', 'any', 'other',
'type'])
>>>7 4 7 23 also with strings ['or', 'any', 'other', 'type']
This is possible because of the unpacking args mechanism
in python , which means ungrouping multiple args at the
same time and this allows a function to accept as much
arguments as we need
We can see this while trying to print a list
myList = [34, 6, 8, 34, 8, 1]
print(myList)
>>> [34, 6, 8, 34, 8, 1]
Now we can unpack this list with the * sign
myList = [34, 6, 8, 34, 8, 1]
print(*myList)
>>> 34 6 8 34 8 1
As you can notice now the function deals with elements in
the list as if they were stand alone arguments
So we can apply this to our functions by putting a * sign
before our args
def addition(*Ns):
result = 0
for n in Ns:
result += n
return result
now as we can see in this function we can receive as much
as we need of Ns and add them to the variable result and
return it as a submission of the args
print(addition(23, 456, 8, 94, 89, 34, 79, 32))
>>>815
Note : you have to make sure that if you have any normal
arguments you have to put it before the packed args

def print_skills(name, *skills):


for skill in skills:
print(f"{name} have the {skill} skill")
Note: *args are passed in as a tuple object

• Vid 59:
o Functions with default parameters
▪ Some times you may have a default value for some
parameters like steps in slicing a string , its default value is 1
however, the user can easily override this default value and
use for example 2 steps
▪ This is known as parameters with defauls values and these
default values are used in case the user didn’t enter any value
▪ def tell_age(age=20):
▪ print(f'your age is {age}')

▪ tell_age()
➢ your age is 20
▪ tell_age(30)
➢ your age is 30
▪ Note: if you have any normal parameters you should put it
before the default parameter and the packed *args in the end
• Vid 60:
o Packing unpacking keyword arguments
▪ You can accept keyword arguments in your function using **
▪ Key word arguments means arguments with their key words
attached to them and they are packed into the function as a
dictionary so you can loop over its items with the items()
method and access keys and values
▪ def show_skills(**skills):

▪ print(type(skills))

▪ for skill, value in skills.items():

▪ print(f"{skill} => {value}")
▪ We can pass key word arguments to a function from a
dictionary after unpacking it with the same ** signs
▪ mySkills = {
▪ 'Html': "80%",
▪ 'Css': "70%",
▪ 'Js': "50%",
▪ 'Python': "80%",
▪ "Go": "40%"
▪ }

▪ show_skills(**mySkills)

• Vid 61:
o Training
• Vid 62:
o Function scoops
▪ Every function has its own scoop of variables that is different
than the global scoop
▪ If two variables in the global and local scoop of a function
have the same name that doesn’t mean they are the same ,
they are different because python has a great reference to
the variables
▪ You still can use the global variables without declaring it but
trying to assign a new value to it would declare a new
variable with this value in the local scope instead
▪ You can use the global keyword to tell python that you’re
using the global variable and you want to edit it
▪ x = 1

▪ 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 Ca
lled {x}")
• Vid 63:
o Recursion functions
▪ A recursion function is a function that calls it self over and
over
▪ All the called function are built over each other and the
language creates a copy of the function each time it’s called
▪ In the recursion you have a case called the base case on
which the recursion stop for some condition which you
decide , on reaching this base case all cases up over the this
base case are stored in the memory and waiting for the
recursion to finish execution to be able to complete all these
functions and remove them from memory , this is why
recursion may not be the best solution in many cases for
problem solving
▪ Recursion is used perfectly in the backtracking algorithm

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:])
print(cleanWord("WWWoooorrrldd"))
• Vid 64:
o Lambda function
▪ This is a simple type of function without a name used for
simple tasks
▪ Lambda function have only one single expression not a block
of code
▪ You can store the function object in a variable , every
element in python is object so you can store this function
object
▪ hello = lambda name, age : f"Hello {name} your Age Is: {age}"
▪ print(hello('ahmed', 21))
>>> Hello ahmed your age Is 21

• Vid 65:
o Files handling part 1
▪ os library is an operating system independent library
▪ you can use open to open any file with available modes
• r for reading
• a for appending
• w for writing (deletes the old content of the file)
• x for creating file
• don’t forget to close your file after using it , you can use
with open(file, mode) as f:
this does the same as opening the file with the open
function only but it takes care of closing the file after
you finish for you
▪ you can chose the encoding to open a file with encoding arg

• import os

• print(os.getcwd())

• # Directory For The Opened File

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

• 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")
• Vid 66:
o Files handling 2
▪ file = open(r"path\to\my\file", mode='r', encoding='utf-8')
▪ you can access file.name or file.mode or file.encoding as they
are attributes for the file in the the io instance
▪ the read() method reads the content of the file and you can
give it an integer to define how many chars you want to read
▪ readline() methods reads a line or if you give it an integer it
reads only this amount of chars, the next call would continue
reading the same line and stop when it reaches \n (new line)
▪ readlines() return a list of lines in the files
▪ you can loop over the file and use every line in it (the io
object is iterable)
• Vid 67:
o Files handling 3
▪ Write() takes a string and write it to your file
▪ Writelines() takes a list and write it into your file
▪ Note: w would delete the file but it would start from the
begiging , a wouldn’t delete the content but it would start
from the end , however you can always use the seek()
function to go back to a certain position in the file with the
cursor
• Vid 68:
o Files handling 4
▪ Truncate() cut the file and get only the truncated part
▪ Tell() tells you the position of the cursor
▪ Seek() moves the cursor
• Vid 69:
o Built in functions
▪ All() returns true if all elements in iterable are true
▪ Any() returns true if all elements in iterable are true
▪ Bin() convert the number to binary
▪ Id () returns the id of the element in the memory
• Vid 70:
o Built in functions
▪ Sum() takes iterable and returns the submission of the
elements inside , start is a parameter you can pass to start
sum from
▪ Round() this function rounds a float to int also you can give it
n of digits to round to after the point
▪ Range() you can give it a start , you have to give it an end ,
you can give it a step
▪ Print() the separator between strings in this function is space
by default and the end is new line\n
• Vid 71
o Built In functions
▪ Abs() this gives the absolute value of the given num
▪ Pow() raise a number to a power factor , and you can get
mod of it by another num
▪ Min() returns the minimum number or a string of some
values
▪ Max() the opposite
▪ Slice() is the same as [] but it requires the
• A[slice(2, 6)]
• Vid 72:
o Built in functions map
▪ Map() take a function and iterator
▪ It takes every element in the iterable and applies the function
on it
• Vid 73:
o Built in functions filter
▪ Filter() takes a function and iterable
▪ The function should be a function that returns true or false
and this is a validator function
▪ Filter returns the iterable elements that return True from the
validation function

• Vid 74:
o Built in functions reduice
▪ Reduice() this function take function and iterable then it takes
the first two elements in the iterable and apply the function
on them then take the result and apply the function on it with
the next element the repeat
▪ You need to import it from the functools module

• Vid 75:
o Built in functions part 7
▪ Enumerate() this function adds a counter to the given iterable
, the start is a param you can pass
▪ You can loop over the two elements in the enumerate like the
dict
▪ Help() this function returns the properties of the function
from the manual
▪ Reversed() return the same iterable reversed
• Vid 76:
o Modules
▪ Module is a file containing a set of functions
▪ You can import it to help you
▪ You can import multiple modules and use you own modules
▪ You can access modules and functions or files and packages in
modules using the dot notation
▪ You can import using
• From module import function
• Import module
▪ Dir() returns all the data in the object
• Vid 77:
o Create your own module
▪ First you can create a python file with the functions you need
to import in other place
▪ In any file you can import this module if it’s in sys.path and
you can append any path in the run-time to this sys.path list
▪ You can access Any function using the dot notation or you can
• From module import function
• From module import function as [a given name to use
it]
▪ You can give the imported functions or modules a name
which you can use it to call the function if you need so its
name won’t conflict with an exciting function
• Vid 78:
o Install external package
▪ A module is a single file with functions in it
▪ A package is a folder with modules in it
▪ Pip is the python package manager
▪ Pip installs the package you need and all its dependencies
▪ Pip list gives you all the installed packages
▪ Pip install [package name] [package name] [package name]
• Vid 79:
o Date and time
▪ import datetime
▪ print(datetime.datetime.now())
▪ print(datetime.datetime.now().day)
▪ print(datetime.datetime.now().month)
▪ print(datetime.datetime.now().year)
▪ print(datetime.datetime.min)
▪ print(datetime.datetime.max)
▪ print(datetime.datetime.now().time())
▪ print(datetime.datetime.now().time().hour)
▪ print(datetime.datetime.now().time().minute)
▪ print(datetime.datetime.now().time().second)
▪ print((datetime.datetime.now() - datetime.datetime(2001, 5, 25)).
days)
• Vid 80:
o Date and time format
▪ You can find all the string format directives here
▪ import datetime

▪ birth = datetime.datetime(2001, 5, 25)
▪ print(birth)
▪ print(birth.strftime("%d %B %Y"))
• Vid 81:
o Iterable vs iterator
▪ Iterable is the object wich have elements inside it that you
can access or loop over it
▪ String, lists, tuples, etc..
▪ Iterator is an object that can loop over an iterable using the
next() method and return one element each time
▪ You can call iter() to create an iterator from any iterable
▪ The for loops call iter() function for the object that you give
behing the scenes
• Vid 82:
o Gererators
▪ This is a function that creates (generate) elements using the
yield keyword
▪ It gives an iterator which you can call next() on it or use a for
loop for it

def myGen(n, m):

yield n +m
yield n-m
yield n*m
yield n/m

proccesses = myGen(5, 7)

print(next(proccesses))
print(next(proccesses))
print(next(proccesses))
print(next(proccesses))

▪ def myGen(n, m):



▪ yield n +m
▪ yield n-m
▪ yield n*m
▪ yield n/m

▪ for proccess in myGen(3, 8):
▪ print(proccess)
• Vid 83:
o Decorators intro
▪ This Is a function that takes a function as a parameter and
improves it’s functionality by adding or making sure some
thing Is valid and enhance the behavior of the function
▪ Decorators are higher order functions
• def myDecorator(func):
• def nested():
• print('this is before function')
• func()
• print('this is after function')
• return nested

• @myDecorator
• def myFunc():
• print("this is from funcion")

• myFunc()
• Vid 84:
o Decorate functions with parameters
▪ If you want to decorate a function with parameters you have
to pass the parameters to the nested function also
▪ def myDecorator(func):
▪ def nested(n, m):
▪ if m == 0:
▪ raise ZeroDivisionError('can\'t divide by zero ')
▪ func(n, m)

▪ return nested

▪ @myDecorator
▪ def myFunc(n, m):
▪ print(n/m)

▪ print(myFunc(2, 0))
▪ you can use multiple decorators and chose the order of which
decorator occure first
▪ you can use *args , **kwargs in the wrapping function
• Vid 85:
o Practical speed test , decorators
▪ This is a block of code to compare the speed of the same
function with a for a loop vs with an iterator
• from time import time

• def speedTest(func):
• def wrapper(num):
• start = time()
• func(num)
• end = time()
• print(f"running time is {end - start}")
• return wrapper

• @speedTest
• def function(num):
• myIter = iter(range(num))
• while True:
• try:
• print(next(myIter))
• except:
• break

• @speedTest
• def forFunc(num):
• for i in range(num):
• print(i)
• function(9999)
• forFunc(9999)

• Vid 86:
o Loop on many iterables with zip()
▪ This function returns a zip object which is iterable with the
length of the shortest iterable given
▪ You can loop over this zip object and access its elements
▪ Every element in the zip object is a tuple
▪ list1 = [23,68, 89,2 ]
▪ list2 = ['23','68', '89','2' ]

▪ big = zip(list1, list2)
▪ for i, j in big:
▪ print(i, j)
• Vid 87:
o Image manipulation
▪ Pip install pillow
o from PIL import Image
o
o myImage = Image.open(r"path\to\my\photo")
o
o # show the image in the default images viewer
o myImage.show()
o
o # crop the image
o newImage = myImage.crop(0, 0, 300, 400)

▪ you can check more obtions here

• Vid 88:
o Docstring and commenting vs documenting
▪ The document string is a string after defining a function ,
class or a module to explain what this function does and
could be accessed with the help method and the Doc
attributes
▪ def thisIsFunc():
▪ '''THIS IS MY DOCUMENT'''
▪ print('this is')

▪ help(thisIsFunc)
▪ print(thisIsFunc.__doc__)
▪ commenting is simply to explain the details of how the
function work while documenting explain its usage
• Vid 89:
o Installing pylint to type a better code
▪ This is a library that makes sure you use the coding style
convention in python
▪ Pip install pylint
▪ Pylint requires you to name your module with the snake
case naming style
▪ It would require a doc string for the module and the
functions
▪ It would require you to name your functions with the
snake case style
• Vid 90:
o Errors and exceptions raising
▪ Exception is a reporting mechanism that give you a
message to understand the problem
▪ This is the exceptions list in python here
▪ Exception is a runtime error(there are syntax, index, key
erro)
▪ Traceback gives you the line where the error occurs
▪ You can raise your own exception
▪ x = 0
▪ if x == 0 :
▪ raise ZeroDivisionError("can't divide by zero")
▪ print( 10 / x)
• Vid 91:
o Error handling , try , except, else , finally
▪ When you expect an error in the a certain block of code
you have to put this block in a try except block
▪ Note: can’t use try without except (you can pass)
▪ In the except error block of code you can handle this error
and decide what to do
▪ You can specify the error type you want to except and you
can specity multiple types and deal with each one alone
▪ You can also excpect multiple errors and handle them in
one block by passing them as a tuple
▪ Use the else key word to execute a block of code if none of
the exceptions happened
▪ Use the finally keyword to execute a block of code
whatever happened in the try block

▪ try:
▪ age = int(input('enter age: '))
▪ name = input('enter name: ')
▪ numberToTest = 4 / age
▪ except ValueError:
▪ print('this is not an integer')

▪ except ZeroDivisionError:
▪ print('you can\'t have 0 years')
▪ else:
▪ print(f'your name is {name} and age is{age}')
▪ You can except any error and use it as below
▪ try:
▪ age = int(input('enter age: '))
▪ name = input('enter name: ')
▪ number = 4 / age
▪ except Exception as e:
▪ print(e)
• Vid 92:
o Exceptions Handling Advanced Example
▪ theFile = None
▪ tries = 10

▪ while tries > 0:

▪ try:
▪ file_name = input(f"you have{tries} , enter the file n
ame: ").strip()
▪ theFile = open(file_name , 'r')
▪ print(theFile.read())
▪ break

▪ except FileNotFoundError:
▪ print('not found')
▪ tries -= 1

▪ finally:
▪ if theFile:
▪ theFile.close()

• Vid 93
o Debugging code
▪ You can put a break point to stop the code execution and
check for the variables values or active function and know
what you need to find the problem in your app so you can
fix it
• Vid 94
o Type hinting
▪ You can tell python or any one working with you in the
team the type of the data in a variable or given to a
function by this way
▪ def say_hello(name) -> str:
▪ print(f"hello {name}")
▪ def addition(num1, num2) -> int:
▪ print(num1+ num2)
▪ def division(num1:int, num2:int):
▪ print(num1/ num2)
▪ Note : this doesn’t prevent any other type to be passed to
the function this is just for human redabilty
• Vid 95
o Regular expressions
▪ This is a concept which you can use to check for certain
pattern in a string
▪ You can test it here
▪ You can find the special characters here
▪ \d chooses one digit
▪ \D chooses any thing that is not a digit
▪ \s chooses a white space
▪ \S chooses any thing that is not a white space
▪ \w chooses any word character
▪ \W chooses any thing that is not an word character
▪ \d\d chooses two digits after each other
▪ \d\d\d means three sequenced digits
▪ \d\s means a digit then a space
▪ . means any character except the new line
• Vid 96:
o Quantifiers
▪ This is the special chars for the quantity
▪ You can choose a specific character with typing this
character
▪ * quantifier means 0 or more
▪ + means one or more
▪ ? quantifier means 0 or 1
▪ The quantifier is written after the char which specify your
patter
▪ You can use {} to define a number of repeatetions
▪ You can use {} to get a range {2,5} {3,}{,9)
▪ So you can find phone numbers like \d{3}\s\d{4}\s\d{3}
• Vid 97:
o Character classes
▪ You can use [] to find any char in it separately
▪ You can do [a-zA-Z0-9] or [A-z]
▪ [^] would get any thing except things after it
• Vid 98:
o Assertion and email pattern
▪ If you have two similar patterns but not identical you can
use the ? quantifier to try to get some thing that matches
both of them , tepically the difference would be 0 or 1
▪ ^ this make sure that your pattern is the start of the line
▪ $ this make sure that your pattern is the end of the line
▪ You can specify some string with () you can use the pipe
line | to select some string or other string (com|net|edu)
• Vid 99:
o Logical Or & Escaping
▪ You can group parts of a string using ()
▪ You can use | to represent or
▪ You can escape special characters with \
• Vid 100:
o Re Module Search & FindAll
▪ You can import re in python
• import re
▪ the search function returns the first match in the given
string
• my_string = re.search('[A-
z]*', "ahmed yasser soliman")
>>> <re.Match object; span=(0, 5),
match='ahmed'>
▪ findall() function gives all the string that match the
pattern you give and return a list , may be empty if
there is no match
o my_string = re.findall(r'[A-
z]+', "ahmed yasser soliman")
o for i in my_string:
o print(i)

• Vid 101:
o Re Module Split & Sub
▪ re.split function allows you to split as same in the normal
split function but with a given pattern
▪ re.sub function allows you to replace a string that matches
a certain pattern in a given string with another given string
, you can give it a replace count for how many times you
want this pattern to be replaced
• Vid 102:
o Group Training's & Flags
▪ You can group parts together and access them with the
groups() method
▪ You can group all the match groups together with the
group() method and if you give it a number would give you
access to the group you need
▪ Flags are obtional settings you can add to your search
pattern
▪ Ignore case : ignores the capital and small case
▪ Multiline: can deal with multiple lines
▪ Dotall: make the dot (.) match with every thing even the
new line
▪ Verpose : allow comments (don’t use it cause it would
make you struggle to read the pattern

You might also like