Introduction to Python Programming
Introduction to Python Programming
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.
•
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.
• Example :
THE IF STATEMENT (ALSO KNOWN AS DECISION MAKING).
• Example :
THE IF STATEMENT (ALSO KNOWN AS DECISION MAKING).
• 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:
• 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.
• 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.
• 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 :
• 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.
• 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 :
• 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.
• 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.
• 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.
• 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.
• When maxsplit is specified, the list will contain the specified number
of elements plus one.
WORKING WITH SPECIAL CHARACTERS.
• 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.
• 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.
• 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.
• 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