🎁GET 20% OFF Using Code 👉SCHOOL👈 Until End 2024🎁

Certificate

CERTIFICATE OF COMPLETIONThis is presented to:Edward OjamboOnline: Learning PYTHONDate: 2024-06-22Edward OjamboAuthorOjamboShop.com

References

Supported versions https://devguide.python.org/versions

Language Reference https://docs.python.org/3/reference

Exceptions https://docs.python.org/3/tutorial/errors.html

Basic Use Of Exceptions

Exceptions can be thrown and caught. Surround code in a try block. If an exception is thrown and its current function scope has no catch block, the exception will “bubble up” the call stack to the calling function until it finds a matching catch block. All finally blocks it encounters along the way will be executed.

Try

Sample Codetry:
	print(x)
except:
	print(“An exception Occured Because X Is Undefined”)
def divide(x, y):
    try:
        result = x // y
        print(“Answer is :”, result)
    except ZeroDivisionError:
        print(“Cannot divide by zero!”)
divide(3, 2)
divide(3, 0)

Finally

Sample Codedef divide(x, y):
    try:
        result = x // y
    except ZeroDivisionError:
        print(“Cannot divide by zero!”)
    else:
        print(“Answer is :”, result)
    finally:
        print(‘Always executed’)
divide(3, 2)
divide(3, 0)
# Type Some Code

Chapter 10: Exceptions

During the execution of a program, it may be required to process special conditions called exceptions. An exception breaks the normal execution flow and executes a specified exception handler.

An exceptional event could occur from an error and the Python will try to find a matching exception block. Python uses try with at least one corresponding catch or finally block. An exception can be thrown or caught.

Table : Exceptions

FunctionDescriptionExample
tryExecutes only if exception triggerstry: print(x) except: print(“Undefined”)
exceptBlock that handles errortry: print(x) except: print(“Undefined”)
elseBlock that is executed when no errortry: print(“Hello”) except: print(“Something went wrong”) else: print(“Nothing went wrong”)
finallyExceutes code regardless of try except block resulttry: print(x) except: print(“Something went wrong”) finally: print(“The ‘try except’ is finished”)

Chapter 9: Modules

Python has a way to put definitions in a file and use them in a script or in an interactive instance of the interpreter. The file is called a module and definitions from a module can be imported into other modules or into the main module.

Therefore the main module is a collection of variables that be accessed in a script executed at the top level. The file name is the module name with the suffix .py appended. Within a module, the module’s name as a string is available as the value of the global variable __name__.

Create Module

Sample Codedef greeting(name)
	print(“Hello, ” + name)
personx = {
	“name”: “John”,
	“age”: 24
}
# Save the code snippet above in a file named mymodule.py

Use Module

Sample Codeimport mymodule
mymodule.greeting(“John”)
# Alternative Method To Import
from mymodule import personx
print(personx[“age”])

Python has several built-in modules that can be imported.

The date is Python is not a data type and can be imported from the datetime module.

Date

Sample Codeimport datetime
timestamp = datetime.datetime.now()
print(timestamp)

Date Objects

	
Sample Codethe_date = datetime.datetime(2024, 9, 2)print("Labor Day 2024 is " + str(the_date)) # Cast Datetime To String

The Python Math module extends the list of mathematical functions.

Math

Sample Codeimport math
num1 – math.pi # PI constants
print(num1)
num2 = math.sqrt(9) # Square Root Of A Number
print(num2)
num3 = math.ceil(11.4) # Rounds A Number Up To Nearest Integer
print(num3)
num4 = math.floor(11.6) # Rounds A Number Down To Nearest Integer
print(num4)

JSON or JavaScript Object Notation is a text format that is a syntax for storing and exchanging data. The Python JSON module allows JSON data to be converted into a dictionary or vice versa.

JSON

Sample Codejson_text = ‘{“name:”John”, “age”:24}’
json_dict = json.loads(json_text) # Parse JSON Text
print(json.dict[“name”])
print(json.dict[“age”])
person_dict = {
	“name”: “John”,
	“age”: 24,
	“retired”: False
}
person_json = json.dumps(person) # Convert Into Json
print(person_json)
# Type Some Code

Class Declaration

An object is created by an executed constructor function of the class. The class defines how objects behave, providing initial values as member variables and implementations of behavior via member functions. Use public and private modifiers to define if functions can be used outside the object.

Class

Sample Codeclass SimpleClass:
	name = “John”
s1 = SimpleClass()
print(s1.name)
class Person:
	def __init__(self, name, age):
		self.name = name
		self.age = age
p1 = Person(“John”, 24)
print(p1.name)
print(p1.age)
class Greeting:
	def __init__(self, name, age):
		self.name = name
		self.age = age
	def greet(self):
		print(“Hello, my name is ” + self.name)
g1 = Greeting(“John, 24)
g1.greet()
g1.age = 34
print(g1.age)
del g1.age
del g1

Table : Common Functions To Manipulate Objects

FunctionDescriptionExample
delDelete object propertiesdel obj
selfParameter to reference the current instancedef myfunction(self):
__str__()Function returned when class is represented as string
__init__()Function automatically called when class is used to create new object
# Type Some Code

Chapter 8: Objects

An object is a compound data type. Values of more than one type can be stored together in a single variable. An object is an instance of either a built-in or user defined class. An object is initialized by creating a new statement to instantiate a class.

Multiple objects can be created from a class. Each object has all the properties and methods defined in a class but will have different property values.

Function Declaration

A function is a unit of code that represents a sequence of statements. Functions can accept arguments or values and return a single value (or not). In Python, a function is defined using the def keyword.

Function

Sample Codedef my_function():
	print(“Hello from my function”)
my_function() # Execute the function
def my_name_function(first_name):
	combined = f”My first name is {first_name}”
	return combined
greeting = my_name_function(“John”)
print(greeting)
# Type Some Code

Chapter 7: Functions

A function is a subprogram that can be called by code externally or internally to the function. It is composed of a sequence of statements called the function body. Values can be passed to a function as parameters or arguments and the function can return a value if applicable.

Python comes with built-in functions that can be called directly to perform a specific task. It is also possible to create custom functions also called user defined functions.

A function is therefore a block of statements that can be used repeatedly in a program. It will not execute automatically and must be executed by a call to the function.

While Loop

While loop executes a set of statements as long as a condition is true. It requires relevant variables to be ready such as an indexing variable to iterate through a loop.

While Loop

Sample Codecounter = 0
while counter < 10:
	counter += 1
	print(counter)
# Type Some Code