0% found this document useful (0 votes)
310 views286 pages

Introduction to Python Programming

The document discusses Python, including what it is, its uses, advantages, and basic syntax and data types. Python is an interpreted, high-level programming language created by Guido van Rossum in 1991. It can be used for web development, software development, data science, and more due to its simple syntax and many libraries.

Uploaded by

supriya mandal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
310 views286 pages

Introduction to Python Programming

The document discusses Python, including what it is, its uses, advantages, and basic syntax and data types. Python is an interpreted, high-level programming language created by Guido van Rossum in 1991. It can be used for web development, software development, data science, and more due to its simple syntax and many libraries.

Uploaded by

supriya mandal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 286

PYTHON

AN INTRODUCTION TO PYTHON.
• What is python ?
• Python is an interpreted, high level, general purpose programming language.
• Created by Guido van Rossum and first released in 1991.
• Python is a programming language that lets you work quickly and integrate systems more
effectively.
• Python design philosophy emphasizes code readability with its notable usage of significant
whitespaces.
• It is used for,
• Web development
• Software development
• Mathematics
• System scritping
WHAT PYTHON CAN DO?
• Python is a general purpose and high level programming language
that you can use for developing desktop GUI applications, websites
and web applications.
• It can be used on a server to create web applications.
• It can be used alongside software to create workflows.
• Can connect to database systems and can also read and modify files.
• Handle big data and perform complex mathematics.
• For rapid prototyping or for production ready software development.
WHY PYTHON?
• Since 2012, Python has been consistently growing in popularity and
the trend is likely to continue if not increase in the future.
WHY PYTHON ?
• Python being a high level programming language allows you to focus more on core functionality
of the application by taking care of the common programming tasks.
• Below are some of the reason why python has become famous rapidly.
• Works on different platforms (Linux, Windows, MacOS, etc).
• Has a simple syntax which is similar to english like language.
• Has a syntax that allows developers to write programs with fewer lines of code than some other
programming languages.
• Runs on a interpreter system, meaning the code can be executed as soon as it is written.
• Can be treated in a procedural way, and object oriented way and also as a functional way. 
WHY PYTHON ?
• There's a python library for everything,
• Data visualization
• Machine learning
• Data science
• Natural language processing
• Complex data analysis.
• There is a variety of framework to choose from,
• Django
• Flask
• Pyramid
• Twisted
• Falcon
GOOD TO KNOW.
• The most recent major version on python is python 3, which we shall
be seeing in this tutorial.
• However, python 2, although not being updated with anything other
than security updated is still quite popular among the developers
PYTHON SYNTAX COMPARED TO
OTHER PROGRAMMIN LANGUAGES.
• Python was designed for readability and has similarities to english
language.
• Python used new lines to complete a command whereas other
programming languages use semicolons or parentheses.
• Python heavily relies on indentation which is using whitespaces to
define scopes such as scope for loops, functions and classes.
• Other programming languages often use curly braces for this purpose.
PYTHON INSTALLATION.
• To install python on linux machine, use the below command.
• yum install python -y
• python --version
• To install python on windows machine, use below link.
• https://www.python.org/downloads/
• Then you can open “cmd” or “powershell” and type python --version to verify
python installation.
RUNNING PYTHON CODE.
• There are several ways to run the python code on different
development environment.
• There are 3 types of environments.
• Text editors.
• Full IDEs.
• Notebook environments.
TEXT EDITORS.
• General text editors for any text file.
• Works with a variety of text files.
• Can be customised with plugins and add-ons.
• Most popular text editors are sublime text, atom, etc.
FULL IDEs.
• Development environments designed specifically for python.
• Larger programs.
• Only community editions are free.
• Desgined specifically for python with lots of extra functionality.
• Most popular IDEs are Pycharm and Spyder.
NOTEBOOK ENVIRONMENTS.
• Great for learning.
• See input and output next to each other.
• Support in-line markdown notes, visualizations, videos and more.
• Special file formats that are not .py.
• Most popular is jupyter notebook.
• Development environments are a personal choice highly dependent
on the personal preference.
SIMPLE PROGRAM EXAMPLE.
• Lets look at a simple example for python program.
• print ("Hello world")
• Simple example using text editors.
• Simple example using python IDEs.
• Simple example using jupyter notebook.
PYTHON BASICS.
• THE PRINT STATEMENT :
• The print statement is used to write your program output to the console or to the terminal.
• It is useful for sending messages and keeping track of what is happening in the program.
• It prints the given object to the standard output device which is generally a screen or to the text stream
file.
• Print is a built-in function in python meaning you do not have to import it from anywhere.
• You can call the print statement by using "print()" statement.
• You can also access it through a module from the standard library called "builtins".
• Syntax :
• print()
• EG :
• print("Hello world")
• print("Welcome to the class of python")
• print("This is just a print statement to show the example for python")
COMMENTS.
• Comments are very important in any programming language.
• They are not part of your functionality but helps you to make your code more readable.
• It also helps you to prevent execution when you are testing the code.
• Comments can also be used to explain the python code.
• Comments always starts with a "#" and python will understand that this is a comment and will
ignore them.
• A comment may appear at the start of a line or code but not within a string literal.
• Example :
• #This is a comment example
• print("Hello world")
COMMENTS.
• Comments can also be placed at the end of a line and python will ignore the rest of the line
starting from "#"
• print("Hello world") #This is a comment example.
• Comments are not only limited to explain you code. Python can also use it to prevent the code
from execution.
• #print("This is a comment")
• print("Hello world")
• Multiline comments.
• There is really no syntax for multi-line comments. You just have to add the "#" to each of the line
that you want to be treated as a comment.
• Example :
• #This is a single line comment
• #This is a multi-line comment
• #Adding another line for multi-line comment
• print("Hello world")
COMMENTS.
• You can either use the above method, or you can use a multiline
string to represent a multi-line comment.
• You can add a multiline string in your code and place your comment
inside it.
• Example :
• """
• This is a comment
• Showing the exampel for multiline comments
• Adding another line
• Adding another line for multiline comments
• """
• print("Hello world")
PYTHON DATA STRUCTURES AND DATA TYPES.

• Data structures are structures that can hold some data together for later use.
• In other words, they are used to store a collection of related data.
• Data structures deal with how the data is organized and held in the memory when a program processes it.
• Below are the data types that you have in python.
• Numbers
• Strings
• Lists
• Tuples
• Dictionaries
PYTHON DATA TYPES.
• There are four built-in data structures in python - list, tuple, dictionary
and set.
• List : List is a collection of items which is ordered and changeable.
Allows for duplicate members.
• Tuple : Tuple is a collection of items which is ordered and
unchangeable. Allows for duplicate members.
• Set : Set is a collection of items which is unordered and unindexed.
Does not allow for duplicate members
PYTHON DATA TYPES - NUMBERS.
• Number data types store numeric values. They are immutable data
types, meaning you can change the value of the number data type.
• Python supports below different numerical data types.
• Integers : They are referred as "int" with no decimal point. Integers can be a
positive or negative whole numbers.
• Floating point numbers : They are integers with decimal points or fractional
parts. They are referred as "float".
• Complex numbers : They are of the form a + bj where and b are floats and j is
an imaginary number. Complex numbers are not used much in python
programming.
PYTHON DATA TYPES - STRINGS.
• Strings are sequence of characters using the syntax of either
single quotes or double quotes.
• 'hello' “hello” “Today's date”
• print (“Hello python”)
• print (“Hello \npython”)
• print (“Hello \t python”)
• len (“Hello”)
• len (“Today's date”)
INDEXING AND SLICING.
• Because strings are ordered sequences, it means we can use indexing
and slicing to grab sub-sections of tje string.
• Indexing allows you to grab a single character from the string.
• These actions use [] square brackets and a number index to indicate
positions of what you wish to grab.
• character : python
• index : 012345
• Reverse index :0 -5 -4 -3 -2 -1
SLICING.
• Slicing allows you to grab a sub-section of multiple characters, a
“slice” of a string.
• This has the following syntax:
• [start:stop:step]
• Start with a numerical index for the slice start.
• Stop is the index you will go up to.
• Step is the size of the “jump” you take.
PYTHON DATA TYPE - LISTS.
• List is a collection of items which is ordered and changeable. Allows for duplicate members.
• In python, lists are written with square brackets.
• Example :my_list = ["one","two","three"]
• Python has the below built-in methods that you can use with lists.
• append() : Adds an element at the end of the list
• clear() : Removes all the elements from the list
• copy() : Returns a copy of the list
• count() : Returns the number of elements with the specified value
• extend() : Add the elements of a list (or any iterable), to the end of the current list
• index() : Returns the index of the first element with the specified value
• insert() : Adds an element at the specified position
• pop(): Removes the element at the specified position
• remove() : Removes the item with the specified value
• reverse() : Reverses the order of the list
• sort() : Sorts the list
PYTHON DATA TYPE - TUPLES.
• A tuple is a collection that is ordered and unchangeable.
• In python, tuples are written with round brackets.
• Example : my_tuple = ("one","two","three")
• Once a tuple is created, you cannot change its values. Tuples are immutable or
unchangeable. But there is a workaround for this.
• You can convert the tuple to a list, change the value and change it back to a tuple.
• Python has the following built-in methods for tuples.
• count() : Returns the number of times a specified value occurs in the tuple.
• x = my_tuple.count("test")
• index() : Return the position of the specified item in the tuple.
• y = my_tuple.index("test")
PYTHON DATA TYPE - SETS.
• A set is a collection of items that is unordered and unindexed. A set will always
contain uinque items.
• In python, sets are written with curlt brackets.
• Example : my_set = {"one","two","three"}
• You cannot access items in a set by referring the index because sets are
unordered and does not have an index.
• But you can loop through the set or find a specific iten in the set by using the in
keyword.
• Once a set is created, you cannot change the items, however you can add new
items to the set.
• You can add more items to the set by using the update() keyword.
PYTHON DATA TYPE - SETS.
• If the item to remove does not exist in the set, then it will throw an error.
• You can also us the pop() method to remove an item, however this method will
remove the last item from the set.
• Python has the following built-in methods for sets.
• add() : Adds an element to the set
• clear() : Removes all the elements from the set
• copy() : Returns a copy of the set
• discard(): Remove the specified item
• pop() : Removes an element from the set
• remove() : Removes the specified element
• union() : Return a set containing the union of sets
• update() : Update the set with the union of this set and others
PYTHON DATA TYPE -
DICTIONARIES.
• A dictionary is a collection which is unordered, changeable and indexed.
• Dictionaries are written with curly braces and they consists of key and values.
• my_dict = {"key1":"value1","key2":"value2",....}
• print(my_key)
• type(my_key)

• You can access the items in the dictionary by referring it key name in square brackets.
• print(my_dict["key2"])

• You can change the value of a specific item by referring it key name.
• my_key["key2"] = "new_value"

• You can also loop through a dictionary. When you use the for loop, the return values are the keys of the dictionary.
• There are methods that you can use to return the values as well.
• my_dict = {"key1":"value1","key2":"value2"}
• for x in my_dict:
•     print(x)
• my_dict = {"key1":"value1","key2":"value2"}
• for x in my_dict:
•     print(my_dict[x])
PYTHON DATA TYPE -
DICTIONARIES.
• You can also use the "values" keywork to get the values from a dictionary.
• my_dict = {"key1":"value1","key2":"value2"}
• for x in my_dict.values():
•     print(x)
• You can also use for loop to print keys and values by using the items keyword.
• my_dict = {"key1":"value1","key2":"value2"}
• for x,y in my_dict.items():
•     print(x,y)
• You can use the pop keywork to remove an item from a dictionary by using a keyword.
• my_dict = {"key1":"value1","key2":"value2"}
• x = my_dict.pop("key2")
• print(my_dict)
PYTHON DATA TYPE -
DICTIONARIES.
• You can clear a dictionary by using the clear() method.
• my_dict = {"key1":"value1","key2":"value2"}
• my_dict.clear()
• print(my_dict)
• Python has many more built-in methods that you can use in Dictionaries.
• clear() : Removes all the elements from the dictionary
• copy() : Returns a copy of the dictionary
• fromkeys() : Returns a dictionary with the specified keys and values
• get() : Returns the value of the specified key
• items() : Returns a list containing a tuple for each key value pair
• keys() : Returns a list containing the dictionary's keys
• pop(): Removes the element with the specified key
• popitem() : Removes the last inserted key-value pair
• setdefault(): Returns the value of the specified key. If the key does not exist: insert the key, with the
specified value
• update() : Updates the dictionary with the specified key-value pairs
• values() : Returns a list of all the values in the dictionary
PYTHON DATA TYPE - BOOLEAN.
• Booleans are used to represent True or False values in python.
• When you compare 2 values, python will evaluate the expression and return the boolean answer.
• Example:
• 10 > 9
• 9 > 10
• Almost any value is evaluted as True in if it has some content.
• bool("Hello")
• bool(15)
• The boolean will be evaluted as False if the strings are empty, number is "0" and list, tuple, set and dictionary
are empty.
• bool()
• bool(0)
• bool("")
• bool(())
• bool([])
INPUT AND OUTPUT IN PYTHON.
• Developers often have a need to interact with the users, either to get
some data or to provide some sort to results.
• Most programs today use a dialog box as a way of asking the user to
provide some type of input.
• While python provides us with two builtin functions to read the input
from the keyboard.
• raw_input() : This is used in version 2.x
• input() : This is used in version 3.x
• Example.
HOW THE INPUT FUNCTION WORKS IN PYTHON.

• When input() function executes, program flow will be stopped until


the user has given an input.
• Whatever you enter as input, input function will convert it into a
string.
• If you enter an integer value, input() function will convert it into a
string.
• You need to explicitly convert it into an integer in your code.
OUTPUT FORMATTING IN PYTHON.
• Often you will want to “inject” a variable into your string for printing.
• course = 'python'
• print ('Hello' + course)
• There are multiple ways to format strings for printing variables in
them.
• This is known as string interpolation.
• Lets explore the 2 methods for this.
• .format() method.
• f-strings (Formatted string literals)
FORMATTING WITH .FORMAT() METHOD.


FLOAT FORMATTING WITH .FORMAT()METHOD.

• Allows you to adjust the width and precision of your floating point
number.
OPERATORS IN PYTHON.
TABLE OPERATORS.
• Please remember that comparison operators are case sensitive and
also data types are also taken into consideration.
• ‘2’ == 2
• ‘Bye’ == ‘bye’
• 2 == 2
• ‘Bye’ == ‘Bye’
• However, floating point will return true as long as the values are equal
• 2.0 == 2
CHAINING COMPARISON OPERATORS.

• So far we saw how we can use the comparison operators to compare


one value with another.
• To compare more than one value you will need to chain comparison
operators. Ie you will need to use logical operators.
• We can use logical operators to combine comparisons,
• And
• Or
• Not
COMPARISON OPERATOR.
• AND : In this oprerator, both the conditions must be true.
• 1<2
• 2<3
• 1 < 2 and 2 < 3
• OR : In this operator, any one of the condition must be true.
• 1 == 1 or 2 == 2
• 1 == 2 or 2 == 3
• 1 == 2 or 2 == 2
• Not : Not is used to get the opposite of the boolean conditions.
• 1 == 1
• not(1 == 1)
INDENTATION.
• Indentation in python refers to the spaces and tabs that are used at
the beginning of a statement.
• The statements with the same indentation belong to the same group
called a suite.
• Example :
THE IF STATEMENT (ALSO KNOWN AS DECISION MAKING).

• Decisions in a program are used when the program has conditional


choices to execute a block of code.
• Lets take an example of traffic lights.
• It is the prediction of conditions that occur while executing the
program to specify actions.
• Multiple expressions get evalated with an outcome of either True or
False.
• These are logical decisions, and python also provides decision making
statements that is used to make a decision within a program for an
application based on the user requirement.
THE IF STATEMENT (ALSO KNOWN AS DECISION MAKING).

• Below are the conditional statements that python provides.


• if statements : Consists of a boolean expression which evaluates to
True or False followed by one or more actions.
• Syntax :

• Example :
THE IF STATEMENT (ALSO KNOWN AS DECISION MAKING).

• if else statements : Consists of a boolean expression followed by an


optional else statement and if the expression evaluated to False, then
else statement will be executed.
• Syntax :

• Example :
THE IF STATEMENT (ALSO KNOWN AS DECISION MAKING).

• elif or nested statement : We can implement if statement and if-else


statement inside another if or if-else statement. Here there are more
than one if conditions are applied and there can be more than one
within elif.
• Syntax : Example :
LOOPS IN PYTHON.
• In general, statements are executed sequently.
• The first statement in a function is executed first, followed by the
second and so on.
• There may be a situation when you need to execute a block of code
several number of times.
• Programming languages provide various control structures that allow
for more complicated execution paths.
• A loop statement allows us to execute a statement or a group of
statements multiple times.
LOOPS IN PYTHON - WHILE.
• Python provides the following type of loops to handle loop
requirements.
• While loops
• For loops
• Nester loops
• While loop : Repeats the statement or a group of statements while a
given condition is True. It tests the  given condition before executing
the loop body.
• Syntax :
LOOPS IN PYTHON - WHILE.
• Example :
LOOPS IN PYTHON - WHILE.
• Using else statements with loop :
LOOPS IN PYTHON - FOR.
• For loop : Executes a sequence of statements multiple times.
• Syntax :

• Example:
LOOPS IN PYTHON - FOR.
• Using else statements with for loop :
LOOPS IN PYTHON - NESTED.
• nested loops : Use one or more than one loop inside any another
while, for and do...while loop.
• Syntax :

• Example :
LOOPS IN PYTHON - NESTED.
• Syntax for while nested loop:

• Example for while nester loop:


LOOPS IN PYTHON - NESTED.
• While loop with else block :
LOOP CONTROL STATEMENTS.
• Loop control statements are used to change the execution from its
normal sequence.
• When execution leaves a scope, all automatic objects that were
created in that scope are destroyed.
• Python provides the following control statements.
• break.
• continue.
• pass.
LOOP CONTROL STATEMENTS - BREAK.

• Terminates the loop statement and transfers the execution to the


statement immediately following the loop.
• With the break statement we can stop the loop before it has looped
through all the items.
LOOP CONTROL STATEMENTS - CONTINUE.

• Causes the loop to skip the remainder of its body and immediately
retest its condition prior to reiterating.
• With the continue statement we can stop the current iteration of the
loop, and continue with the next loop.
LOOP CONTROL STATEMENTS - PASS.
• Used when a statement is required syntactically but you do not want
any command or code to execute.
• For loops cannout be empty, but if you for some reason have a for
loop with no content, you can use the pass statement to avoid getting
an error.
RANGE STATEMENT.
• To loop though a set of code a specified number of times, we can use
the range() function.
• The range() function returns a sequence of numbers, starting at '0' by
default and increments by '1' by default and ends at the specified
number.
RANGE STATEMENT.
• The range() function default to '0' as a starting value, however, it is possible to
specify the starting value by adding a parameter : range(2,6) which means values
from 2 to 6 not including 6.

• The range() function defaults to increment the sequence by '1', however it is


possible to specify the increment value by adding a third parameter :
range(2,20,2)
ASSERT.
• Assert is a debugging aid that tests a condition.
• If the condition is true, it does nothing and your program just continues to
execute.
• But if the assert condition evaluates to false, it raises an “AssertionError”
exception with an optional error message.
• The assert keyword is used when debugging your code.
FUNCTIONS AND MODULES.
• A function is a block of code that get executed only when you call the function.
• You can pass data, known as parameters into a function.
• A function can return data as a result.
• Functions are used to utilize the code in more than one place in a program.
• Creating a function :
• In python a function is created by using “def” keyword.
FUNCTIONS AND MODULES.
• Calling a function :
• To call a function, use the function name followed by parenthesis.
FUNCTIONS AND MODULES - PARAMETERS.

• Information can be passed to functions as parameters.


• Parameters are specified after the function name, inside the parenthesis. You can add as many
parameters as you want, just separate them with a comma.
• The following exmaple has a function with one parameter. when the function is called, we pass
along the value which is used inside the function to execute the code.
DEFAULT PARAMETER VALUE.
• You can also pass default parameter within a function.
• If you call the function without the parameter, the default parameter
will be used.
PASSING A LIST AS A PARAMETER.
• You can send any data types of parameter to a function.
• It could be your string, number, list, dictionary, etc.
RETURN STATEMENT.
• You can use the return statement to let a function return a value.
SCOPE OF A FUNCTION.
• Variables can only reach the area in which they are defined. This is called as
scope.
• Python supports global variables and local variables.
• By default, all variables declared in a function are local variables.
• Local scope : A variable created inside a function belongs to the local scope of
that function and can only be used inside that function.
FUNCTION INSIDE FUNCTION.
• The local variable can be accessed from a function within the
function.
GLOBAL SCOPE.
• A variable created in the main body of the python code is a global
variable and belongs to the global scope.
• Global variables are defined outside a function.
GLOBAL KEYWORD.
• If you need to create a global variable but are stuck in the local scope, then you
can use the “global” keyword to make the variable global.

• You can also use the global keyword to make a variable global inside a function.
LAMBDA FUNCTIONS.
• Lambda functions are small, restricted functions that do not need a name or an
identifier.
• Lambda functions are also known as anonymous functions.
• A lambda function can take any number of arguments but it can have only one
expression.
• Use lambda functions when an anonymous function is required for a short period
of time.
• With lambda, you do not have to declare the function in the standard manner,
that is by using the def keyword.
• These functions are declared by using the “lambda” keyword.
• It simulates inline functions in C and C++ but is not exactly an inline function.
LAMBDA FUNCTIONS.
• Syntax :

• Example :

LAMBDA FUNCTIONS.
• The main role of a lambda function is better described in the
scenarios when we use them anonymously inside another function.
• Use lambda function when an anonymous function is required for a
short period of time.

LAMBDA FUNCTION WITH MAP.
• The map() function in python takes in a function and a list as
argument.
• The function is called with a lambda function and a list and a new list
is returned which contains all the lambda modified items returned by
that function for each item.
LAMBDA FUNCTION WITH FILTER.
• The filter() function in python takes in a function and a list as an
argument.
• This offers and elegant way to filter out all the elements of a sequence
for which the function return True.
LAMBDA FUNCTION WITH REDUCE.
• The reduce() function is used to apply an operation to every element in a
sequence
• This is similar to the map() function, however, it differs in the way it operates.
• Perform the operation on the first 2 items of the sequence.
• Save this result.
• Perform the operation with the saved result and the next item in sequence.
• Repeat until there are no more items in sequence.
MODULES IN PYTHON.
• A module allows you to logically organize your python code.
• Grouping related code into a module makes the code easier to
understand and use.
• Simply, a module is a file in python code.
• A module can define functions, classes and variables.
• A module can also include runnable code.
• Consider a module to be same as a code library.
• A file containing a set of functions you want to include in your
application.
CREATE A MODULE.
• To create a module, just save the file with the file extension “.py”.
• Lets create a file and name is mymodule.py
• Below is the code i have in mymodule.py
USING A MODULE.
• Now we can use the module that we just created by using the
“import” statement from another “.py” module.
• Lets create a file with python.py and add the below code.
EXCEPTION HANDLINGS.
• An exception is an event, which occurs during the execution of a
program that disrupts the normal flow of the program's instructions.
• In general, when a python script or program encounters a situation
that it cannot cope with, it raises an exception.
• An exception is a python object that represents an error.
• It is a type of run time error that commonly occurs in a program or a
script.
EXCEPTION HANDLINGS.
• To use exception handling in python, you will first need to have a
catch-all except clause.
• The words “try”, “finally” and “except” are python keywords and are
used to catch exceptions.
• The “try” block lets you test a block of code for errors.
• The “except” block lets you handle the error.
• The “Finally” block lets you execute the code regardless of the result
of the try and except blocks.
EXCEPTION HANDLING.
• When an error occurs, or exception as we call it, python will normally
stop and generate an error message.
EXCEPTION HANDLING.
HANDLING MULTIPLE EXCEPTIONS.
• You can define as many exceptions as you want, example: If you want to execute
a special block of code for a special kind of error.

• ELSE : You can use the “else” keyword to define a block of code to be executed if
nor errors were raised.
EXCEPTION HANDLING.
• Finally : The “finally” block, if specified, will be executed regardless of the try
block raises an error or not.

• This can be useful to close objects and clean up resources. Example, try to open
and write to a file that is not writable.
• This program can continue without leaving the file object open.
RAISING AN EXCEPTION / WIRTING YOUR OWN EXCEPTIONS.

• As a python developer, you can choose to throw an exception if a condition


occurs.
• To throw an exception, you can use the “raise” keyword.

• The “raise” keyword is used to raise an exception.


• You can define what kind of error to raise, and the text you want to be printed to
the user.
PYTHON FILE HANDLING.
• File handling is a process by which a software handles its input or
output operations with binary or text files.
• For example, in any program that handles permanent data, you will
need to write and read information whether that is via a database
handler or by using explicit files.
• Python too supports file handling and allows users to handle files.
That is to read and write files along with other file handling options to
operate on the files.
FILE HANDLING MODES.
• Python has several functions for reading, updating, creating and deleting files.
• The key function for working with the files in python is the “open()” function.
• The “open()” function takes 2 parameters : filename and mode.
• There are 4 different modes available for opening a file.
• “r” - read : This is the default value which will open a file for reading and will throw an error if the file
does not exist.
• “w” - write : This will open the file for writing andf will create the file if it does not exist.
• “a” - append : This will open the file for appending and will create the file if it does not exist.
• “x” - create : This will create the specified file and will return an error if the file exists.
• In addition to the above mentioned menthods, you can also specify how the file should be
handled.
FILE HANDLING MODES.
• “t” - text : This is the default value and specifies that the file shoule be
handled in the text mode.
• “b” - binary : This specifies that the file should be handled in the
binary mode like images.
• Syntax :
• To open a file for reading, you can specify the name of the file.
FILE HANDLING MODES.
• Because 'r' for read and 't' for text are the default values, you do not
have to specify them.
• Make sure that the file you are trying to read exists, else you will get
an error.
OPENING A FILE.
• To open a file located on a server, you can use the built-in “open()” function.
• The open() function returns a file object, which has a “read()” method for reading
the contents of a file.
• Eg :

• By default, the read() method returns the whole text, but you can also specify
how many characters you want to return.
• Eg :
OPENING A FILE.
• You can also return the lines from a file by using the “readline()” method. Each
readline() method returns one line.
• Eg :

• If you want to read multiple lines from a file, you will need to specify the
readline() method multiple times.
• Eg :
OPENING A FILE.
• You can also read through the whole file line by line by looping through the lines of the file.
• Eg :

• It is very important and a good practise to always close a file once you are done working with the
file.
• You should always close your files. In some cases, due to buffering, changes made to a file may
not show until you close the file.
• Eg :
WRITING TO A FILE.
• When you are reading a file, you can do so just by using the open()
function. You do not have to pass any parameters as “r” is taken by
default.
• However, when you are working with the write, you will need to pass
parameter to the open() function.
• Here you can use 2 types of parameters.
• “a” - append : This will append to the end of the file.
• “w” - write : This will overwrite any existing content of a file.
WRITING TO A FILE.
• Eg :

• Eg :
WRITING TO A FILE.
• To create a new file in python, you can use the open() method with
any of the following parameters.
• “x” - create : This will create a file and returns an error if the file
exists.
• “a” - append : This will create a file if the file does not exists.
• “w” - write : This will create a file if the specified file does not exists.
• Eg :
DELETING A FILE.
• You can also delete the files/folders in python. To do this you can
import the “OS” module which is a way of using operating system
dependent functionality.
• To delete a file, you can use the “os.remove()” function.
• Eg :

• It is a good practise to check whether the file exists or not before you
can try deleting it. This way you can avoid getting any errors.
DELETING A FILE.
• Eg :

• You can also delete a folder by using the “os.rmdir()” method.


• Eg :

• Remember that the folder you are trying to delete must be empty and should not
have any files inside the folder.
HANDLING FILE EXCEPTIONS.
• Whenever a run time occurs, it creates an exception.
• Usually the program stops and python prints a error message.
• For example, dividing by zero creates an exception.
• print (55/0)
• So does accessing a nonexistent list item.

• Or accessing a key that is not there in the dictionary.

• Or trying to open a non-existent file.


HANDLING FILE EXCEPTIONS.
• Sometimes we want to execute an operation that could cause an
exception but do not want the program to stop.
• We can handle the exceptions using the try and except statements.
• Eg :

• Write a function to handle the above exception.


THE WITH STATEMENT.
• In python, the with statement is used in exception handling to make
the code cleaner and much more readable.
• It simplifies the management of common resources lile file streams.
• With the “with” statement, you get better syntax and exception
handling.
• In addition, it will automatically close the file.
• The with statement provides a way for ensuring that a clean up is
always used.
THE WITH STATEMENT.
• Eg : Without the with statement.

• Eg : With the “with” statement.

• Exercise : Execute with statement with exception handling.


CLASSES IN PYTHON.
• A class is a code template for creating objects. Objects have member variables and have
behaviour associated with them.
• Python is an OOP language. Unlink the procedural oritented programming, where the emphasis is
on function, OOP stresses on objects.
• Object is simply a collection of data (variable) and methods (functions) that act on those data.
• Class is a blueprint for the object.
• We can think of class as a prototype of a house. It contains all the details about the floors, doors,
windows, etc. Based on these descriptions we build the house.
• House is the object here.
• As many houses can be made from a description, we can create many objects from a class.
CLASSES IN PYTHON.
• An object is also called an instance of a class and the process of creating this
object is called instantiation.
• Like function definition begins with the keyword “def”, in python we define a
class using the keywork “class”.
• Object oriented programming or OOPs allows programmers to create their own
objects that have methods and attributes.
• Remember that after defining a string, list, dictionary or other objects, you were
able to call methods off of them with the “.method_name()” syntax.
• These methods act as functions that use information about the object as well as
the object itself to return results or change the current object.
• OOP allows users to create their own objects.
CLASSES IN PYTHON.
• The general format is often confusing when first encountered and its
usefulness may not be completely clear at first.
• In general, OOP allows us to create code that is repeatable and
organized.
• For much larger scripts of python code, functions by themselves are
not enough for organization and repeatability.
CLASSES IN PYTHON.
• Syntax :

• Eg :

• Once you are done creating a class, you will need to create an object
to work with the class.
CLASSES IN PYTHON.
• Eg :

• The example above are classes and objects in their simplest form and are not
really useful in read life applications.
• To understand the meaning of classes, we will have to understand the build-in
“__init__()” function.
• All classes have a function called __init__(), which is always executed when the
class if being initiated.
• Use the __init__() function to assign values to object properties or other
operations that are necessary to do when the object is being created.
CLASSES IN PYTHON.
• Eg :

• The __init__() function is automatically called every time the class is being used
to create a new object.
• The self parameter is a reference to the current instance of the class and is used
to access variables that belongs to the class.
• It does not have to be named self. You can call it whatever you like but it has to be
the 1st parameter of any function in the class.
CLASSES IN PYTHON.
• Eg :
ATTRIBUTES AND METHODS.
• A class attribute is a python variable that belongs to a class rather
than a particular object.
• It is shared between all the objects of this class and it is defined
outside the constructor function, __init__(self) of the class.
• Class attributes are attributes which are owned by the class itself.
They will be shared by all the instances of the class.
• Therefore they will have the same value for every instance.
ATTRIBUTES AND METHODS.
• Eg :

• A method is a set of instructions. Methods are functions which are


associated with an object.
• A method is a function that is inside of a class.
• The key difference between an attribute and a method is how we call
them.
ATTRIBUTES AND METHODS.
• Remember when calling the attributes we never used the parenthesis
to call them.
• However, when you are going to call the methods, you will need to
provide the parenthesis to call them.
• Eg :
ATTRIBUTES AND METHODS.
• You can also pass arguments to your methods from outside.

• Eg :
INHERITANCE.
• Inheritance allows us to define a class that inherits all the methods
and properties from another class.
• When you talk about inheritance, you will have a parent class and a
child class.
• Parent class is the class being inherited from also called as the base
class.
• Child class is the class that inherits from another calss also called as
the derived class.
CREATING A PARENT CLASS.
• The syntax for creating a parent class is same as creating any other
class. So you can make any class as a parent class.
• Eg :
CREATING A CHILD CLASS.
• You can create a child class by passing the parent class as a parameter
to the child class that will inherit the properties from the parent class.
• Eg :

• Now the child class will have the same properties and methods as the
“person” class.
CREATING A CHILD CLASS.
• So far we have created a child class that will inherit the methods and properties
from a parent class.
• We can also add the __init__() function to the child class.
• But remember that when you add the __init__() function, the child class will no
longer inherit the properties from the parent class.
• The __init__() in the child class will override the inheritance from the parent
__init__() function.
• Eg :
CREATING A CHILD CLASS.
• You can overcome this by adding a call to the __init__() function of the parent
class.
• Eg :

• This way you can include the __init__() function in a child class and also add a
__init__() function from the parent class to inherit the properties.
• Python can also provide you with a “super()” function that can be used to inherit
the properties from the parent to the child class.
CREATING A CHILD CLASS.
• Eg :

• Eg :
CREATING A CHILD CLASS.
• Eg :
POLYMORPHISM.
• Polymorphism refers to the way in which different objects can share
the same method name.
• Sometimes an object comes in many types or forms. If we have a
button, therer are many different draw outputs.
• It can be a round button, check button, square button or a button
with image, they all share the same logic. We access them using the
same method. This is called polymorphism.
POLYMORPHISM.
• Eg :
POLYMORPHISM WITH ABSTRACT CLASS.

• An abstract class is a class that never expects to be instantiated. In abstract class


we do not create an instance for the class.
• An abstract class is only designed to serve as a base class.
• Eg :
POLYMORPHISM WITH ABSTRACT CLASS.

• Eg :
EXCEPTION CLASS.
• Python has many built-in exceptions which forces your program to output an
error when something goes wrong.
• In python, users can define such exceptions by creating a new class.
• This exception class has to be derived either directly/indirectly from “Exception”
class. Most of the build-in exceptions are also derived from this class.
• Eg :
EXCEPTION CLASS.
• Eg :

• This is the standard way of creating user defined exceptions in python but you are not limited to
only this.
PYTHON ITERATORS.
• An iterator is an object that contains a countable number of values.
• An iterator is an object that you can iterate upon, meaning you can go
through all the values.
• You can implement an iterator by using methods, __iter__() and
__next__().
CREATING ITERATORS.
• To create an object/class as an iterator you have to implement the
methods __iter__() and __next__() to your object.
• All the classes have a function called __init__() which allows you to
initialize when an object is created.
• The __iter__() method also does the same thing but must return the
iterator object.
• The __next__() method also allows you to do operations but must
return the next item in the sequence you have.
PYTHON ITERATORS.

• StopIteration : To stop an iteration from going on forever, we can use the “StopIteration”
statement.
• In the “__next__()” method, you can add a terminating condition that will raise an error if the
iteration completes the speccified number of times.
PYTHON ITERATORS.
GENERATORS.
• A python generator is a function that produces a sequence of results.
• It works by maintaining its local state, so that the function can resume
again exactly where it left off when called subsequent times.
• Thus, you can think of a generator as something like a powerful
iterator.
• The state of the function is maintained through the use of the
keyword “yield” which has the below syntax.
GENERATORS.
• This works much like your “return” statement but has some differenences.
• Generator function allows us to write a function that can send back a value and
then later resume to pick up from where it left off.
• The advantage is that instead of having to computer an entire series of values up
front, the generator computes one value, waits until the next value is called for.
• For example, the range() function does not produce a list in memory for all the
values start to stop.
• Instead, it just keeps track of the last number and the step size, to provide the
flow of numbers.
GENERATORS.
ANY and ALL IN PYTHON.
• Python provides two built-in functions for “AND” and “OR” operations. They are
“ALL” and “ANY” functions.
• any() function:
• The “any()” function returns True if any item in an iterable are true, otherwise it returns
False.
• Even is the iterable object is empty, the “any()” function will return False.
• Syntax : any(iterable)
• The iterable object can be a list, tuple or dictionary.
ANY and ALL IN PYTHON.

• Return values from any():


• True : If atleast one item of the iterable is True.
• False : If all the items are False or if an iterable is empty.
ANY and ALL IN PYTHON.
• all() function :
• The all() function returns True if all items in an iterable are true, otherwise it return False.
• If the iterable object is empty, the all() function returns True.
• Syntax : all(iterable)
• The iterable object can be a list, tuple or dictionary.
ANY and ALL IN PYTHON.

• Return value from all():


• True : If all items in an iterable are True.
• False : If any element in an iterabe is False
DATA COMPRESSION.
• In python, the data can be archived, compressed using the modules
like zlib, gzip, bz2, lzma,zipfile and tarfile.
• To use the respective module, you will need to import the module
first.
DATA STRUCTURES.
• Data structures are basically just that, which can hold some data
together.
• In other words, they are used to store a collection of related data.
• There are 4 built-in data structures in python - list, tuple, dictionary
and set.
LIST COMPREHENSION.
• List comprehension provides a concise way to create lists.
• It consists of brackets containing an expression followed by a “for” clause, then
zero or more “for” or “if” clause.
• The result will be a new list resulting from evaluating the expression in the
context of the “for” and “if” clauses which follow it.
• The list comprehension always returns a result list.
• Syntax: The list comprehension starts with a “[“ and “]”, to help you remember
that the result is going to be a list.
LIST COMPREHENSION.
NESTED LIST COMPREHENSION.
• List comprehensions are one of the most amazing features in python.
• It is a smart way of creating lists by iterating over an iterable object.
• Nested list comprehensions are nothing but a list comprehension within another
list comprehension which is quite similar to nested for loops.
DICTIONARY COMPREHENSION.
• Like list comprehension, python allows dictionary comprehensions.
• We can create dictionaries using simple expressions.
• A dictionary comprehension takes the following form,
• {key:value for (key,value) in iterable}
SPECIALIZED SORTS IN PYTHON.
• Sorting any sequence is very easy in python using the built-in method “sorted()”
which does all the hard work for you.
• Sorted() sorts any sequence (list,tuple) and always returns a list with the
elements in sorted manner without modifying the original sequence.
• Syntax : sorted(iterable, key,reverse)
• Parameters : Sorted takes 3 parameters from which two are optional.
• Iterable : Sequence (list, tuple, string) or collection (dictionary, set, frozenset) or any other
iterable that needs to be sorted.
• Key : A function that would serve as a key or a basis of sort comparision.
• Reverse : If set true, then the iterable would be sorted in reverse order. By default it is set as
false.
SPECIALIZED SORTS IN PYTHON.
• Frozenset :
• Frozen set is an immutable version of a python set object.
• While elements of a set can be modified at any time, elements of a frozen set remains the
same after creation.
• Due to this, frozen sets can be used as key in dictionary or as element of another set.
SPECIALIZED SORTS IN PYTHON.
*ARGS AND **KWARGS IN PYTHON.
• *args : The syntax “*args” in function definitions in python is used to pass a
variable number of arguments to a function.
• It is used to pass a non-keyworded, variable length argument list.
• The syntax is to use the symbol “*” to take in a variable number of arguments, by
convention, it is often used with the word args.
• The “*args” allows you to take in more arguments than the number of formal
arguments that you previously defined. With “*args” any number of extra
arguments can be taken on your current formal parameters.
• For example, we want to multiply function that takes any number of arguments
and able to multiply them all together. It can be done using “*args”.
*ARGS AND **KWARGS IN PYTHON.
• Eg :
*ARGS AND **KWARGS IN PYTHON.
• **kwargs : The special syntax “**kwargs” in function definitions in python is used
to pass a keyworded, variable length argument list.
• We use the name “kwargs” with the double stars. The reason is because double
star allows us to pass through keyword arguments.
• A keyword argument is where you provide a name to the variable as you pass it
into the function.
• One can think of the “kwargs” as being a dictionary that maps each keyword to
the value that we pass alongside it. That is why, when we iterate over the kwargs
there does not seem to be any order in which they are printed out.
*ARGS AND **KWARGS IN PYTHON.
COLLECTIONS - NAMEDTUPLE()
• Python supports a type of container like dictionaries called
“namedtuple()” present in module collections.
• Like dictionaries, they contain keys that are hashed to a particular
value.
• But on contrary, it supports both access from the key value and
iteration, the functionality that dictionaries lack.
COLLECTIONS - NAMEDTUPLE()
• Access operations :
• Access by index : The attribute values of namedtuple() and ordered and can
be accessed using the index number inlike dictionaries which are not
accessible by index.
• Access by keyname : Access by keyname is allowed as in dictionaries.
• Using getattr() : This is yet another way to access the value by giving
namedtuple() and key value as its arguments.
COLLECTIONS - NAMEDTUPLE()
• Convertion operators :
• _make() : This function is used to return a namespace() from the iterable
passed as argument.
• _asdict() : This function returns the OrderDict() as constructed from the
mapped values of namedtuple().
• Using “**” operator : This function is used to convert a dictionary into a
namedtuple()
COLLECTIONS - NAMEDTUPLE()
• Additional operators :
• _fields : Returns all the keynames of the namespace declared.
• _replace() : Change the values mapped with the passed keyname.
COLLECTIONS - DEQUE.
• Deque can be implemeted in python using the module “collections”.
• Deque is preferred over list in the cases where we need quicker
append and pop operations from both the ends of container, as
deque provides an 0(1) time complexity for append and pop
operations as compared to list which provides 0(n) time complexity.
• Operations on deque :
• append() : Insert the value in the argument to the right end of the deque.
• appendleft() : Insert the value in the argument to the left end of the deque.
COLLECTIONS - DEQUE.
• pop() : Deletes an argument from the right end of the deque.
• popleft() : Deletes an argument to the left end of the deque.
COLLECTIONS - DEQUE.
• index(ele,beg,end) : Returns the 1st index of the value mentioned in arguments, starting
searching from beg and till end index.
• insert(i,a): Inserts the value mentioned in arguments(a) at index i specified in arguments.
• remove() : Removes the 1st occurence of value mentioned in arguments.
• count() : Counts the number of occurences of values mentioned in arguments.
COLLECTIONS - CHAINMAP.
• Python also contains a container called “ChainMap” which
encapsulates many dictionaries into one unit.
• ChainMap is member of module “collections”.
• Access operations :
• keys() : Displays all the keys of all the dictionaries in ChainMap.
• values() : Displays all the values of all the dictionaries in ChainMap.
• maps : Displays keys with corresponding values of all the dictionaries in
ChainMap.
COLLECTIONS - CHAINMAP.
COLLECTIONS - CHAINMAP.
• Manipulating operations:
• new_child() : Adds a new dictionary in the beginning of the file
ChainMap.
• reversed() : Reverses the relative ordering of dictionaries in the
ChainMap.
COLLECTIONS - CHAINMAP.
COLLECTIONS - COUNTERS.
• Counter is a container which is included in the collections module.
• Container provides you a way to access the objects and perform iteration over
them.
• A counter is a subclass of dict.
• It is an unordered collection where elements and their respective counts are
stored as dictionary.
COLLECTIONS - COUNTERS.
• You can also create an empty counter.

• You can also update the counter using the update() method.
COLLECTIONS - COUNTERS.
• Data can be provided in any way. You can provide it as a sequence of
items, as dictionaries, as argument mapping and the Counter's data
will be increased and not replaced.
• Counts can be zero and negative also.
COLLECTIONS - COUNTERS.
• You can also use counter to count the distinct elements of a list or other
collections.

• Once initialized, you can access counters just like dictionaries.


• It does not raise the “keyValue” error even if the key is not present. Instead the
values count will be '0'.
COLLECTIONS - COUNTERS.
• elements() : This method returns an iterator that produces all the
items that are known or present in a counter.
• It does not include the items if the element count is <= 0.
COLLECTIONS - COUNTERS.
• most_common() : This method produces a sequence of the most
frequently encountered values and their counts.
ORDERDDICT.
• An OrderdDict is a subclass in dictionary that remembers the order in
which the keys are inserted.
• The difference between dict() and OrderdDict() is that OrderdDict()
preserves the order of the keys that are inserted.
• A regular dict() does not keep a track of the items and iterating the
items gives the values in an arbitrary order.
ORDERDDICT.
ORDERDDICT.
• If you change the value of a key, the position of the key remains
unchanged in OrderdDict.
ORDERDDICT.
• Deleting and re-inserting the same key will push it to the back as
OrderedDict maintains the order of insertion.
DEFAULTDICT.
• The defaultdict tool is a container in a collections class in python.
• It is similar to the usual dictionary container but the only difference is that a defaultdict will have
a default value if the key has not been set yet.
• Defaultdict is a modified dict that calls a factory function to support missing values for arbitrary
keys.
• Defaultdict is a dictionary like object which provides all methods provided by dictionary but takes
first argument (default_factory) as default data type for the dictionary.
• using defaultdict is faster than doing the same using dict.set_method method.
• A defaultdict will never raise a keyError. Any key that does not exist gets the value returned by the
default factory.
DEFAULTDICT.
ADVANCED PYTHON.
GUIs.
• We have seen till now how to write text-only programs which have a
command line interface.
• Now we will look at creating a program with an graphical user
interface.
• We will discuss about “tkinter”, a module in the python standard
library which serves as an interface to Tk, a simple toolkit.
• There are many other toolkits available, but they often vary across
platforms.
WRITING GUIS IN PYTHON.
• Python offers multiple options for developing GUI (Graphical User Interface).
• Out of all the GUI methods, “tkinter” is the most commonly used method. It is a
standard python interface to the tk GUI toolkit shipped with Python.
• Python with tkinter is the fastest and easiest way to create the GUI applications.
Creating a GUI using tkinter is an easy task.
• To create a tkinter app :
• Import the module - tkinter
• Create the main window
• Add any number of widgets to the main window
• Apply the event Trigger to the widgets.
EVENT DRIVEN PROGRAMMING.
• Anything that happens in a user interface is an event.
• A event is fired whenever a user does something. Clicks on a button or types a keyboard shortcut.
• Some events could also be triggered by occurences which are not controlled by the user.
• A background task might complete, or a network connection might be established or lost.
• Our application needs to monitor or listen for all the events that we find interesting and respond
to them in some way if they occur.
• To do this, we usually associate certain functions with particular events.
• We call a function which performs an action in response to an event an event handler and we
bind handlers to an event.
COMPONENTS IN PYTHON GUI.
• There are two methods that a developer will have to remember when
creating a python application with GUI.
• Tk()
• mainloop()
• Tk() :
• This method is used to create the main window. tkinter offers a method
'Tk(screenName=None,baseName=None,className='Tk',useTk=1).
• If you wish to change the name of the window, you can change the className to the desired
one.
• The basic code used to create the main window of your application will be,
• main_window=tkinter.Tk() where is main_window is the name of the main window object.
COMPONENTS IN PYTHON GUI.
• mainloop() :
• This method is used to when your application is ready to
run.
• mainloop() is an infinite loop that is used to run the
application, wait for any event to occur and process the
event as long as the window is not closed.
EXAMPLE GUI.
EXAMPLE GUI.

• To initialize tkinter, we have to create a Tk root widget, which is a


window with a title bar and other decoration provided by the window
manger. The root widget has to be created before any other widget
and there can be only one root widget.
• root = tk.Tk()
EXAMPLE GUI.
• w = tk.Label(root, text=”Hello world GUI”)
• The next line of code contains a Label widget. The first parameter of the label
call is the name of the parent window, in our case 'root'. So our label widget is
a child of the root widget. The keywork parameter “text” specifies the text as
shown.
• w.pack() :
• The pack method tells Tk to fit the size of the window to the given text.
• root.mainloop() :
• The window will not appear until we enter the Tkinter event loop.
ADDING A BUTTON.
ENTRY WIDGETS.
• The Enry widget is used to accept single line text strings from a user.
• If you want to display multiple lines of text that can be edited, then
you an use the “Text” widget.
• If you want to display one or more lines of text that cannot be
modified by the user, then you can use the “Label” widget.
• Syntax :
• master : Represents the parent window
• options : Options that you can use with the Enry widget.
ENTRY WIDGETS.
• Below are some of the options that are available for Entry widget.
ENTRY WIDGETS.
• Below are some of the methods that are available for Entry widget.
ENTRY WIDGETS.
TEXT WIDGET.
• This widget is used to display the multi-line formatted text with
various styles and attributes.
• This widget is mostly used to provide the text editor to the user.
• This widget also facilitates us to use the marks and tabs to locate the
specific sections of the text.
• We can also use the windows and images with the text as it can also
be used to display formatted text.
• Syntax :
TEXT WIDGET.
• Below are list of options for Text widget.
TEXT WIDGET.
• Below are the list of methods for Text widget.
TEXT WIDGET.
• Tag handling methods : The tags are the names given to the separate
areas of the text. Below are some of the tags.
TEXT WIDGET.
CHECK WIDGET.
• The Checkbutton widget is used to display a number of options to a
user as toggle buttons.
• The user can then select one or more options by clicking the button
corresponding to each option.
• You can also display images in place of text.
• Syntax :
CHECK WIDGET.
• Below are the list of options that you can use with Checkbutton.
CHECK WIDGET.
• Below are the list of methods available for Checkbutton.
CHECK WIDGET.
PYTHON SQL DATABASE - INTRODUCTION.

• A database is a collection of organized information that can easily be


used, managed, updated and they are classified to their
organizational approach.
• It is a collection of tables related to each other via columns.
• We can use SQL to create, access and manipulate data.
• Python supports many database servers for database programming.
• MYSQL, Oracle, PostgreSQL, SQLite, Microsoft SQL server,
mSQL,Microsoft Access and many more.
PYTHON SQL DATABASE - INTRODUCTION.

• It also supports Data Query Statements, Data Definition Language (DDL) and Data
Manipulation Language (DML).
• The standard database interface for python is python DB-API.
• Advantages :
• Platform independent
• Faster and more efficient
• Portable
• Support for RDS
• Easy to migrate and port database application interfaces.
• Support for SQL queries.
• Handles open and close connections.
PYTHON SQL DATABASE - INSTALLATION.

• To install mysql on Ubuntu machine, you can use the following command.
• apt-get update -y
• apt install mysql-server-5.7
• mysql_secure_installation utility
• mysql -u root -p
• create user "test"@"localhost" IDENTIFIED BY "password"
• grant all on demo.* to "test"@"localhost";
• grant all privileges on *.* to "test"@"localhost";
• If you are using windows machine, you can install mysql from below url.
• https://dev.mysql.com/downloads/mysql/
• Download the package and install it in your machine.
DATABASE CONNECTION.
• To create a connection between the sql and the python application,
the connect() method of mysql.connector module is used.
• Pass the database information like hostname, username and the
database password in the method call. The method returns the
connection object.
• Below is the syntax :
CREATING A CURSOR.
• The cursor object can be sepcified as an abstraction specified in the python DB-
API 2.0.
• It facilitates us to have multiple separate working environments through the
same connection to the database.
• We can create the cursor object by calling the 'cursor' function of the connection
object.
• The cursor object is an important aspect of executing queries to the database.
• The syntax to create a cursor is as below.
CREATING A DATABASE.
• A new database can be created using the below syntax.
CREATING A TABLE.
• We can create a table by using the “CREATE TABLE” statement of SQL.

• show databases;
• use demo;
• show tables;
• desc Employee;
INSERT OPERATION.
• The 'INSERT INTO' statement is used to add a record to a table.
• In python, we can mention the format specifier (%s) in place of
values.
• We provide the actual values on the form of tuple in the execute()
method of the cursor.
READ OPERATION.
• The 'SELECT' statement is used to read the values from a database.
• We can restrict the output of a query by using various clause in SQL
like where, limit, etc.
• Python provides the fetchall() method that returns the data stored
inside the table in the form of rows.
• We can iterate the result to get the individual rows.
READ OPERATION.
READ OPERATION.
READ OPERATION.
UPDATE OPERATION.
• The 'update-set' statement is used to update any column inside the
table.
DELETE OPERATION.
• The 'Delete from' statement is used to delete a specific record from
the table.
• Here, we must impose a condition using 'where' clause otherwise all
the records from the table will be removed.
COMMIT() METHOD.
• This method sends a COMMIT statement to the MYSQL server, to commit the
current transaction.
• Commit is used to tell the database to save all the changes in the current
transaction.
• This is especially useful when you have multipple INSERT, UPDATE and DELETE
statements within the same connection.
• If everything is in order with all the statements within a single transaction, all
changes are recorded together in the database will be committed.
• The commit saves all the transactions to the database since the last commit or
rollback command.
ROLLBACK() METHOD.
• Rollback is a command that causes all the data changes since the last BEGIN
WORK or START TRANSACTION to be discarded by the relational database
management systems, so that that state of the data is “rolled back” to the way it
was before those changes were made.
• If any error occurs with any of the SQL grouped statements, all changes needs to
be aborted.
• The process of reversing changes is called rollback.
• This command can only be used to undo transaction since the last commit or
rollback command was issued.
HANDLING ERRORS.
• Error happens all the time when programming, so it is better to equip
yourself how to deal with them.
• There are 2 types of error messages severity in mysql.
• Error : An error indicates a problem with query or command which prevented
it from being executed.
• Warning : Warning tells you something unexpected has happened that could
cause problem down the line, but it is not severe enough to stop the
statement from being executed.
HANDLING ERRORS.
• The error class is divided into 3 subclass :
• Database error
• Interface error
• Pool error
HANDLING ERRORS.
HANDLING ERRORS.
PYTHON NETWORKING.
• Python provides 2 level of access to network services.
• At a low level, you can access the basic socket support in the
underlying OS, which allows you to implement clients and servers for
both connection-oriented and connection protocols.
• Python also has libraries that provide higher-level access to specific
application-level network protocols such as FTP, HTTP and so on.
WHAT IS SOCKETS?
• Sockets are the endpoints of a bidirectional communications channel.
• Sockets may communicate within a process, between processes on the same
machine or between processes on different continents.
• Sockets may be implemented over a number of different channel types like unix
domain sockets, TCP, UDP and so on.
• The 'socket' library provides specific classes for handling the common transports
as well as a generic interface for handling the rest.
SOCKETS.
• Below are the sockets library.
THE SOCKET MODULE.
• To create a socket, you must use the 'socket.socket()' function
available in the socket module. Below is the syntax.

• socket_family : This is either AF_UNIX or AF_INET.


• socket_type : This is either SOCK_STREAM or SOCK_DGRAM.
• protocol : This is usually left out, defaulting to '0'.
• Once you have the socket object, then you can use required functions
to create your client or server program.
SERVER SOCKET METHODS.
• Below are the list of functions.
CLIENT SOCKET METHODS.
• Below are the list of methods for socket.
GENERAL SOCKET METHODS.
A SIMPLE SERVER.
• To write internet servers, we use the socket function available in socket module
to create a socket object.
• A socket object is then used to call other functions to setup a socket server.
• Now call bind (hostname,port) function to specify a port for your service on the
given host.
• Next, call the accept method of the returned object.
• This method waits until a client connects to the port you specified and then
returns a connection object that represents the connection to that client.
A SIMPLE SERVER.
A SIMPLE CLIENT.
• The 'socket.connect(hostname,port)' opens a TCP connection to
hostname on the port.
• Once you have a socket open, you can read from it like any IO object.
• When done, remember to close it, as you would close a file.
• The following code is a very simple client that connects to a given
host and port, reads any available data from the socket and then
exists.
A SIMPLE CLIENT.
A SIMPLE SERVER.
A SIMPLE CLIENT.
PYTHON DATE AND TIME.
• A python program can handle date and time in several ways.
• Converting between date formats is a common task for computers.
• Python's time and calendar modules help track dates and times.
TICK.
• Time intervals are floating-point numbers in units of seconds.
• Particular instants in time are expressed in seconds.
• There is a popular “time” module available in python which provides
functions for working with times and for converting between
representations.
• The function “time.time()” returns the current system time in ticks.
TIMETUPLE.
• Many of python's time functions handle time as a tuple of 9 numbers
as show below.
GETTING CURRENT TIME.
• To translate a time instant from a seconds floating point value into a
time-tuple, pass the floating-point value to a function that returns a
time-tuple with all nine items valid.
GETTING FORMATTED TIME.
• You can format any time as per your requirement, but simple method
to get time in readable format is asctime().
GETTING CALENDAR FOR A MONTH.
• The calendar module gives a wide range of methods to play with
yearly and monthly calendars.
THE TIME MODULE.
• There is a popular time module available in python which provides
functions for working with times and for converting between
representations.
THE TIME MODULE.
• There are also 2 important attributes available with the time module.
THE CALENDAR MODULE.
• The calendar module supplies calendar-related functions, including
functions to print a text calendar for a given month or year.
• By default, calendar takes Monday as the first day of the week and
Sunday as the last one.
• To change this, call calendar.setfirstweekday() function.
THE CALENDAR MODULE.
• Here is a list of functions available with the calendar module.
DECORATORS.
• Decorators allows you to decorate a function.
• Imagine you craeted a function.

• Now you want to add some new capabilities to the function.


DECORATORS.
• Now you have 2 options here.
• Add that extra code to your new function.
• Create a brand new function that contains the old coed and then add the new
code to that.
• But what if you then want to remove that extra “functionality”.
• you would need to delete it manually or make sure to have the old
functions.
• Is there a better way ? may be a on/off switch to quickly add this
functionality.
DECORATORS.
• Python has “decorators” tha allow you to tack on extra functionality
to an already existing function.
• They use the “@” operator and are then placed on top of the original
function.
• So you can easily add on extra functionality with a decorator.
FROZENSET.
• Frozen set is just an immutable version of python set.
• While elements of a set can be modified at any time, elements of a
frozen set remains the same after creation.
• Due to this, frozen set can be used as a key in dictionary or as element
of another set.
• The frozenset() is a built-in function in python which takes an iterable
object as input and makes them immutable.
• Simple it freezes the iterable objects and maken them unchangeable.
FROZENSET.
• Syntax :
• iterable can be a list, tuple, set, etc.
REGULAR EXPRESSIONS - SPLIT.
• split() method returns a list of strings after breaking the given string
by the specified separator.
• If it is not provided then any white space is a seperator.
• Syntax :
• Separator : Optional, specifies the separator to use when splitting.
• Maxsplit : Optional, specifies how many time the splits should
happen.
REGULAR EXPRESSIONS - SPLIT.

• When maxsplit is specified, the list will contain the specified number
of elements plus one.
WORKING WITH SPECIAL CHARACTERS.

• Python provides a bunch of special characters that you can use to


work with python.
WORKING WITH SPECIAL CHARACTERS.
WORKING WITH EMAILS IN
PYTHON.
• Simple Mail Transer Protocol (SMTP) is a protocol, which handles
sending emails and routing email between mail servers.
• Python provides 'smtplib' module, which defines an smtp client
session object that can be used to send email to any internet machine
with an SMTP or ESMTP listener daemon.
• syntax :
WORKING WITH EMAILS IN
PYTHON.
• Host : Host running your SMTP server. You can specify IP address of the host or a
domain name. This is optional argument.
• Port : If you are providing 'host' argument, then you need to specify a port, where
SMTP server is listening. Usually this port would be 25.
• Local_hostname : If your smtp server is running on your local machine, then you
can specify just 'localhost' as of this option.
• An SMTP object has an instance method called 'sendmail', which is typically used
to do the work of mailing a message. It takes 3 parameters.
• Sender : A string with the address of the sender.
• Receiver : A list of strings, one for each recipient.
• Message : A meesage as a string formatted as specified in the various RFCs (Request for
Comments).
WORKING WITH EMAILS IN
PYTHON.
WORKING WITH EMAILS IN
PYTHON.
REGULAR EXPRESSIONS.
• A RegEx or Regular Expressions is a sequence of characters that forms a search
pattern.
• RegEx is used to check if a string contains the specified search pattern.
• Python has a built-in package called 're' which can be used to work with the
regular expressions.

• When you have imported the 're' module, you can start using regular expressions.
REGULAR EXPRESSIONS.
• The 're' module offers a set of functions that allows us to search a
string for a match.
• findall : Returns a list contianing all the 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 more matches with a string.
REGULAR EXPRESSIONS.
• Python provides the below meta-characters with a special meaning.
REGULAR EXPRESSIONS.
• Findall() : Returns a list containing all the matches.

• The list will contains the matches in the order they are found.
• If no matches are found, an empty list will be returned.
REGULAR EXPRESSIONS.
• Search() : Searches the string for a match and returns a Match Object
if there is a match.
• If there is more than one match, only the first occurence of the match
will be returned.

• If there is no match, the value 'none' is returned.


REGULAR EXPRESSIONS
• Split() : Returns a list where the string has been split at each match.
REGULAR EXPRESSIONS.
• Sub() : Replaces the matches with the text of your choice.

• You can control the number of replacements by specifying the


“count” parameter.
REGULAR EXPRESSIONS.
• Match Object : A Match Object is an object containing information about the
search and the result.

• The Match Object has properties and methods used to retrieve information about
the search and the result.
• .span() : Returns a tuple containing the start and end positiong of the match.
• .string : Returns a string passed into the function.
• .group() : Returns the part of the string where there was a match.
REGULAR EXPRESSIONS.

• If there is no match, the value 'none' will be returned, instead of the


Match Object.
REGULAR EXPRESSIONS.
• Special sequences : A special sequence is a “\” followed by one of the
following characters in the list and has a special meaning.
THREADS IN PYTHON.
• Threading in python is used to run multiple threads (tasks, function calls) at the
same time.
• Python threads are used in cases where the execution of a task involves some
waiting.
• One example would be interaction with a service hosted on another computer
such as webserver.
• Running several threads is similar to running several diferent programs
concurrently but with the following benefits.
• Multiple threads within a process share the same data space with the same thread and can
therefore share information or communicate with each other more easily than if they were
seperate processes.
• Threads are sometimes called light-weight processes and they do not require much memory
overhead, they are cheaper than processes.
THREADS IN PYTHON.
• A thread has a beginning, an execution sequence and
a conclusion.
• It has an execution pointer that keeps track of where
within its context it is currently running.
• It can be pre-empted (interuppted).
• It can temporarily be put on hold (also known as sleeping)
while other threads are running - this is called yielding.
STARTING A NEW THREAD.
• To spawn another thread, you need to call following method available
in “thread” module.

• This method call enables fast and efficient way to create new threads
in both linux and windows.
• The method call returns immediately and the child thread starts and
call function with the passed list of args. When function returns, the
thread terminates.
• Here, args is a tuple of arguments, use an empty tuple to call function
without passing any arguments. kwargs is an optional dictionary of
keyword arguments.
STARTING A NEW THREAD.
THE THREADING MODULE.
• The threading module provides the below methods,
• threading.active(count) : Returns the number of thread objects that are active.
• threading.currentThread() : Returns the number of thread objects in the caller's thread
control.
• threading.enumerate() : Returns a list of all thread objects that are currently active.
• run() : Is an entry point for a thread.
• start() : Starts a thread by calling the run method.
• join([time]) : Waits for threads to terminate.
• isAlive() : Checks whether a thread is still executing.
• getName() : Returns the name of the thread.
• setName() : Sets the name of the thread.
CREATING THREAD USING THREADING MODULE.

• To implement a new thead using the threading module, you have to


do the following.
• Define a new subclass of the Thread class.
• Override the __init__(self[,args]) method to add additional arguments.
• Then, override the run(self[,args]) method to implement what the thread
should do when started.
• Once you have created the new thread subclass, you can create an
instane of it and then start a new thread by invoking the start(), which
in turn will call the run() method.
CREATING THREAD USING THREADING MODULE.
SYNCHRONIZING THREADS.
• The threading module provided with python includes a simple to implement locking mechanism
that allows you to synchronize threads.
• A new lock is created by calling the “Lock()” method, which returns the new lock.
• The “acquire(blocking)” method of a new lock object is used to force threads to run
synchronously.
• The optional “blocking” parameter enables you to control whether the thread waits to acquire
the lock.
• If “blocking” is set to “0”, the thread returns immediately with a “0” value if the lock cannot be
acquired and with a “1” if the lock was acquired.
• If blocking is set to “1”, the thread blocks and wait for the lock to be released.
• The “release()” method of the new lock object is used to release the lock when it is no longer
required.
SYNCHRONIZING THREADS.
MULTITHREADED PRIORITY QUEUE.
• The queue module allows you to create a new queue object that can
hold a specific number of items.
• These are the following methods to control the queue.
• get() : Removes and returns an item from the queue.
• put() : Adds item to a queue.
• qsize() : Returns the number of items that are currently in the queue.
• empty() : Returns True if queue is empty, otherwise False.
• full() : Returns True if queue is full, otherwise False.
MULTITHREADED PRIORITY QUEUE.
DJANGO.
• Django is a web application framework written in python programming language.
• It is based on MVT (Model View Template) design pattern. The Django is very
demanding due to its rapid development feature. It takes less time to build
application after collecting client requirement.
• By using Django, we can build web applications in very less time.
• Django is designed in such a manner that it handles much of configuration things
automatically, so we can focus on application development only.
DJANGO FEATURES.
• Rapid development : Designed with the intention to make a framework which takes less time to
build the web application.
• Secure : Avoids many securty mistakes such as SQL injection, cross-site scripting, etc.
• Scalable : Scalable in nature and has ability to quickly and flexibly switch from small to large
applications.
• Fully loaded : Takes care of authentication, content administration, site mapps, RSS feeds, etc.
• Versatile : Allows to build applications for different domain like Content management system,
social networks, etc.
• Open source : Publicly available without cose.
• Vast and supported community : Wide supportive community and channels to share and
connect.
DJANGO INSTALLATION.
• You can download Django from the official site -
https://www.djangoproject.com/
• Django requires pip to start installation.Pip is a package manager
which is used to install and manage packages written in python.
• pip3 install django==3.0.3
• You can verify the installation as below.
• import django
• print (django.get_version())
WORKING WITH DJANGO.
• To create a project in Django, we can use the following command where
“projectname” is the name of the project of the Django application.
• django-admin startproject <projectname>
• cd <projectname>
• tree
• A Django project contains the following packages and files.
• manage.py : It is a command-line utility which allows to interact with the project
in various ways and also used to manage an application.
• The directory located inside is the actual application package name
• __init__.py : It is an empty file that tells to the python that this directory should
be considerd as a python package.
WORKING WITH DJANGO.
• settings.py : This file is used to configure application settings such as
database connection, static files linking, etc.
• urls.py : This file contains the listed URLs of the application. In this
file, we can mention the URLs and corresponding actions to perform
the task and display the view.
• wsgi.py : It is an entry-point for WSGI (Web Server Gateway Interface)
compatible web servers to serve Django project.
RUNNING THE DJANGO PROJECT.
• Django project has a built-in development server which is used to run
the application isntantly without any external web server.
• It means we do not need Apache or any other web server to run the
application in development mode.
• To run the application, we use the following command.
• python3 manage.py runserver
• You can access the application using localhost:8000
DJANGO APPLIACTION.
• Django application consists of project and app, it also generated an
automatic base directory for the app, so we can focus on writing the
code rather than creating app directories.
• The difference between a projecy and app is, a project is a collection
og configuration files and apps where as the app is a web application
which is written to perform business logic.
• To create an app, run the below command.
• python3 manage.py startapp myapp
DJANGO APPLIACTION.
• views.py

• urls.py
DJANGO APPLIACTION.
• Once you are done making the changes, run the below command to
start the server,
• python3 manage.py runserver
• Then you can access the app by running the below url,
• localhost:8000/hello

You might also like