reviewer :3
PPT SUMMARY:
CHAPTER 1 - CC3 PYTHON PROGRAMMING
Reference:
Chapter-1-Part-1_JMAD.pptx
Chapter-1-Part2_JMAD.pptx
- HISTORY:
● Python Programming Language History:
> Conceived in the late 1980s.
> Implementation started in December 1989.
- Creator: Guido van Rossum.
> Developed at the Centre for Mathematics and Computer Science (CWI)
in the Netherlands.
>Designed as a successor to the ABC programming language.
>Features included exception handling and interfacing with the Amoeba
operating system.
- Guido van Rossum's role:
> Principal author of Python.
>Continues to play a central role in deciding the direction of Python.
>Title in the Python community: “Benevolent Dictator For Life” (BDFL).
>Oversees Python development and retains the final say in community
disputes or arguments.
- THRUST AREAS OF PYTHON
- PYTHON'S MARKETABILITY:
> Known for its simplicity and developer friendliness.
> Considered one of the fastest-growing major programming languages.
> Consistently ranked in the top ten most popular programming languages
since 2003 (TIOBE Programming Community Index).
- As of April 2018, Python ranked fourth in the TIOBE Index.
- PYTHON'S RANKINGS:
>Ranked first by IEEE Spectrum for top programming languages in 2017.
>Ranked third by RedMonk Programming Language Rankings in 2018.
- Python in Academia:
> Offered as the introductory programming language in the majority of
computer science departments at various American universities.
> Adopted by academia for research purposes at an accelerated rate.
- Python vs. Matlab:
Competing with Matlab for the title of most preferred language for research.
> Advantages of Python over Matlab:
Matlab is not considered a real programming language, while Python is.
Python has numerous scientific tools that are almost as good as Matlab
modules.
- SCIENTIFIC TOOLS
Essential for simulating and analyzing complex systems.
> Core scientific packages in the Python ecosystem:
+ SciPy library:
Used for numerical integration and optimization.
+ NumPy:
Provides N-dimensional array objects.
Performs linear algebra, Fourier transform, and other mathematical
operations.
+ Jupyter:
Revolutionized the way programming is done in Python.
+ SymPy
+ Matplotlib
Licensing:
Most of these tools are available under the Berkeley
- MACHINE LEARNING
> Effective and adaptive tool to learn from experience and by a dataset.
> Originates from Computer Science and Statistics.
> Various algorithms and techniques developed for machines to learn.
+ Scikit-Learn:
> Well-known Machine Learning tool built on top of other Python scientific
tools like NumPy, SciPy, and Matplotlib.
> Easily extended to implement new models.
> Supports various models for: Classification. Regression. Clustering.
Model Selection. Dimensionality Reduction. Preprocessing.
+ Advantages:
● Integration of parallelization.
● Consistent APIs.
● Good documentation.
● Available under BSD license and also offers a commercial
license with full support.
- NATURAL LANGUAGE
> Natural Language Processing (NLP):
Used to read and understand text.
+ Natural Language Toolkit (NLTK):
> Popular library for NLP in Python.
> Contains numerous trained algorithms to understand text.
+ Includes a large corpora of datasets and lexical resources such as:
- Journals
- Chat logs
- Movie reviews
- Many more
Licensing:
NLTK is available under Apache License V2.0.
- DATA ANALYSIS
+ Pandas Library:
> Transformed data analysis in Python. Available under BSD license.
> Built on top of NumPy.
+ Data Structures:
+ Series:
Holds any type of data: integers, floats, strings, objects, etc.
Each piece of data is labeled by the index.
+ DataFrame:
> Tabular data structure with labeled rows and columns (similar to Excel
spreadsheet).
> Useful for handling real-world data, including missing data and reshaping
datasets.
- Features and Functions:
Filling in missing data. Reshaping datasets. Slicing and indexing. Merging
and joining datasets.
+ File Formats:
Can read and handle various file formats:
● Comma-Separated Values (CSV) files.
● Microsoft Excel files.
● Structured Query Language (SQL) database.
● Hierarchical Data Format (HDF5) files.
- STATISTICS
+ Statsmodels library:
● Used for statistical analysis in Python.
● Supports various models and features:
● Linear regression models
● Generalized linear models
● Discrete choice models
● Functions for time series analysis
+ Accuracy:
> Thoroughly tested by comparing results with other statistical packages.
Integration:
> Can be used with Pandas to fit statistical models.
Licensing:
Available under the modified BSD license.
+ Application Fields:
Widely used in economics, finance, and engineering.
- HYPER-TEXT TRANSFER PROTOCOL (HTTP) LIBRARY
+ Requests HTTP library:
> Known as the library written for humans.
> Created to overcome the verbosity of Python's standard HTTP library
[Link].
+ HTTP Operations:
> Supports common HTTP verbs:
● POST: Create operation
● GET: Read operation
● PUT: Update operation
● DELETE: Delete operation
+ Features:
- Thread-safety
- Support for International Domains
- Cookie Persistence
- Connection Timeouts
- DATABASE CONNECTORS
Database connectors are drivers that allow querying the database directly
from the programming language.
+ Popular open-source databases:
● MySQL
● PostgreSQL
+ Python connector:
MySQL-Python-Connector from Oracle is the most popular for Python.
- OBJECT RELATIONAL MAPPING
a technique used in creating a "bridge" between object-oriented programs
and, in most cases, relational databases.
Put another way, you can see the ORM as the layer that connects object
oriented programming (OOP) to relational databases.
- WEB FRAMEWORK
> Web Frameworks:
Two of the most popular web frameworks are Django and Flask.
+ Django:
● Full-fledged web framework.
● Built-in support for various web-related services:
● Caching
● Internationalization
● Serialization
● ORM support
● Automatic admin interface
+ Flask:
● Microframework.
● Used to build small applications with minimal requirements.
● Allows users to configure web services by installing external
libraries.
● Both Django and Flask are available under BSD-derived
licenses.
- CLOUD COMPUTING
+ OpenStack:
● Entirely written in Python.
● Used to create scalable private and public clouds.
● Development overseen by the OpenStack Foundation.
● OpenStack Features:
● Decent load balancing.
● Highly reliable.
● Vendor independent.
● Built-in security.
● Uses a dashboard to manage network resources, processing
power, and storage in a data center.
+ Linux Distributions:
> Fedora and Ubuntu include OpenStack as part of their package.
+ Cloud Service Providers:
- Support hosting of Python applications on platforms like:
● Google App Engine
● Amazon Web Services (AWS)
● Heroku
● Microsoft Azure
- GAME DEVELOPMENT
> Python enhances game development efficiency with its simplicity and
rapid prototyping capabilities.
> Leveraging libraries like Pygame, it accelerates coding tasks, especially
in game mechanics and UI development. Its strength in automation and
scripting streamlines repetitive processes, boosting productivity.
- WHY PYTHON
● Multiplatform Support(Windows, Mac, Linux, Raspberry Pi, etc).
● Simple syntax similar to the English language.
● Syntax that allows developers to write programs with fewer
lines
● Runs on an interpreter system,
○ Code can be executed as soon as it is written. This
means that prototyping can be very quick.
● Python can be treated in a procedural way, an object-oriented
way or a functional way.
- PYTHON SYNTAX
Python’s Syntax is designed for readability. It is similar enough to the
English language with influence from mathematics.
It uses new lines to complete a command, unlike other programming
languages which use semicolons or parentheses.
It accomplishes this by relying on indentation, using whitespace, to define
scope; such as the scope of loops, functions and classes.
Other programming languages often use curly-brackets for this purpose.
- PYTHON INTERPRETER
NOTE: just to help, i will try to explain them in a short term so its easier to
read, u prob know more about this but i will just try to help a little, i hope u
don’t mind (and to also have like something u can remember)
Python is an interpreted language, which means the source code of a is
converted into bytecode that is then executed by the Python virtual
machine.
Python is different from major compiled languages, such as C and C + +,
as its code is not required to be built and linked like code for these
languages.
EXP: Python is a bytecode interpreter. It converts your code into bytecode,
8 bit binary values, into a virtual machine connected to the library in order
to run. This makes it easier to program in comparison to using compilers.
● A compiler translates code written in a high-level programming
language into a lower-level language like assembly language, object
code and machine code.
EXP : It takes code and translates it into language that a
computer can understand i.e assembly code (code that is in
hexadecimal or binary 1 and 0s that explains the operations
and functions of a computer)
● It converts the code ahead of time before the program runs. An
interpreter translates the code line-by-line when the program is
running.
EXP: An interpreted language means that the code is separate,
line by line, as it is being executed. Compared to a Compiled
language which directly takes all of the code and translates it to
assembly.
- INDENTATION
Python uses indentation, whitespace to determine the scope of statements
that usually starts at the beginning of the code, making the code easier to
program in and read.
Where in other programming languages the indentation in code is for
readability only, the indentation in Python is very important.
- RULES OF INDENTATION
● Default indentation is 4 spaces, the number is up to the user but you
need at least 1 to indicate a statement.
● You can’t indent on the first line of code.
● A block of code must have consistent spacing
● Whitespaces are preferred over tabs. Mixing tabs and whitespaces
can result in indentation errors.
- COMMENTS
in Python is the inclusion of short descriptions along with the code to
increase its readability.
A developer uses them to write his or her thought process while writing the
code. It explains the basic logic behind why a particular line of code was
written.
They are just meant for the coders themselves or other developers to
understand a piece of code, especially since the Python interpreter
completely ignores comments in Python.
- COMMENTS ARE USUALLY INDICATED WITH # -
- EX: #This is a comment.
- VARIABLES
Python variables are simply containers for storing data values.
Unlike other languages, such as Java, Python has no command for
declaring a variable, so you create one the moment you first assign a value
to it.
● Variables in programming are similar to variables in algebra
● Variables allow you to write programs that process information
without having all the values up front.
● Unlike algebraic variables, however, programming variables can
represent a much wider variety of information.
● Variables do not need to be declared with any particular type, and
can even change type after they have been set.
Example:
number = 5
name= “Mary"
- STRING
String is a text data type.
> Python has powerful and flexible built-in string (str) processing
capabilities.
> The value of a str object is a sequence of characters.
> You can delimit string values with either single quotes (' ') or double
quotes (" "). All the characters between the opening and closing delimiter
are part of the string
> Strings are also index based.
+ INDEXING (Accessing Characters In Python)
> In Python, individual characters of a String can be accessed by using the
method of Indexing.
> Indexing allows negative address references to access characters from
the back of the String, e.g. -1 refers to the last character, -2 refers to the
second last character and so on.
> While accessing an index out of the range will cause an IndexError. Only
Integers are allowed to be passed as an index, float or other types will
cause a TypeError.
EXAMPLE 1: Using Index
EXAMPLE 2: USING RANGES
+ CONCANTENATING STRINGS
> Concatenation means combining two things together. Once you
assign string values to the new variables, you can join them
- NUMERIC TYPE VARIABLES
Integers (int) and floats (float) are numeric types, which means they hold
numbers. You can perform mathematical operations with them.
Integers are values that are whole numbers (0, 1, 2, 3…) while floating
point numbers are numbers that contain decimal values (0.1, 1.1. 1.12…)
The Python interpreter can then evaluate these expressions to produce
numeric values.
The code (type()) is used to return the type of variable the value is in.
+ FOR CONCANTENATING NUMERICALS
- PYTHON BOOLEANS
Most objects in Python have a characteristic of True or False.
Python also provides a boolean data type. Objects of this data type may
have one of two values: True or False.
The most common (and simplest) example of Booleans is a filter where all
the records that meet a condition (True) are returned, like when using
Microsoft Excel and you filter for a specific value in a field.
EXP: I’m confused here cause there isn’t an explanation for Boolean
Logic so I’ll give an explanation and I don’t know if this might come
up but I will just add extra information, you can skip this if you
want :3
Boolean Logic or Boolean Operators are operations that check whether two
statements are true or false. They check for two values and output a certain
value once the condition is met. This is used mostly in computer logic and
binary.
These Boolean Operators are:
For these examples, I’ll use 1 for True and 0 for False.
NOT = If statement is 0, output 1
OR = If the first or second statement is 1, output 1
NOR = If the first or second statement is 0, output 1
AND = If both the first and second statement is 1, output 1
NAND = If both the first and second statement is 1, output 1
XOR = If the first and second statements are 1, output 1. However, if both
are on, output a 0.
XNOR = If the first and second statements are 1, output 0. However, if both
are on, output a 1.
- ALL THE DATA TYPES:
- TYPE CASTING
There may be times when you want to specify a type on a variable. This
can be done with casting.
Python is an object-orientated language, and as such it uses classes to
define data types, including its primitive types.
+ Casting in python is therefore done using constructor functions:
● int() - constructs an integer number from an integer literal, a float
literal (by removing all decimals), or a string literal (providing the
string represents a whole number)
● float() - constructs a float number from an integer literal, a float literal
or a string literal (providing the string represents a float or an integer)
● str() - constructs a string from a wide variety of data types, including
strings, integer literals and float literals
- OUTPUT AND INPUT FUNCTIONS
+ INPUT
Python allows for user input.
That means we are able to ask the user for input.
name = input(“Enter Full Name: ”)
email = input(“Enter Email: ”)
print(“Name: ” + name)
print(“Email: ” + email)
+ OUTPUT
print() function
The print() function prints the specified message to the screen, or other
standard output device. It can be a string or any object.
- OPERATORS
ARITHMETIC OPERATIONS: FUNCTION
Basic mathematical operations.
+ Addition
- Subtraction
* Multiplacation
/ Division
% Modulo (Retrieves the remainder in
division)
** Exponential
// Floor Division (Divides with no
fractions i.e outputs integer)
ASSIGNMENT OPERATORS: FUNCTION
Used to assign values to variables
= Assigns value to variable
(x = 5)
+= Adds assigned value to number
(x+=5 is the same as x = x + 5)
-= Subtracts assigned value to number
(x-=5 is the same as x = x - 5)
*= Multiplies assigned value to number
(x*=5 is the same as x = x * 5)
/= Divides assigned value to number
(x/=5 is the same as x = x / 5)
%= Retrieves the remainder of the
assigned value divided by the
number
(x%=5 is the same as x = x % 5)
//= Divides assigned value to the
number without fractions or
remainder
(x+=5 is the same as x = x // 5)
**= Raises the power of the assigned
value to the exponential value which
is the number
(x+=5 is the same as x = x + 5)
&= Bitwise AND
Checks if assigned value AND
number are true (equal to 1)
(x+=5 is the same as x = x + 5)
|= Bitwise OR
Checks if assigned value and
number are true (equal to 1)
(x+=5 is the same as x = x + 5)
^= Bitwise XOR
Checks if assigned value OR
number are ONLY true (equal to 1)
(x+=5 is the same as x = x + 5)
>>= Checks if assigned value is greater
than number
(x+=5 is the same as x = x + 5)
<<= Checks if assigned value is lesser
than number
(x+=5 is the same as x = x + 5)
CONDITIONAL OPERATORS: FUNCTIONS
Comparison between two values
== Equal
!= Not Equal
> Greater Than
< Lesser Than
>= Greater or Equal Than
<= Lesser Or Equal Than
LOGICAL OPERATORS: FUNCTIONS
Conditional Statements
and If both statements are true, output a
true
or If either statements are true, output
a true
not If a statement is true, output a false
- STRING PLACEHOLDER
> Container For Strings
> There are two types of placeholders, one is {} and second is %.
> {} is for format while % is used for numbers
These are examples for string placeholder “{}”
EXAMPLE 1
EXAMPLE 2
EXAMPLE 3
- STRINGPLACE HOLDER %
This is a string that has placeholders (%d, %s, %.2f) where actual values
will be inserted.
• %d: A placeholder for an integer (e.g., 55 for quantity).
• %s: A placeholder for a string (e.g., "milk" for the item name).
• %.2f: A placeholder for a floating-point number (a number with
decimals) formatted to 2 decimal places (e.g., 335.50 for the cost).
- STRING FORMATTING
● [Link]() - Converts a string into upper case
● [Link]() - Converts a string into lower case
● str. capitalize() - Converts the first character to uppercase
● [Link]() - Converts the first character of each word to uppercase
● split() - Splits the string at the specified separator, and returns a list
● replace()-Returns a string where a specified value is replaced with a
specified value
● len() - count characters in a string
● count() - Returns the number of times a specified value occurs in a
string
- NUMBER FORMATTING FUNCTIONS
Number data types store numeric values.
They are immutable data types, which means that changing the value of a
number data type results in a newly allocated object.
Number formatting functions:
● round() - Rounds to nearest whole/decimal place
● ceil() - Rounds up to nearest whole number
● floor() - Round numbers down to the nearest integer
● pow() - returns the value of x to the power of y (xy).Raises a number
to a power. If a third parameter is present, it returns x to the power of
y, modulus z. Return the value of 4 to the power of 3 (same as 4 * 4 *
4)
- CONTROL STRUCTURES IN PYTHON
Most programs don't operate by carrying out a straightforward sequence of
statements. A code is written to allow making choices and several
pathways through the program to be followed depending on shifts in
variable values.
All programming languages contain a pre-included set of control structures
that enable these control flows to execute, which makes it conceivable.
- TYPES OF CONTROL STRUCTURES:
+ Sequential -
The default working of a program
> Sequential statements are a set of statements whose execution process
happens in a sequence.
> The problem with sequential statements is that if the logic has broken in
any one of the lines, then the complete source code execution will break.
+ Selection
This structure is used for making decisions by checking conditions and
branching
> The statements used in selection control structures are also referred to
as branching statements or, as their fundamental role is to make decisions,
decision control statements.
> A program can test many conditions using these selection statements,
and depending on whether the given condition is true or not, it can execute
different code blocks.
- There can be many forms of decision control structures.
Here are some most commonly used control structures:
● Only if
● if-else
● The nested if
● The complete if-elif-else
+ Iteration/ Repetition -
This structure is used for looping, i.e., repeatedly executing a certain piece
of a code block.
To repeat a certain set of statements, we use the repetition structure.
There are generally two loop statements to implement the repetition
structure:
● for loop
● while loop
CHAPTER 2 - CC3 PYTHON PROGRAMMING
Reference: Chapter-2_JMAD.pptx
- SELECTION
(FOR DEFINITION, CHECK CHAPTER 1 “CONTROL STRUCTURES)
A Selection Structure provides a choice between two alternatives.
It has three components
A condition to be tested
- The statement to be performed if the condition is satisfied (process A)
- The statement to be performed if the condition is not satisfied
(process B)
Entry to the structure is through the condition
Exit is through the execution of process A or process B
EXAMPLE CODES:
For Selection
Dual Alternative Selection
Multiple True Selection
Nested If Statements
- COMPOUND CONDITIONS:
> Have more than 1 conditional expression
> The result of the compound expression depends on the individual
result of each condition
Format:
(condition-1) and (condition-2)
(condition-1) or (condition-2)
- BUILT IN METHODS
● isupper() - Returns True if all characters in the string are upper case
● islower() - Returns True if all characters in the string are lower case
● isdigit() - Returns True if all characters in the string are digits
● isalpha() - Returns True if all characters in the string are in the
alphabet
CHAPTER 3 - CCS
REFERENCE: Chapter-3_JMAD.pptx
- ITERATION:
(FOR DEFINITION, CHECK CHAPTER 1 “CONTROL STRUCTURES)
> Most useful and powerful structure
> Allows the repetition of instructions or statements in the loop body
- UNDERSTANDING ITERATION IN PYTHON
> When writing computer programs, you often need to repeat a given piece
of code multiple times.
> To do this, you can follow one of the following approaches:
1. Repeating the target code as many times as you need in a sequence
2. Putting the target code in a loop that runs as many times as you
need
The first approach has a few drawbacks. The most troublesome issue is
the repetitive code itself, which is hard to maintain and not scalable.
Using a loop will be a much better way to solve the problem and avoid the
maintainability issue. Loops allow you to run a piece of code as often as
you need.
Parts of the iteration structure
● Loop body instruction(s) or statements which are repeated
● Loop-exit condition the condition to be tested before each repetition
TYPES OF LOOPS
● while loop
● for loop
● In
● Range
- WHEN TO USE WHILE AND FOR LOOP?
> Loops that are dependent on a sentinel value (or indicator) are better
coded using a while loop
> The for loop is generally used for traversing and manipulating arrays.
When the number of times that the loop will be executed is known, the for
loop provides a convenient shorthand.
- COMMON LOOP APPLICATIONS
● Using a loop to accumulate totals
● An accumulator is a variable that “sums up” or accumulates values
● It is similar to a counter whose values change each time the loop is
entered.
● Counters, however, add a fixed value while accumulators
accumulate undetermined values.
● Using a loop to validate user entry
● Data entered by a user usually needs validation. It needs to be
checked for errors.
● Incorrect data can lead to unwanted results and could end a program
abnormally
● Usual checks for data are:
○ If it is the correct data type
○ For numeric data, if it is within an acceptable range of values
- WHILE LOOP
> The statements inside the while loop are executed as long as the
condition remains true
The while loop evaluates the condition:
If the condition is true, the body of the while loop is executed. The condition
is evaluated again.
This process continues until the condition is False.
Once the condition evaluates to False, the loop terminates.
- SENTINEL VALUE
> It is a special type of value that allows a different number of inputs by the
user each time.
> A special value that isn’t a part of the input to be processed.
> It allows a different number of inputs each time.
It takes some value as an endpoint. When the endpoint is given by the
user. It will display the statement that the programmer gives.
For example, if I am setting a sentinel value as a -98 and saying goodbye!
It will take any value from the user and display the value. When the user
gives -98, it will display the statement goodbye!
- BREAK STATEMENT
Force immediate termination of a loop, bypassing the conditional
expression and any remaining code in the body of the loop.
>The loop is terminated and program control resumes at the next statement
following the loop
- FOR LOOP
For loops are used when you have a block of code which you want to
repeat a fixed number of times.
The for-loop is always used in combination with an iterable object, like a list
or a range.
The Python for statement iterates over the members of a sequence in
order, executing the block each time.
Contrast the for statement with the ''while'' loop, used when a condition
needs to be checked each iteration or to repeat a block of code forever.
> The for loop in Python is an iterating function.
> If you have a sequence object like a list, you can use the for loop to
iterate over the items contained within the list.
>The functionality of the for loop isn’t very different from what you see in
multiple other programming languages.
- ELSE IN FOR LOOP
> The else keyword in a for loop specifies a block of code to be executed
when the loop is finished:
- CONTINUE STATEMENT
> A continue statement causes control to be transferred directly to the
conditional expression that controls the loop.
>The continue statement in Python returns the control to the beginning of
the while loop.
> The continue statement rejects all the remaining statements in the current
iteration of the loop and moves the control back to the top of the loop.
> The continue statement can be used in both while and for loops.
- PASS STATEMENT
> The pass statement is a null operation; nothing happens when it
executes.
> The pass is also useful in places where your code will eventually go, but
has not been written yet
CHAPTER 4 - CCS
REFERENCE: Chapter-3_JMAD.pptx
- EXCEPTIONS
> Events or errors that disrupt the normal flow of execution of a program.
> It prevents the program from reaching a normal end.
These events or errors usually occur during runtime.
Example of exceptions:
● Division by zero
● Invalid input
● File not found
- KIND OF EXCEPTIONS
+ Checked Exception
● All exceptions, except for Runtime Exceptions, are checked
exceptions.
● Exceptions are “checked” because they are subject to the
Catch or Specify Requirement.
● Checked exceptions are checked by the compiler so they are
called compile time exceptions.
○ Otherwise, the program code will not compile.
● Checked exceptions are errors that the program can deal with.
+ Runtime Exception
- Like errors, Runtime Exceptions are not subject to the Catch or
Specify Requirement and are, also, unchecked exceptions.
- These exceptions are the result of programming flaws such as:
● dividing by zero,
● using null pointers or references,
● or going beyond an array’s/list boundaries.
- ERRORS
> Errors are generally beyond the control of the program.
> These are situations that cannot be anticipated and for which the
program cannot recover from.
Example:
● Unreadable file
● Hardware malfunction
● Syntax error
Errors are not subject to the Catch or Specify requirement and are often
referred to as unchecked exceptions.
+ TYPES OF ERRORS
1. SyntaxError: This exception is raised when the interpreter
encounters a syntax error in the code, such as a misspelled
keyword, a missing colon, or an unbalanced parenthesis.
2. TypeError: This exception is raised when an operation or
function is applied to an object of the wrong type, such as
adding a string to an integer.
3. NameError: This exception is raised when a variable or function
name is not found in the current scope.
4. IndexError: This exception is raised when an index is out of
range for a list, tuple, or other sequence types.
5. KeyError: This exception is raised when a key is not found in a
dictionary.
6. ValueError: This exception is raised when a function or method
is called with an invalid argument or input, such as trying to
convert a string to an integer when the string does not
represent a valid integer.
7. AttributeError: This exception is raised when an attribute or
method is not found on an object, such as trying to access a
non-existent attribute of a class instance.
8. IOError: This exception is raised when an I/O operation, such
as reading or writing a file, fails due to an input/output error.
9. ZeroDivisionError: This exception is raised when an attempt is
made to divide a number by zero.
10. ImportError: This exception is raised when an import
statement fails to find or load a module.
- TRY AND EXCEPT BLOCK
> The try and except block in Python is used to catch and handle
exceptions.
Python executes code following the try statement as a “normal” part of the
program. The code that follows the except statement is the program’s
response to any exceptions in the preceding try clause.
> The Except block will be executed if the try block raises an error.
- ELSE
You can use the else keyword to define a block of code to be executed if
no errors were raised.
- FINALLY
The finally block, if specified, will be executed regardless if the try block
raises an error or not.
- RAISE
Use to execute an exception depending on the condition
- ASSERT
> The assert keyword is used when debugging code.
> The assert keyword lets you test if a condition in your code returns True,
if not, the program will raise an AssertionError.
> You can write a message to be written if the code returns False.
In simpler terms, we can say that assertion is the boolean expression that
checks if the statement is True or False. If the statement is true then it does
nothing and continues the execution, but if the statement is False then it
stops the execution of the program and throws an error.
NOTE: Okay finished! Goodluck w ur midterms! I hope this helps! -e.g