0% found this document useful (0 votes)
8 views

Python Basics Notes by Ahmed Naeim

Uploaded by

askw5550
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Python Basics Notes by Ahmed Naeim

Uploaded by

askw5550
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 53

Python Notes

Prepared by Ahmed Naeim


Referencing ElzeroWebSchool & W3Schools

Interpreted: Code processing in the run time (no compilation)

- To run the app from cmder: python file.py


- Indentation is critical in python (spaces before code line)
- Comment using: #
- All data in python are objects
- type(data) → built in function returns data type
- arrays named list in python
- new data type → tuple → implemented as array but in normal brackets (1, 2, 3)
- dict : dictionary → {one: 1, two: 2, three: 3)
- bool: Boolean → true or false

Variables:

- NOTE: data is stored in memory not in variable


- Variable is only address to data
- Syntax → [variable name] [assignment operator] [value]
- Ex → myVariable = “myValue”
- Variable naming rules:
o Begins with only a letter or _
o Can’t begin with number or special characters
o Can include numbers or _ inside the var name
o Can’t include special characters
o Name is not like name, case sensitive
o Unable to use the variable before assigning value to the variable
- To assign values to more than one variable → a, b, c = 1, 2 ,3

NOTES:

- Source code: original code you write it in the computer


- Translation: converting source code into machine language
- Compilation: translate code before the run time
- Run-time: period app takes to execute the command
- Interpreted: code translated on the fly during execution
- Python is dynamic typing language (able to change the var types during run time)
- help(“keywords”) → to know the reserved words

By/ Ahmed M. Naeim


Escape Sequence Characters:

- \b → backspace → delete the character before


- \newline → escape new line +\ → put after each line of a string if it still has remaining
line as:
print(“Hello \
world \
good)
➔ Hello world good
- \\ → to be able to print backslash (escape backslash)
- \’ or \” → to escape single or double quote
- \n → makes new line (line feed character)
- \r → carriage return → takes string after and replacing them with the string or numbers
before with the same number as:
o Print(“123456\rABCD”) → ABCD56
- \t → horizontal tab → makes a tab
- \xhh → character hex value (hh for the hex number)

Concatenation:

- Connect two string to get a bigger one string


- In python we concatenate by + as → print(first_string + second_string) or full =
first_string + second_string
- To add space between them → print(first_string + “ “ + second_string)
- To make a new line between strings → print(first_string + “\n” + second_string)
- Can’t concatenate string with integers (only sting to string)

Strings:

- Works with single or double quote ‘ ’ or “ ”


- To avoid using escape sequence: use the alternative quote type of the var as: var =
“Ahmed ‘is’ a software engineer”
- If you want to make the string in multiple lines do triple (single or double quote) , note it
escapes “” and ‘’ as:

Var = “”” Ahmed

Mohamed ‘ Ali ’ “Naeim”

Is engineer “””

Indexing and slicing:

By/ Ahmed M. Naeim


- All data in python is objects
- Object contains elements
- Each element has its own index
- Python uses zero based indexing (index starts from zero)
- Use square brackets to access element
- Enable accessing parts of strings, tuples or lists
Indexing (access single item)
- We can use as:
myString = “Ahmed Naeim”
print(myString[0]) ➔ A
print(myString[5]) ➔ N
- We can use negative indexing to count from the right side as:
print(myString[-1]) ➔ m #first character from the end

Slicing (access multiple sequence items)


- [start : end] “end is not included” or [start : end : steps] or [ : end ] “if there is no start it
will start from zero index” or [start : ] “if no end specified it will go until the end of the
string ” [:] “if there is no start or end it will get the full string as:
Print(myString[3:7]) ➔ ed N “N is 6”
Print(myString[ : 4] ➔ Ahme
- Steps are 1 by default. If steps are 2 it will get a character and miss one and so on as:
Print(myString [0 : 6 : 2]) ➔ Amd

String Methods

- len() ➔ returns the number element of the object #number not index and spaces are
counted ➔ len(varName)
- strip()➔ removes spaces from right and left of the string
- rstip() ➔ removes spaces from right
- lstrip() ➔ removes spaces from left
ex:
print(myString.strip())
- if you want to remove something not spaces from right and left put it or them in the
brackets as: print(myString.strip(‘@’)) or print(myString.rstrip(‘$%’))
- title() ➔ converts string into a title ➔ each character beginning a word is capitalized
and each character after a number will be capitalized as: print(myString.title())
- capitalize() ➔ each character beginning a word is capitalized but not capitalized after
numbers as: print(myString.capitalize())
- zfill(width) ➔ zero fill on left to organize the output if the output is less than the width
in the function as 01 or 001 and so on: print(num.zfill())
- upper() ➔ convert all characters into upper case: print(myString.upper())
- lower() ➔ convert all characters into lower case: print(myString.lower())

By/ Ahmed M. Naeim


- split() ➔ split strings into list, each word is an element in the list “knowing the word by
the space after” : print(myString.split()) || if I want to split after another thing like “-” we
put it in the split brackets as : print(myString.split(“-“))
- split( , ) ➔ using max split; say it is 2 so it will takes 2 elements and all the rest will be in
one last element as: print(myString.split( “-“ , 2 ))
- rsplit() ➔ makes splits but from the right side; say I said that 2 is the max split so it will
split from the right side BUT it will output from the left normally as:
print(myString.rsplit(“-“,2))
- center() or center( , )➔ it makes the string in the center as you input a number more
than the elements in the string so it will make the string in the middle and divide the
rest of the number into spaces before and after the string. NOTE: if you want to put
something not space put it in the bracket as : print(myString.center(14,”@”))
- count() ➔ counts a text or element how many times they are at the string:
print(myString.count(“A”)) or print(myString.count(“Ahm”))
- count(“ ”, start, end) ➔ counts a text or element how many times they are at the string
but with a start and end indexing : print(myString,count (“A”, 0 , 10))
- swapcase() ➔ convert lower case into upper case and upper case into lower case :
print(myString.swapcase())
- startswith(“ ”) ➔ indicates if the string starts with something and returns a Boolean
true or false as: print(myString,startswith(“A”)) ➔ true
- startswith(“” ,start ,end) ➔ indicates if the string starts with something but from a
starting index until ending index and returns a Boolean true or false
- endswith(“ ”) ➔ indicates if the string ends with something and returns a Boolean true
or false
- endswith(“” ,start ,end) ➔ indicates if the string ends with something but from a
starting index until ending index and returns a Boolean true or false
- index(substring, start, end) ➔ to search for an element or sub-string (start and end are
optional) and returns the index number and it will returns an ERROR if the value is not
found: print(myString.index(“A”, 0, 10))
- find(substring, start, end) ➔ as index but it will return -1 not error if the value is no
found : print(myString(“A”, 0, 12))
- rjust(width, fill character) , ljust(width, fill character) ➔ right and left justified as it put
spaces (if no character is given to fill with) on the right or the left of the string, NOTE: the
string elements is included in the width. Ex ➔ print(myString.rjust(10,“#”)) ➔
#####Ahmed
- splitlines() ➔ returns all lines in list ➔
var = “””Ahmed
Mohamed
Naeim”””
print(var.splitlines()) ➔ [‘Ahmed’, ‘Mohamed’ , ‘Naeim’]
- expandtabs() ➔ to expand the tab to be a number of spaces the developer give
var = “ahmed \t Mohamed \t Naeim”
print(var.expandtabs(5)) ➔ ahmed Mohamed Naeim

By/ Ahmed M. Naeim


- istitle() ➔ returns a Boolean of true or false if the the string is title based (first letter of
any word or after any number is capital)
var1= “Ahmed Naeim”
print(var1.istitle()) ➔true
- isspace() ➔ returns a Boolean of true or false if the variable is space or not:
var1, var2= “ “, “”
print(var1,isspace()) ➔ true
print(var2,isspace()) ➔ false
- islower() ➔ returns Boolean of true or false if the string is lower case
- isidentifier() ➔ is the string can be variable name or not returns Boolean of true or false
- isalpha() ➔ is the string alphabetical letters returns Boolean of true or false
- isalnum() ➔ is the string alphabetical or numbers or both returns Boolean of true or
false
- replace(old value, new value, number of replacement if needed) ➔ replacing any
substring with other new one (no integers), if no number or replacement identified It
will replace all of them
- join(iterable) ➔ join all the list elements:
myList = [“one”, “two”, “three”]
print(“-“,join(mylist)) ➔ one-two-three

String Formatting (Old Way):

- ex:
name = “Ahmed”
age = 23
print(“My name is : “ + name) ➔ my name is ahmed
print(“my name is : “ + name + “my age is: “ + age) ➔ error can’t concatenate string with
integers
print(“my name is : %s “ % “Ahmed”)
print(“my name is : %s” % name)
print(“my name is : %s and my age is %d” % (name, age))
- % ➔ place holder
- %s ➔ string
- %d ➔ integer
- %f ➔ float
- %.(num)f ➔ as %.2f to control how many floating points
- truncate string: as float control ➔ % .(num)s ➔ to control how many elements to
replace in then string

By/ Ahmed M. Naeim


String Formatting (New Way):

- ex:
name = “Ahmed”
age = 23
print(“My name is : {} “ .format(“ahmed”) ➔ my name is ahmed
print(“my name is : {} my age is: {} “ .format(name, age)) ➔ my name is Ahmed, my age
is 10
print(“my name is : {:s} my age is: {:f} “ .format(name, age)) ➔ my name is Ahmed, my
age is 10.000000
- {: } ➔ place holder
- .format(variable, “value”)
- {:s} ➔ string
- {:d} ➔ integer
- {:f} ➔ float
- {.(num)f} ➔ as {:.2f} to control how many floating points
- truncate string: as float control ➔ {: .(num)s} ➔ to control how many elements to
replace in then string as {:.5s}
- format money ➔{: , d} or {:_d}
- rearrange items ➔ print(“{1} {2} {0}” .format(a, b, c)) ➔ b, c, a values

can arrange with defining a data type {3:d}, {2:.4f}

- Format in V3.6+:
print(f“my name is {name} and my age is {age}”)

Search on Pyformat.info for more information

Numbers:
- Integer: + or – {:d}
- Float: + or – {:f} or {:.5f}
- Complex: real part + imaginary part as: 2 + 5j can be complex or complex.real or
complex.imag

num = complex(2,3)
print(num)
print(num.real)
print(num.imag)
Output:

(2+3j)

2.0

By/ Ahmed M. Naeim


3.0

- Able to convert int to float or complex


- Able to convert float to int or complex
- CANNOT convert complex to int or float
Ex: print(100)

intNum = 5
fNum = 2.33

print(float(intNum))
print(int(fNum))
print(complex(intNum))
print(complex(fNum))
Output:

5.0

(5+0j)

(2.33+0j)

Arithmetic operations:

- ‘+’: addition
- ‘-‘: subtraction (can have - - with no error)
- ‘*’: multiplication
- ‘/’: division (default result in float), can change to int by int(var)
- ‘%’: modulus as 8 % 2 (reminder)
- ‘**’: exponent (power)
- ‘//’: floor division (gives the nearest output in in integer form “less or equal”)

Lists:

- List Items are enclosed in square brackets


- Lists are ordered, to use indexes to access item
- Lists are Mutable (add, sub, mult, edit, delete)
- Lists items are not unique (can be repeated)
- List can have different data types
- Can apply slicing as: print(myList[0:3]) //that means the indexes 0,1,2 as the end is not
included
- Can use steps as: print(myList[1:5:2]) //that means the indexes 1,3
- Syntax: myList = [1,2,”Hello”, 100.2]
- Access by index number as: print(myList[0]) or print(myList[-1]) //negative indexes starts
from -1 and it refers to the last index

By/ Ahmed M. Naeim


- Can reassign values as: myList[2] = “Naeim”
- Can reassign values “more than 1 value at a time” by slicing myList[2:4]
- Can delete items as: myList[3] =[]

Lists Methods:

- append() ➔ add element in the end as: myList.append(“Ahmed”)


o The added element may be another list which will be added to the main list as
an element of type list as: myList.append(newList)
myList = [1,2,3]
newList = [4, ,5 ,6]
myList.append(newList) ➔ [1, 2, 3, [4 , 5 ,6 ]]
o Or can get an element in another list as myList.append(newList[2])
- To access an element inside a list element, all in a main list : myList[3][2] as 2 is the index
of the desired element in the sub list and 3 is the index of the sub list in the main list
- extend() ➔merge 2 lists in the first list as :
myList = [1, 2, 3]
newList = [4, 5, 6]
myList.extend(newList) ➔ [1, 2, 3 ,4 ,5 ,6]
- remove() ➔ see all the items from the beginning until it meets the desired remove
element then it removes it (if the desired to remove element is repeated, it will remove
the first one only) as: myList.remove(“Ahmed”)
- sort() ➔ sort the items (not support mix between integers and strings) in a list
ascendingly as: myList.sort()
to sort a list in reverse order : myList.sort(reverse=True)
- reverse() ➔ reverse the items no matter what is the items
- clear() ➔ remove all items from the list but don’t delete the list as: myLsit.clear()
- copy() ➔return a shallow copy of the list (don’t affect the oldList and if the OldList had
any modification but after the copy process, the newList will NOT be updated with this
changes)as: newList = oldList.copy()
- count() ➔ count a specific element repetition in the list : myList,count(“A”)
- index() ➔ returns the index number of the desired item in the list (if repeated it will
return the first one): myList.index(“Naeim”)
- insert(index, object) ➔ insert object before index myList.insert(5, “ahmed”) or
myList.insert(0, “Mohamed”) or myList.insert(-1, “Naeim”)
- pop(index) ➔ removes and return item in index (default last), raises IndexError if the list
is empty or the list is out of range:
- myList = ["A", "B", "C", "D"]
-
- print(myList.pop(2))
- print(myList)

C
['A', 'B', 'D']

By/ Ahmed M. Naeim


- len() ➔ returns the number of items in list as: len(friends)

how to remove duplicates from a List in Python:

mylist = ["a", "b", "a", "c", "c"]


mylist = list(dict.fromkeys(mylist))
print(mylist)

Tuple:

- Items are enclosed in parentheses (brackets) ➔ myTuple = (“One”, “Two”)


- You can remove parentheses if you want ➔ myTuple = “One”, “Two”
- Tuples are in order, we can use indexing to access ➔ print(myTuple[2])
- Tuples are immutable, can’t add or delete
- Tuple items are not unique
- Items can have different data types
- Operators used in strings and lists available in tuple

Tuple Methods:

- To identify that a tuple with one element is a tuple (default will be as a string or float or
integer), you must add a , after it as ➔ myTuple= (“Ahmed”,) or myTuple =
“Ahmed”, ➔

myTuble = 23,
print(type(myTuble))
<class 'tuple'>

myTuble = (23)
print(type(myTuble))
<class 'int'>

- Tuple concatenation: as ➔ a = b + (“Ahmed”, 2, True) + c


- Tuple, List, String Repeat (*) ➔
myTuple = (“Ahmed” , “Naeim”)
print(myTuple * 3) ➔ (“Ahmed” , “Naeim” , “Ahmed” , “Naeim”, “Ahmed” , “Naeim”)
- count() ➔ returns a specific element value how many is repeated in the tuple ➔
print(myTuple.count(“Ahmed”))
- index() ➔ returns the index of an item ➔ print(myTuple.index(“Naeim”))
- Tuple Destruct ➔ note if you want to ignore an element put an _

By/ Ahmed M. Naeim


ex ➔
a = (1, 2, 3)
x, y, z = a
print(f” x= {}, y= {}, z= {}”) ➔ x = 1, y = 2, z = 3
ex 2 ➔
a = (1, 2, 3, 4)
x, y, _ , z = a
print(f” x= {}, y= {}, z= {}”) ➔ x = 1, y = 2, z = 4
- NOTE: to update a Tuple value convert it into a list and then get it back

x = ("apple", "banana", "cherry")
y = list(x)
y[1] = "kiwi"
x = tuple(y)
print(x)

- Hashing: it is a mechanism that help you to search quickly in the computer memory.

Set:

- Set items are enclosed in curl brackets {}


- Set items are NOT ordered and NOT indexed
- Set indexing and slicing can NOT be done
- Set has ONLY immutable data types (Numbers, Strings, Tuples). List and Dictionary are
not allowed
- Set items are UNIQUE

Set Methods:

- clear() ➔ remove all elements from the set ➔ mySet.clear()


- union() ➔ union 2 or more sets ➔ mySet1.union(mySet2) or (mySet1 | mySet2)
- add() ➔add 1 item to the set ➔ mySet1.add(5)
- copy() ➔ to copy the set (shallow copy “don’t affect the original and if ant updates acts
on the original after the copy process, it will not affect the copied set”) ➔ newSet =
mySet.copy()
- remove() ➔ remove a specific item called by value (NOTE: if you tried to remove a non-
existing item, it will give an error) ➔ mySet.remove(“Ahmed”)
- discard() ➔ remove a specific item called by value (NOTE: if you tried to remove a non-
existing item, it will NOT give an error) ➔ mySet.discard(“Ahmed”)
- pop() ➔ get a random item from the set ➔ mySet.pop()

By/ Ahmed M. Naeim


- update() ➔ update a set with a union or itself and others, you can update with a list
mySet.update([“Ahmed”, 2]) ➔ mySet1.update(mySet2)
- difference() ➔ returns the items in the first set only and doesn’t in the other set (used
for print but not affecting the original set)➔ a.difference(b) or a-b
- difference_update() ➔ returns the items in the first set only and doesn’t in the other
set then update the original set with the difference only➔ a.difference_update(b)
- intersection() ➔ mySet1 & mySet2 ➔ returns the common items between the original
set and another set (used for print but not affecting the original set)➔
mySet1.intersect(mySet2) or mySet1 & mySet2
- intersection_update() ➔ returns the common items between the original set and
another set then update the original set with the intersect (common) only ➔
mySet1.intersect(mySet2) or mySet1 & mySet2
- symmetric_difference() ➔ returns items that isn’t in the both sets as it is in the first and
not in the second or in the second and not in the first (used for print but not affecting
the original set) ➔ mySet1 ^ mySet2 or mySet1.symmetric_difference(mySet2)
- symmetric_difference_update() ➔ returns items that isn’t in the both sets as it is in the
first and not in the second or in the second and not in the first and another set then
update the original set with these elements only ➔
mySet1.symmetric_difference_update(mySet2)

True or False Set Methods:

- issuperset() ➔ returns True/False that the original set is a superset for the second or no
(the original has all the items of the second set) ➔ mySet1.issuperset(mySet2)
- issubset() ➔ returns True/False that the original set is a subset for the second or no (the
second has all the items of the original set) ➔ mySet1.issubset(mySet2)
- isdisjoint() ➔ returns True/False that the original and second sets are disjoint (has no
common items)➔ mySet.isdisjoint(mySet2)

Dictionary:

- Dict items are enclosed in curly braces {}


- Dict items contains key : value
- Dict Keys are Immutable ➔ (number, string, tuple), lists are not allowed
- Dict Value can be in any data type
- Dict Key need to be unique (if repeated it will overwrite the first by the second)
- Dict is not ordered as you can’t access by index but access the elements with the key

user = {

“name”: “ahmed”,

“age”: 23,

“country”: “Egypt”

By/ Ahmed M. Naeim


print(user)

print(user[‘county’]) #access using key

print(user.get(‘country’))

Two Dimensions Dictionary:

- Values are dictionaries

languages = {

“One” : {

“name”: “HTML”,

“progress”: “80%”

},

“Two” : {

“name”: “C”,

“progress”: “90%”

},

“Three” : {

“name”: “Python”,

“progress”: “40%”

},

Print(languages[‘One’])

Print(language[‘two’][‘name’])

- Len() ➔ to get dictionary length ➔ print(len(language)) || print(len(language[‘Two’]))


- Make dictionary from variables➔

Dict1 = {

“name”: “HTML”,

“progress”: “80%”

Dict2 = {

By/ Ahmed M. Naeim


“name”: “C”,

“progress”: “90%”

Dict3 = {

“name”: “Python”,

“progress”: “40%”

allDicts = {

“One” : Dict1,

“Two” : Dict2,

“Three” : Dict3

Another example:

Naeim = "Human"
users = {
"Ahmed": 23,
"Mohamed": 22,
"Ali":21,
Naeim:11
}

print(users)
Output:

{'Ahmed': 23, 'Mohamed': 22, 'Ali': 21, 'Human': 11}

Dictionary Methods:

- clear() ➔ to clear the dict ➔ user.clear()


- update() ➔ to add new member (Note we can add new members without update as
user[“age”] = 23) ➔ member.update({country : “Egypt”})
- copy() ➔ take a shallow copy of a dict in another one ➔ new = main.copy()
- keys()➔To print all dict keys ➔ print(user.keys())
- values()➔To print all dict values ➔ print(user.values())
- setdefault(key, value) ➔ it searches for the key, if it is found it will return it, if it is not
found it will add the key and initialize the value in it ➔ user.setdefault(“name”) ➔
Ahmed || or it is initialized by “Naeim” and I wrote ➔ user.setdefault(“name”,”Ahmed”),

By/ Ahmed M. Naeim


it will ignore Ahmed and return Naeim. || if it is not existed in the dictionary, it will
create a key “name” and initialized it by value “Ahmed”
- popitem() ➔ returns the last element you added to the dictionary (key, value)➔
user.popitem()
- items() ➔it copies with updated in any time not a shallow copy, the var that holds the
items will be a list and has tuples inside ➔ newVar = user.items()
- fromkeys() ➔ it takes the keys and values from variables and make a dictionary as ➔
dict.fromkeys(keysVar, valuesVar)

Boolean:

- it is True or False
- mainly used in if conditions and control flow
- bool() ➔ built-in function returns true or false, trues when any string or int or float
except zero or Boolean or list, false when 0, “ “ (space with double quote or not), any
empty data like list or tuple or dict, False, None (NULL)

Boolean Operators:

- and ➔ need to or more conditions to be true to return true, else it will return zero
- or ➔ any of the conditions is true even it the rest is false, it will return true, only if all
the conditions are false, it returns false
- not ➔ reverse the logic

Assignment Operators:

- = ➔ assign value to a variable


- += ➔ to add on the same variable by a specific value as ➔ x = x+y ➔ x+=y
- -= ➔ to subtract on the same variable by a specific value as ➔ x = x-y ➔ x-=y
- *= ➔ to multiply on the same variable by a specific value as ➔ x = x*y ➔ x*=y
- /= ➔ to divide on the same variable by a specific value as ➔ x = x/y ➔ x/=y
- **= ➔ to power on the same variable by a specific value as ➔ x = x**y ➔ x**=y
- %= ➔ to modulus on the same variable by a specific value as ➔ x = x+y ➔ x+=y
- //= ➔ to floor division on the same variable by a specific value as ➔ x = x+y ➔ x+=y

Comparison Operators:

- == ➔ equal
- != ➔ not equal
- > ➔ greater than
- < ➔ less than
- >= ➔ greater than or equal
- <= ➔ less than or equal

Type Conversion:

By/ Ahmed M. Naeim


- str() ➔ converts into string even it is float or int➔ str(Var1)
- tuple() ➔ converts into tuple even if it is str, list, dict, set can’t do with int because it is
not iterable ➔ tuple(something)
- list() ➔ converts into list even if it is str, tuple, dict, set can’t do with int because it is not
iterable ➔ list(something)
- set() ➔ converts into set even if it is str, list, dict, tuple can’t do with int because it is not
iterable ➔ set(something)
- dict() ➔ converts into dict even if it is nested list, nested tuple can’t do with str, tuple,
list, set or nested set(unhashsable type) int because they must have key and value

User Input:

- input(‘Enter a name’)
- problem (spaces are calculated in input) solution ➔ print(f” {fName.strip()}”) or make it
in the assigned variable

Notes:

- chain method ➔able to use more than one built-in function in the same line ➔
fName.strip().capitalized()
- if you want one character (first) only ➔ print(f”{FName} {MName:.1s} {LName}”)

Practical Slice Email:

email = "[email protected]"
email = email[:email.index("@")].replace(".","") +
email[email.index("@"):]
print(f"first is {email[ :email.index("@")]}")
print(f"second is {email[email.index("@")+1: email.index(".")]}")
print(f"third is {email[email.index(".")+1:]}")

Practical – Your age full details:

- Note: Input will return a string by default

age = int(input("Enter your"))

if Conditions:

- Python relies on indentation (whitespace at the beginning of a line) to define scope in


the code. Other programming languages often use curly-brackets for this purpose.
- Python supports the usual logical conditions from mathematics:

By/ Ahmed M. Naeim


o Equals: a == b
o Not Equals: a != b
o Less than: a < b
o Less than or equal to: a <= b
o Greater than: a > b
o Greater than or equal to: a >= b
- These conditions can be used in several ways, most commonly in "if statements" and
loops.

Syntax:

if “condition”:
argument
elif “condition":
argument
else:
argument
- using condition operators in condition as (and , or, not)

nested if condition:

if condition:
if condition:
argument

Ternary Conditional Operator & short if else:

o If the argument is only one line of code:


- print("A") if a > b else print("B")
- print("A") if a > b else print("=") if a == b else print("B")
Short if ➔ If you have only one statement to execute, you can put it on the same line as the if
statement.

if a > b: print("a is greater than b")

- The pass Statement ➔ if statements cannot be empty, but if you for some reason have
an if statement with no content, put in the pass statement to avoid getting an error.
if b > a:
pass
- Membership Operator ➔ in || not in ➔ it returns True or False:

name = ("Ahmed","Naeim")
print("Ahmed" in name)
print("Naeim" not in name)
True
False

By/ Ahmed M. Naeim


LOOPS:

While:

- While Condition is true the code runs, NOTE: it will go in infinite loop else if you change
the condition variable as using increment of decrement in the loop body. Can make else.
When the loop is done (else: )

while num1 < 10:


print(f"{num1}\n")
num1+=1
else:
print("finished")

- Note:

mylist =[]
mylist.append(f"https\\ {mylist}")

print(f"The password is wrong, { 'Last' if tries == 0 else tries} chances


left")

For LOOP:

- for item in iterable object:


do something
- item name is free to u to create
- the iterable object is a sequence as: list, tuple, set, dict, string

myNumbers = [1,2,3,4,5,6,7,8,9]
for number in myNumbers:
print(number)

myRange = range(1,100)
for number in myRange:
print(number)

mySkills = {
'HTML': '90%',
'CSS': '80%',
'JS': '70%',
'C': '60%',
'C++': '50%',

By/ Ahmed M. Naeim


'Python': '40%'
}
for skill in mySkills:
print(f"Your skilles in language {skill} progress is
{mySkills.get(skill)}")

People = {
'Ahmed': {
'HTML': '90%',
'CSS': '80%',
'JS': '70%',
'C': '60%',
},
'Mohamed': {
'C++': '50%',
'Python': '40%'
},
'Naeim': {
'HTML': '90%',
'C++': '50%',
'Python': '40%'
}
}

for name in People:


print(f"{name}: ")
for skill in People[name]:
print(f" {skill}: {People[name].get(skill)}")
Output:

Ahmed:

HTML: 90%

CSS: 80%

JS: 70%

C: 60%

Mohamed:

C++: 50%

Python: 40%

Naeim:

HTML: 90%

By/ Ahmed M. Naeim


C++: 50%

Python: 40%

Break | Continue | Pass:

- continue: stop the iteration and continue to the next iteration


- break: exit the loop
- pass: do nothing, mainly used to not let the loop or condition without any code

Advanced Loops:

- mainly using dictionaries


- loop on keys and values in the same time

myDict = {
'HTML': '90%',
'CSS': '80%',
'JS': '70%',
'C': '60%',
'C++': '50%',
'Python': '40%',
}

for Skill,SkillProgress in myDict.items():


print(f"your progress in {Skill} is {SkillProgress}")

People = {
'Ahmed' : {
'HTML': '90%',
'CSS': '80%',
'JS': '70%',
'C': '60%',
},
'Naeim' : {
'HTML': '90%',
'C++': '50%',
'Python': '40%'
}
}

for main_key, main_value in People.items():


print(f"{main_key} Progress is:")
for child_key, child_value in main_value.items():
print(f"- {child_key} => {child_value}")

By/ Ahmed M. Naeim


Example:

students = {
"Ahmed": {
"Math": "A",
"Science": "D",
"Draw": "B",
"Sports": "C",
"Thinking": "A"
},
"Sayed": {
"Math": "B",
"Science": "B",
"Draw": "B",
"Sports": "D",
"Thinking": "A"
},
"Mahmoud": {
"Math": "D",
"Science": "A",
"Draw": "A",
"Sports": "B",
"Thinking": "B"
}
}

for name,subject in students.items():


print(name)
for subjectName, grade in subject.items():
if grade == 'A':
gradePoints = 100
elif grade =='B':
gradePoints = 80
elif grade == 'C':
gradePoints = 40
elif grade == 'D':
gradePoints = 20
else:
print ("Enter a valid number")
print(f"- {subjectName} => {gradePoints} points")

Functions:

By/ Ahmed M. Naeim


- A function is a reuseable block of code to do a task
- A function runs when you call it
- A function accept element to deal with called (parameters)
- A function can do the task without returning data
- A function can return data after the job is finished
- A function is created to prevent DRY (don’t repeat yourself)
- A function accepts elements when you call it called (arguments)
- There are built-in functions and user defined functions
- A function is for all the team and all apps

Syntax:

def function_name():
print("Hello Python from inside the function")

#calling by
function_name()

with return

def function_name():
return "Hello Python from inside the function"
#calling by
dataFromFunction = function_name()

Functions Parameters and Arguments:

#def is the function keyword (define)


# say_hello() is function name
#name is a parameter, can be any name
#print(f"Hello {name}") => task
#say_hello("Ahmed") => Ahmed is argument
def say_hello(name):
print(f"Hello {name}")

say_hello("Ahmed")
a = "Naeim"
say_hello(a)

with 2 parameters:

def addition(num1, num2):


print(num1 + num2)

By/ Ahmed M. Naeim


addition(100,200)

Function Packing and Unpacking Arguments *Arg:

- If you do not know how many arguments that will be passed into your function, add a
* before the parameter name in the function definition.
- This way the function will receive a tuple of arguments, and can access the items
accordingly
- When I have a tuple and want to unpack the elements of it
- Application: if I don’t know how many parameters I need to input in the function so I
can put them. To solve it we define the function as: def funcName(*listName) then in
the function argument we loop this tuple and when we need to call the function and
input the parameters, we are allowed to put any number of parameters as the following
example:

def say_hello (*people):


for name in people:
print(f"Hello {name}")

say_hello("Ahmed", "Mohamed","Naeim")

can also have 2 parameters and one of them is unpacked list:

def say_hello (something, *people):

Function Default Parameters:

- If the function has 3 input parameters but accidentally or on purpose we input only 2
parameters, of course it will return an error. We solve this problem by assigning the
parameter that the user may not assign a value to it with a value in the function
definition, so if the user didn’t input the value of the 3rd parameter it will use the pre
assigned (default) value in the function definition.
- Note: the default value must be the last parameter, or it can be last + before last and so
on or it can be all parameters.
- As:

def say_hello (name, age, country = "unknown"):


print(f"Hello {name}, {age}, {country}")

say_hello("Ahmed", 23,"Egypt")
say_hello("Ahmed", 15)

By/ Ahmed M. Naeim


Arbitrary Keyword Arguments, **kwargs:

- If you do not know how many keyword arguments that will be passed into your
function, add two asterisks: ** before the parameter name in the function definition.
- This way the function will receive a dictionary of arguments and can access the items
accordingly.

def my_function(**kid):
print("His last name is " + kid["lname"])

my_function(fname = "Tobias", lname = "Refsnes")

Function Scope:

- We have two types of scope:


o Global scope: which is not in a function and can be used in all the code but if
you tried to overwrite its value in a function, it would not affect the value of this
variable in the rest of the code, else if you used this:

x = 2
def printX():
global x
x = 22
print(x)

def printXnew():
x = 12
print(x)

printX()
printXnew()
print(x)

22

12

22

o Function Scope (local scope): can only be used in the scope of the function and
can’t be called or overwritten outside the function and even if the variable is
defined as a global in function, your can’t use it before calling the function

By/ Ahmed M. Naeim


Recursion Function:

- Python also accepts function recursion, which means a defined function can call itself.
- Recursion is a common mathematical and programming concept. It means that a
function calls itself. This has the benefit of meaning that you can loop through data to
reach a result.
- The developer should be very careful with recursion as it can be quite easy to slip into
writing a function which never terminates, or one that uses excess amounts of
memory or processor power. However, when written correctly recursion can be a very
efficient and mathematically elegant approach to programming.

def tri_recursion(k):
if(k > 0):
result = k + tri_recursion(k - 1)
print(result)
else:
result = 0
return result

print("\n\nRecursion Example Results")


tri_recursion(6)

Lambda Function:

- The power of lambda is better shown when you use them as an anonymous function
inside another function.
- It has no name
- U can call it inline without defining it
- U can use it in return data from another function
- Lambda used for simple functions and def handle the large tasks
- Lambda is one single expression does not block of code
- Lambda type is function

Syntax:

lambda parameter: expression

x = lambda a : a + 10
print(x(5))

x = lambda a, b, c : a + b + c
print(x(5, 6, 2))

By/ Ahmed M. Naeim


def myfunc(n):
return lambda a : a * n

mydoubler = myfunc(2)
mytripler = myfunc(3)

print(mydoubler(11))
print(mytripler(11))

File Handling:

- The key function for working with files in Python is the open() function.
- Make it file = open(r”path”) ➔ to make it a raw string
- The open() function takes two parameters; filename, and mode.

There are four different methods (modes) for opening a file:

- "r" - Read - Default value. Opens a file for reading, error if the file does not exist
- "a" - Append - Opens a file for appending, creates the file if it does not exist
- "w" - Write - Opens a file for writing, creates the file if it does not exist
- "x" - Create - Creates the specified file, returns an error if the file exists

Trick:

- Import os ➔ to get some functions like getcwd() ➔ that gives the current working
directory
- Import os ➔ os.path.abspath(__file__) ➔ return the absolute version of a path
- Import os ➔ dirname() ➔ returns a directory component of a pathname
- Impot os ➔ os.chdir() ➔ change the current working directory

Read file:

- How? ➔ myFile = open(“file absolute path”) or open(“file absolute path”,”r”)


- Print file data object ➔ print(myfile)
- Print file name ➔ print(myfile.name)
- Print file mode ➔ print(myfile.mode)
- Print file encoding ➔ print(myfile.encoding)
- Print file content ➔ print(myfile.read()) or print(myfile.read(n of charcters))
- You can return one line by using the readline() method: print(f.readline())
- You can return lines in a list using ➔ print(myFile.readlines())
- You need to close the file upon finishing ➔ myFile.close()

By/ Ahmed M. Naeim


Write and Append file:

- To write to an existing file, you must add a parameter to the open() function:
o "a" - Append - will append to the end of the file
o "w" - Write - will overwrite any existing content “the "w" method will overwrite
the entire file.”

Open the file "demofile2.txt" and append content to the file:

f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.close()

#open and read the file after the appending:


f = open("demofile2.txt", "r")
print(f.read())

Open the file "demofile3.txt" and overwrite the content:

f = open("demofile3.txt", "w")
f.write("Woops! I have deleted the content!")
f.close()

#open and read the file after the overwriting:


f = open("demofile3.txt", "r")
print(f.read())

Create a New File:

- To create a new file in Python, use the open() method, with one of the following
parameters:
o "x" - Create - will create a file, returns an error if the file exist
o "a" - Append - will create a file if the specified file does not exist
o "w" - Write - will create a file if the specified file does not exist

Truncate: ‫اقتطاع‬

- Deleting all except the number of characters in it ➔ myFile.truncate(num)

Tell:

- To know where the curser, returns the number of characters including new line
- Note: new line is counted as 2 characters in windows

By/ Ahmed M. Naeim


myFile.tell()

Seek:

- If I want to read from a specific offset and read after that when you try to read after
myFile.seek(num)

Remove:

- Need to import os
- To delete a file, you must import the OS module, and run its os.remove() function.
- Put absolute path in the function

import os
os.remove("demofile.txt")

Built-in Functions:

Function Description
abs() Returns the absolute value of a number
all() Returns True if all items in an iterable object
are true
any() Returns True if any item in an iterable object
is true
ascii() Returns a readable version of an object.
Replaces none-ascii characters with escape
character
bin() Returns the binary version of a number
bool() Returns the boolean value of the specified
object
bytearray() Returns an array of bytes
bytes() Returns a bytes object
callable() Returns True if the specified object is callable,
otherwise False
chr() Returns a character from the specified
Unicode code.
classmethod() Converts a method into a class method
compile() Returns the specified source as an object,
ready to be executed
complex() Returns a complex number
delattr() Deletes the specified attribute (property or
method) from the specified object
dict() Returns a dictionary (Array)
dir() Returns a list of the specified object's
properties and methods

By/ Ahmed M. Naeim


divmod() Returns the quotient and the remainder
when argument1 is divided by argument2
enumerate() Takes a collection (e.g. a tuple) and returns it
as an enumerate object
eval() Evaluates and executes an expression
exec() Executes the specified code (or object)
filter() Use a filter function to exclude items in an
iterable object
float() Returns a floating point number
format() Formats a specified value
frozenset() Returns a frozenset object
getattr() Returns the value of the specified attribute
(property or method)
globals() Returns the current global symbol table as a
dictionary
hasattr() Returns True if the specified object has the
specified attribute (property/method)
hash() Returns the hash value of a specified object
help() Executes the built-in help system
hex() Converts a number into a hexadecimal value
id() Returns the id of an object
input() Allowing user input
int() Returns an integer number
isinstance() Returns True if a specified object is an
instance of a specified object
issubclass() Returns True if a specified class is a subclass
of a specified object
iter() Returns an iterator object
len() Returns the length of an object
list() Returns a list
locals() Returns an updated dictionary of the current
local symbol table
map() Returns the specified iterator with the
specified function applied to each item
max() Returns the largest item in an iterable
memoryview() Returns a memory view object
min() Returns the smallest item in an iterable
next() Returns the next item in an iterable
object() Returns a new object
oct() Converts a number into an octal
open() Opens a file and returns a file object
ord() Convert an integer representing the Unicode
of the specified character
pow() Returns the value of x to the power of y
print() Prints to the standard output device
property() Gets, sets, deletes a property

By/ Ahmed M. Naeim


range() Returns a sequence of numbers, starting from
0 and increments by 1 (by default)
repr() Returns a readable version of an object
reversed() Returns a reversed iterator
round() Rounds a numbers
set() Returns a new set object
setattr() Sets an attribute (property/method) of an
object
slice() Returns a slice object
sorted() Returns a sorted list
staticmethod() Converts a method into a static method
str() Returns a string object
sum() Sums the items of an iterator
super() Returns an object that represents the parent
class
tuple() Returns a tuple
type() Returns the type of an object
vars() Returns the __dict__ property of an object
zip() Returns an iterator, from two or more
iterators

For print():

Parameter Description
object(s) Any object, and as many as you like. Will be
converted to string before printed
sep='separator' Optional. Specify how to separate the
objects, if there is more than one. Default is '
'
end='end' Optional. Specify what to print at the end.
Default is '\n' (line feed)
file Optional. An object with a write method.
Default is sys.stdout
flush Optional. A Boolean, specifying if the output
is flushed (True) or buffered (False). Default is
False

Map:

Definition and Usage

- The map() function executes a specified function for each item in an iterable. The item is
sent to the function as a parameter.

Syntax:

map(function, iterables)

By/ Ahmed M. Naeim


Parameter Description
function Required. The function to execute for each
item
iterable Required. A sequence, collection or an
iterator object. You can send as many
iterables as you like, just make sure the
function has one parameter for each iterable.

Example:

def myfunc(a, b):


return a + b

x = map(myfunc, ('apple', 'banana', 'cherry'),


('orange', 'lemon', 'pineapple'))

Filter:

Definition and Usage

- The filter() function returns an iterator where the items are filtered through a function to
test if the item is accepted or not.

Syntax:

filter(function, iterable)
Parameter Description
function A Function to be run for each item in the
iterable
iterable The iterable to be filtered

Example:

ages = [5, 12, 17, 18, 24, 32]

def myFunc(x):
if x < 18:
return False
else:
return True

adults = filter(myFunc, ages)

By/ Ahmed M. Naeim


for x in adults:
print(x)

Reduce:

- Reduce takes (function, Iterator)


- Reduce runs a function first on the first and second element then gives a result
- Then run the function on the result and the third element
- Then run the function on the result and the fourth element and so on
- Till one element is left and this is the result of the reduce
- The function can be pre-defined function or lambda function
- Needs to be imported form functools in the modern versions of p[ython

From functools import reduce

Syntax:

reduce(function, iterator)

enumerate:

- The enumerate() function takes a collection (e.g. a tuple) and returns it as an enumerate
object.
- The enumerate() function adds a counter as the key of the enumerate object.
- Start is optional and the default value is zero

Syntax:

enumerate(iterable, start)
Example 1:

names = ["Ahmed", "MOHAMED", "naeim"]


namesWithCounter = enumerate(names)
for name in namesWithCounter:
print(name)

(0, 'Ahmed')
(1, 'MOHAMED')
(2, 'naeim')

Example 2:

names = ["Ahmed", "MOHAMED", "naeim"]


namesWithCounter = enumerate(names,1)
for count,name in namesWithCounter:

By/ Ahmed M. Naeim


print(f"{count}- {name.strip().capitalize()} ")

1- Ahmed
2- Mohamed
3- Naeim

Help:

- Executes the built-in help system


- Used to know what a function is

Syntax:

help(functionName)

Example:

print(help(print))

Reversed:

- The reversed() function returns a reversed iterator object.


- Sequence is iterable may be list or tuple or even a string and then loop on it
- Can be converted to list using
list(reversed(sequence))

Syntax:

reversed(sequence)
examples:

names = ["Ahmed", "MOHAMED", "naeim"]


myName= "Ahmed"

reversedNames = reversed(names)
reversedMyName = reversed(myName)

for name in reversedNames:


print (name)

for letters in reversedMyName:


print(letters)

for letters in reversedMyName:


print(letters,end="")

naeim

By/ Ahmed M. Naeim


MOHAMED
Ahmed
d
e
m
h
A

Modules
- What is a Module?

Consider a module to be the same as a code library.

• Module is a file contain a set of functions


• You can import module in your app to help you
• You can import multiple modules
• You can create your own module
• Modules saves your time

A file containing a set of functions you want to include in your application.

- Create a Module

To create a module just save the code you want in a file with the file extension .py

Example:

Save this code in a file named mymodule.py

- Use a Module

Now we can use the module we just created, by using the import statement:

Example

Import the module named mymodule, and call the greeting function:

import mymodule

mymodule.greeting("Jonathan")

Note: When using a function from a module, use the syntax:


module_name.function_name.
- Variables in Module

The module can contain functions, as already described, but also variables of all types (arrays,
dictionaries, objects etc):

By/ Ahmed M. Naeim


Example:

Save this code in the file mymodule.py

person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}
Import the module named mymodule, and access the person1 dictionary:

import mymodule

a = mymodule.person1["age"]
print(a)
- Naming a Module

You can name the module file whatever you like, but it must have the file extension .py

- Re-naming a Module

You can create an alias when you import a module, by using the as keyword:

Example

Create an alias for mymodule called mx:

import mymodule as mx

a = mx.person1["age"]
print(a)
- Built-in Modules

There are several built-in modules in Python, which you can import whenever you like.

Example

Import and use the platform module:

import platform

x = platform.system()
print(x)
- Using the dir() Function

There is a built-in function to list all the function names (or variable names) in a module. The
dir() function:

Example

By/ Ahmed M. Naeim


List all the defined names belonging to the platform module:

import platform

x = dir(platform)
print(x)

Note: The dir() function can be used on all modules, also the ones you
create yourself.
- Import From Module

You can choose to import only parts from a module, by using the from keyword.

Example

The module named mymodule has one function and one dictionary:

def greeting(name):
print("Hello, " + name)

person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}
Example

Import only the person1 dictionary from the module:

from mymodule import person1

print (person1["age"])

Note: When importing using the from keyword, do not use the module
name when referring to elements in the module. Example:
person1["age"], not mymodule.person1["age"]

Python PIP
- What is PIP?

PIP is a package manager for Python packages, or modules if you like.

Note: If you have Python version 3.4 or later, PIP is included by default.

By/ Ahmed M. Naeim


- What is a Package?

A package contains all the files you need for a module.

Modules are Python code libraries you can include in your project.

- Check if PIP is Installed

Navigate your command line to the location of Python's script directory, and type the following:

pip –version
- Install PIP

If you do not have PIP installed, you can download and install it from this page:
https://pypi.org/project/pip/

- Download a Package

Downloading a package is very easy.

Open the command line interface and tell PIP to download the package you want.

Navigate your command line to the location of Python's script directory, and type the following:

pip install camelcase


- Using a Package

Once the package is installed, it is ready to use.

Import the "camelcase" package into your project.

import camelcase

c = camelcase.CamelCase()

txt = "hello world"

print(c.hump(txt))
- Find Packages

Find more packages at https://pypi.org/

- Remove a Package

Use the uninstall command to remove a package:

pip uninstall camelCase


The PIP Package Manager will ask you to confirm that you want to remove the camelcase
package.

By/ Ahmed M. Naeim


- List Packages

Use the list command to list all the packages installed on your system:

pip list
Package Version
-----------------------
camelcase 0.2
mysql-connector 2.1.6
pip 18.1
pymongo 3.6.1
setuptools 39.0.1

Python Dates
- A date in Python is not a data type of its own, but we can import a module named
datetime to work with dates as date objects.

Example:

Import the datetime module and display the current date:

import datetime
x = datetime.datetime.now()
print(x)
Date Output:

• When we execute the code from the example above the result will be:

2024-07-22 14:59:43.491400

• The date contains year, month, day, hour, minute, second, and microsecond
• The datetime module has many methods to return information about the date object.

Return the year and name of weekday:

import datetime
x = datetime.datetime.now()
print(x.year)
print(x.strftime("%A"))
Creating Date Objects:

- To create a date, we can use the datetime() class (constructor) of the datetime module.
- The datetime() class requires three parameters to create a date: year, month, day.

Example:

By/ Ahmed M. Naeim


import datetime
x = datetime.datetime(2020, 5, 17)
print(x)
The datetime() class also takes parameters for time and timezone (hour, minute, second,
microsecond, tzone), but they are optional, and has a default value of 0, (None for timezone).

The strftime() Method:

- The datetime object has a method for formatting date objects into readable strings.
- The method is called strftime(), and takes one parameter, format, to specify the format
of the returned string:

Example

Display the name of the month:

import datetime
x = datetime.datetime(2018, 6, 1)
print(x.strftime("%B"))
Directive Description Example
%a Weekday, short version Wed
%A Weekday, full version Wednesday
%w Weekday as a number 0-6, 0 is Sunday 3
%d Day of month 01-31 31
%b Month name, short version Dec
%B Month name, full version December
%m Month as a number 01-12 12
%y Year, short version, without century 18
%Y Year, full version 2018
%H Hour 00-23 17
%I Hour 00-12 05
%p AM/PM PM
%M Minute 00-59 41
%S Second 00-59 08
%f Microsecond 000000-999999 548513
%z UTC offset +0100
%Z Timezone CST
%j Day number of year 001-366 365
%U Week number of year, Sunday as the 52
first day of week, 00-53
%W Week number of year, Monday as the 52
first day of week, 00-53
%c Local version of date and time Mon Dec 31 17:41:00 2018
%C Century 20
%x Local version of date 12/31/18
%X Local version of time 17:41:00

By/ Ahmed M. Naeim


%% A % character %
%G ISO 8601 year 2018
%u ISO 8601 weekday (1-7) 1
%V ISO 8601 weeknumber (01-53) 01

Python Iterators
- An iterator is an object that contains a countable number of values.
- An iterator is an object that can be iterated upon, meaning that you can traverse
through all the values.
- Technically, in Python, an iterator is an object which implements the iterator protocol,
which consist of the methods __iter__() and __next__()

Iterator vs Iterable:

- Lists, tuples, dictionaries, and sets are all iterable objects. They are iterable containers
which you can get an iterator from.
- All these objects have a iter() method which is used to get an iterator:

Example:

Return an iterator from a tuple, and print each value:

mytuple = ("apple", "banana", "cherry")


myit = iter(mytuple)
print(next(myit))
print(next(myit))
print(next(myit))
Even strings are iterable objects, and can return an iterator:

Example

Strings are also iterable objects, containing a sequence of characters:

mystr = "banana"
myit = iter(mystr)
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
Looping Through an Iterator:

- We can also use a for loop to iterate through an iterable object:

Example

By/ Ahmed M. Naeim


Iterate the values of a tuple:

mytuple = ("apple", "banana", "cherry")


for x in mytuple:
print(x)
Example

Iterate the characters of a string:

mystr = "banana"
for x in mystr:
print(x)
The for loop actually creates an iterator object and executes the next() method for each loop.

Create an Iterator:

- To create an object/class as an iterator you have to implement the methods __iter__()


and __next__() to your object.
- As you have learned in the Python Classes/Objects chapter, all classes have a function
called __init__() , which allows you to do some initializing when the object is being
created.
- The __iter__() method acts similar, you can do operations (initializing etc.), but must
always return the iterator object itself.
- The __next__() method also allows you to do operations, and must return the next item
in the sequence.

Example

Create an iterator that returns numbers, starting with 1, and each sequence will increase by one
(returning 1,2,3,4,5 etc.):

class MyNumbers:
def __iter__(self):
self.a = 1
return self

def __next__(self):
x = self.a
self.a += 1
return x

myclass = MyNumbers()
myiter = iter(myclass)

print(next(myiter))

By/ Ahmed M. Naeim


print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))
StopIteration:

- The example above would continue forever if you had enough next() statements, or if it
was used in a for loop.
- To prevent the iteration from going on forever, we can use the StopIteration statement.
- In the __next__() method, we can add a terminating condition to raise an error if the
iteration is done a specified number of times:

Example

Stop after 20 iterations:

class MyNumbers:
def __iter__(self):
self.a = 1
return self

def __next__(self):
if self.a <= 20:
x = self.a
self.a += 1
return x
else:
raise StopIteration

myclass = MyNumbers()
myiter = iter(myclass)

for x in myiter:
print(x)

Introduction to generator expressions

A generator expression is an expression that returns a generator object.

Basically, a generator function is a function that contains a yield statement and returns a
generator object.

For example, the following defines a generator function:

def squares(length):

By/ Ahmed M. Naeim


for n in range(length):
yield n ** 2

The squares generator function returns a generator object that produces square numbers of
integers from 0 to length - 1.

Because a generator object is an iterator, you can use a for loop to iterate over its elements:

for square in squares(5):


print(square)

Output:
0
1
4
9
16

A generator expression provides you with a more simple way to return a generator object.

The following example defines a generator expression that returns square numbers of integers
from 0 to 4:

squares = (n** 2 for n in range(5))

Since the squares is a generator object, you can iterate over its elements like this:

for square in squares:


print(square)

As you can see, instead of using a function to define a generator function, you can use a
generator expression.

A generator expression is like a list comprehension in terms of syntax. For example, a generator
expression also supports complex syntaxes including:

• if statements
• Multiple nested loops
• Nested comprehensions

However, a generator expression uses the parentheses () instead of square brackets [].

Decorators (meta programming)


- Called meta programming

By/ Ahmed M. Naeim


- Everything in python is object
- Decorators take a function and some functionality and return it
- Decorators wrap (nested function) other function and enhance its behavior
- Decorator is a higher order function (function accepts functions as a parameter)
- Can be used as a debugging message
- If there were parameters put it in the function(parameters,..) and
nesterfunction(parameters,..)
- Can use more than one decorator on the same function as:
@decorator1
@decorator2
Function()
- Can use function Packing and Unpacking Arguments *Arg

Example of decorator function:

def myDecorator (func):


def nestedFunc(): #any name it is just for decoration
print("before") #message from decorator
func() #execute function
print("after") #message from decorator

return nestedFunc #return all data

Example of how to use it: (not recommended)

def sayHello():
print("hello")

afterDecoration = myDecorator(sayHello)
afterDecoration()

Example of how to use it: (recommended)

@myDecorator
def sayHello():
print("hello")

sayHello()

Note: the @decorator is only for the next function, so it there is any function after that it will not
affect it

If you want to use practical speed test:

By/ Ahmed M. Naeim


- Firstly import datetime module
- In the wrapperfunction begin with
Start = time()
Func()
End = time()
- And print the function running time is end – start

Zip()
- Practical ➔ Looping on many Iterators with zip()
- zip() ➔ it is a built-in function➔ returns a zip object contains all objects
- zip() ➔ length is the length of the lowest object

example 1:

list1 = [1,2,3,5,4,59,6]
list2 = ["Ahmed", "Mohamed", "Naeim"]

ultimateList = zip(list1, list2)

for item in ultimateList:


print(item)

(1, 'Ahmed')
(2, 'Mohamed')
(3, 'Naeim')

example 2:

list1 = [1,2,3,5,4,59,6]
list2 = ["Ahmed", "Mohamed", "Naeim"]
for item1,item2 in zip(list1, list2):
print("This is item1",item1)
print("This is item2",item2)
This is item1 1

This is item2 Ahmed


This is item1 2
This is item2 Mohamed
This is item1 3
This is item2 Naeim

By/ Ahmed M. Naeim


Image Manipulation
- Pillow
- pip install Pillow
- from PIL import Image
- ctrl p -> reload window, to solve vs bug that it can’t recognize the module
- to open the image ➔

myImage = image.open(“path”)

- to show the image:

myImage.show()

- to crop image

myBox = (0,0,400,400) #left upper right lower

myNewImage = myImage.crop(myBox)

- To show the new image

myNewImage.show()

- To convert mode image

myConverted = myImage.convert(“L”)

myConverted.show()

• For more information ➔ pillow.readdocs.io

Doc string & commenting vs Documenting


- Documentation string for class, module or function
- Can be accessed from the help an doc attributes
- Made for understanding the functionality of the complex code
- There one line and multiple line doc string

Doc string (can be single line or multiple line) used ➔ triple single or double quote ‘’’ doc string
‘’’ or “”” doc string “”” (make it inside the function not before)

- It helps when print(funcName.__doc__)


- And help(funcName)

PyLint install
- Use in terminal
Pulint.exe filepath

By/ Ahmed M. Naeim


Python Exceptions
- Exception is a runtime error reporting mechanism
- Exception gives you the message to understand the problem
- Traceback gives you the line to look for the code in this line
- Exception have types (syntax error, index error, key error,..)
- Exception list from docs.python.org/3/library/exceptions
- Raise keyword used to raise your own exceptions

Error and Exceptions Raising:

Using: examples:

raise Exception(f”some text”)

or

raise ValueError(“some text”)

- NOTE: It stops the code

Exceptions Handling:

- try ➔ Test the code for errors


- except ➔ Handle the errors

Try and except are used together:

As:

try:
num = int(input("Enter a valid number: "))
except:
print("This is not an integer")

- else ➔ If no errors

can add else after except if there is no errors

- finally ➔ Run the code

finally always run the code whatever happens

Some Examples:

try:
'''some code to test'''
print(10/0)
except ZeroDivisionError:
print("Naeim says it is a zero division error")
except NameError:

By/ Ahmed M. Naeim


print("Naeim says it is a Name Error error")
except:
print("Naeim says that there is another error type here")

else:
print("Naeim says there is no error")

finally:
print("it will run whatever it happens")
Output:

Naeim says it is a zero division error

it will run whatever it happens

try:
'''some code to test'''
print(x)
except ZeroDivisionError:
print("Naeim says it is a zero division error")
except NameError:
print("Naeim says it is a Name Error")
except:
print("Naeim says that there is another error type here")

else:
print("Naeim says there is no error")

finally:
print("it will run whatever it happens")
Output:

Naeim says it is a Name Error

it will run whatever it happens

try:
'''some code to test'''
print(int("Naeim"))
except ZeroDivisionError:
print("Naeim says it is a zero division error")
except NameError:
print("Naeim says it is a Name Error")
except:
print("Naeim says that there is another error type here")

else:
print("Naeim says there is no error")

By/ Ahmed M. Naeim


finally:
print("it will run whatever it happens")
Output:

Naeim says that there is another error type here

it will run whatever it happens

try:
'''some code to test'''
print("Naeim")
except ZeroDivisionError:
print("Naeim says it is a zero division error")
except NameError:
print("Naeim says it is a Name Error")
except:
print("Naeim says that there is another error type here")

else:
print("Naeim says there is no error")

finally:
print("it will run whatever it happens")
Output:

Naeim says there is no error

it will run whatever it happens

Advanced Example:

myFile = None
tries = 3

while tries > 0:


try:
print("please enter the file name and path like
this\nD:/folder1/folder2/fileName.extention")
myFile_and_path = input("Enter the file path and name please : ")
myFile = open(myFile_and_path,"r")
print(myFile.read())
break

except FileNotFoundError:
tries -=1
print(f"Please enter a valid file name and path\n {tries} tries
left")

By/ Ahmed M. Naeim


finally:
if myFile is not None:
myFile.close()

Type Hinting
- It used as a hint to the function parameters in the function implementation to make a
non-error causing hint only to the function parameter data type
Def myFunc(num1,num2) ->int:
#arguments

Regular Expressions (RegEx)


- Sequence of characters that defines a search pattern
- Regular expression is not a PYTHON, it is General Concept
- Used in (Credit Card Validation, IP Address Validation, Email Validation)
- Test RegEx online https://pythex.org/
- Characters sheet: https://www.debuggex.com/chearsheet/regex/python
- Regex101.com as a website to test the regex
- A RegEx, or Regular Expression, is a sequence of characters that forms a search pattern.
- RegEx can be used to check if a string contains the specified search pattern.

Quantifiers:
* 0 or more (append ? for non-greedy)
+ 1 or more (append ? for non-greedy)
? 0 or 1 (append ? for non-greedy)
{m} exactly mm occurrences
{m, from m to n. m defaults to 0, n to infinity
n}
{m, from m to n, as few as possible
n}?
Character Classes (Special Sequences):

Character Description Example

\A Returns a match if the specified characters are at the "\AThe"


beginning of the string

By/ Ahmed M. Naeim


\b Returns a match where the specified characters are at the r"\bain"
beginning or at the end of a word
(the "r" in the beginning is making sure that the string is r"ain\b"
being treated as a "raw string")

\B Returns a match where the specified characters are present, r"\Bain"


but NOT at the beginning (or at the end) of a word
(the "r" in the beginning is making sure that the string is r"ain\B"
being treated as a "raw string")

\d Returns a match where the string contains digits (numbers "\d"


from 0-9)

\D Returns a match where the string DOES NOT contain digits "\D"

\s Returns a match where the string contains a white space "\s"


character

\S Returns a match where the string DOES NOT contain a white "\S"
space character

\w Returns a match where the string contains any word "\w"


characters (characters from a to Z, digits from 0-9, and the
underscore _ character)

\W Returns a match where the string DOES NOT contain any "\W"
word characters

\Z Returns a match if the specified characters are at the end of "Spain\Z"


the string

By/ Ahmed M. Naeim


Set Description
[arn] Returns a match where one of the specified
characters (a, r, or n) is present

[a-n] Returns a match for any lower case character,


alphabetically between a and n

[^arn] Returns a match for any character EXCEPT a, r, and n

[0123] Returns a match where any of the specified digits (0,


1, 2, or 3) are present

[0-9] Returns a match for any digit between 0 and 9

[0-5][0-9] Returns a match for any two-digit numbers from 00


and 59
[a-zA-Z] Returns a match for any character alphabetically
between a and z, lower case OR upper case

[+] In sets, +, *, ., |, (), $,{} has no special meaning, so [+]


means: return a match for any + character in the
string

re Module in Python
- re is a built-in module python
- 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]","AhmedNaeim")

print(my_search)
print(my_search.span())
print(my_search.string)
print(my_search.group())
Output:

By/ Ahmed M. Naeim


<re.Match object; span=(0, 1), match='A'>

(0, 1)

AhmedNaeim

RegEx Functions

The re module offers a set of functions that allows us to search a string for a match:

Function Description
findall Returns a list containing all matches
search Returns a Match object if there is a match
anywhere in the string
split Returns a list where the string has been split
at each match
sub Replaces one or many matches with a string

re Module Split and Sub:

- split(pattern, string, max split) ➔returns a list of elements splited on each match
- sub(pattern,replace,string,ReplaceCount) ➔ replace matches with what you want

Group and Flags:

- .span() returns a tuple containing the start-, and end positions of the match.
- .string returns the string passed into the function
- .group() returns the part of the string where there was a match

Flags: are put in the end of re.search(pattern,something,re.flag)

- IGNORECASE
- MULTILINE
- DOTALL
- VERBOSE

import re

my_web =
"https://www.youtube.com/watch?v=MLb7pPOEJlg&list=PLDoPjvoNmBAyE_gei5d18qk
fIe-Z8mocs&index=102"
search = re.search(r"(https?)://(www)?\.?(\w+)\.(\w+):?(\d+)?/?(.+)",
my_web)

print(f"Protocol: {search.group(1)}")
print(f"Sub Domain: {search.group(2)}")
print(f"Domain Name : {search.group(3)}")

By/ Ahmed M. Naeim


print(f"Top Level Domain: {search.group(4)}")
print(f"Port: {search.group(5)}")
print(f"Query String: {search.group(6)}")

Protocol: https

Sub Domain: www

Top Level Domain: com

Port: None

Query String: watch?v=MLb7pPOEJlg&list=PLDoPjvoNmBAyE_gei5d18qkfIe-Z8mocs&index=102

By/ Ahmed M. Naeim

You might also like