Python Basics Notes by Ahmed Naeim
Python Basics Notes by Ahmed Naeim
Variables:
NOTES:
Concatenation:
Strings:
Is engineer “””
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())
- 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
- 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
- Format in V3.6+:
print(f“my name is {name} and my age is {age}”)
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
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:
Lists Methods:
C
['A', 'B', 'D']
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'>
- Hashing: it is a mechanism that help you to search quickly in the computer memory.
Set:
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:
user = {
“name”: “ahmed”,
“age”: 23,
“country”: “Egypt”
print(user.get(‘country’))
languages = {
“One” : {
“name”: “HTML”,
“progress”: “80%”
},
“Two” : {
“name”: “C”,
“progress”: “90%”
},
“Three” : {
“name”: “Python”,
“progress”: “40%”
},
Print(languages[‘One’])
Print(language[‘two’][‘name’])
Dict1 = {
“name”: “HTML”,
“progress”: “80%”
Dict2 = {
“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:
Dictionary Methods:
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:
Comparison Operators:
- == ➔ equal
- != ➔ not equal
- > ➔ greater than
- < ➔ less than
- >= ➔ greater than or equal
- <= ➔ less than or equal
Type Conversion:
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}”)
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:]}")
if Conditions:
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
- 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
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: )
- Note:
mylist =[]
mylist.append(f"https\\ {mylist}")
For LOOP:
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%',
People = {
'Ahmed': {
'HTML': '90%',
'CSS': '80%',
'JS': '70%',
'C': '60%',
},
'Mohamed': {
'C++': '50%',
'Python': '40%'
},
'Naeim': {
'HTML': '90%',
'C++': '50%',
'Python': '40%'
}
}
Ahmed:
HTML: 90%
CSS: 80%
JS: 70%
C: 60%
Mohamed:
C++: 50%
Python: 40%
Naeim:
HTML: 90%
Python: 40%
Advanced Loops:
myDict = {
'HTML': '90%',
'CSS': '80%',
'JS': '70%',
'C': '60%',
'C++': '50%',
'Python': '40%',
}
People = {
'Ahmed' : {
'HTML': '90%',
'CSS': '80%',
'JS': '70%',
'C': '60%',
},
'Naeim' : {
'HTML': '90%',
'C++': '50%',
'Python': '40%'
}
}
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"
}
}
Functions:
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()
say_hello("Ahmed")
a = "Naeim"
say_hello(a)
with 2 parameters:
- 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:
say_hello("Ahmed", "Mohamed","Naeim")
- 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:
say_hello("Ahmed", 23,"Egypt")
say_hello("Ahmed", 15)
- 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"])
Function Scope:
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
- 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
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:
x = lambda a : a + 10
print(x(5))
x = lambda a, b, c : a + b + c
print(x(5, 6, 2))
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.
- "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:
- 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.”
f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.close()
f = open("demofile3.txt", "w")
f.write("Woops! I have deleted the content!")
f.close()
- 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: اقتطاع
Tell:
- To know where the curser, returns the number of characters including new line
- Note: new line is counted as 2 characters in windows
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
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:
- 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)
Example:
Filter:
- 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:
def myFunc(x):
if x < 18:
return False
else:
return True
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:
(0, 'Ahmed')
(1, 'MOHAMED')
(2, 'naeim')
Example 2:
1- Ahmed
2- Mohamed
3- Naeim
Help:
Syntax:
help(functionName)
Example:
print(help(print))
Reversed:
Syntax:
reversed(sequence)
examples:
reversedNames = reversed(names)
reversedMyName = reversed(myName)
naeim
Modules
- What is a Module?
- Create a Module
To create a module just save the code you want in a file with the file extension .py
Example:
- 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")
The module can contain functions, as already described, but also variables of all types (arrays,
dictionaries, objects etc):
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
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 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
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
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?
Note: If you have Python version 3.4 or later, PIP is included by default.
Modules are Python code libraries you can include in your project.
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
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:
import camelcase
c = camelcase.CamelCase()
print(c.hump(txt))
- Find Packages
- Remove a Package
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 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.
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:
- 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
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
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:
Example
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:
Example
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:
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))
- 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
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)
Basically, a generator function is a function that contains a yield statement and returns a
generator object.
def squares(length):
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:
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:
Since the squares is a generator object, you can iterate over its elements like this:
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 [].
def sayHello():
print("hello")
afterDecoration = myDecorator(sayHello)
afterDecoration()
@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
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"]
(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
myImage = image.open(“path”)
myImage.show()
- to crop image
myNewImage = myImage.crop(myBox)
myNewImage.show()
myConverted = myImage.convert(“L”)
myConverted.show()
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)
PyLint install
- Use in terminal
Pulint.exe filepath
Using: examples:
or
Exceptions Handling:
As:
try:
num = int(input("Enter a valid number: "))
except:
print("This is not an integer")
- else ➔ If no errors
Some Examples:
try:
'''some code to test'''
print(10/0)
except ZeroDivisionError:
print("Naeim says it is a zero division error")
except NameError:
else:
print("Naeim says there is no error")
finally:
print("it will run whatever it happens")
Output:
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:
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")
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:
Advanced Example:
myFile = None
tries = 3
except FileNotFoundError:
tries -=1
print(f"Please enter a valid file name and path\n {tries} tries
left")
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
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):
\D Returns a match where the string DOES NOT contain digits "\D"
\S Returns a match where the string DOES NOT contain a white "\S"
space character
\W Returns a match where the string DOES NOT contain any "\W"
word characters
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
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:
(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
- 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
- .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
- 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)}")
Protocol: https
Port: None