Python For Artificial Intelligence
Python For Artificial Intelligence
Intelligence
By Pavan Khandare
(Data Scientist and AI Trainer)
INDEX
• How to install Jupyter
• What are Jupyter notebook
• Python introduction
• Identifiers, Keywords and Indentation
• Comments and Documentation in python
• Data types : Numbers, Strings, List, Tuple, Set, Dictionary
• Control and loops structure
• Functions in Python
• 1) Built-in 2) User define 3) Anonymous
• Range, Generators, Iterators, Comprehensions & Lambda Expression
• Python Modules and Packages
• Reading, Writing and appending various files into python
• Error handling in python
• Python regular expression
• Database connection using python
• And many more………..
How to install Jupyter
• To install Jupyter into your system you must be sure that python is
installed.
• To install python, go to https://www.python.org/downloads/
• Download the latest version of python and instal it.
• Then go to command prompt of and type python, you will get an
output with python version that is installed.
• Go to command prompt and then make sure that pip is installed with
Python and to check that type pip in the command prompt. If it
throws no error, then there is pip installed in your system.
• Once you confirm pip is installed in system again in command prompt
type pip install notebook and Jupyter notebook will be install.
• But if there is any error then make sure you are login as administrator
in your system, if not type python –m pip install notebook
• Go to command prompt and type notebook, your default browser
will open with localhost
Run your first python program in Jupyter
notebook
• Go to Jupyter notebook and click dropdown menu named New then
go to Python3
Python Introduction
• Python is a high-level, general-purpose programming language.
• Python is currently the most widely used multi-purpose, high-level
programming language.
• Python allows programming in Object-Oriented & Procedural paradigms.
• Python programs generally are smaller than other programming languages
like Java. Programmers must type relatively less and indentation
requirement of the language, makes them readable all the time.
• Python language is being used by almost all tech-giant companies like –
Google, Amazon, Facebook, Instagram, Dropbox, Uber… etc.
Features of Python
• Interpreted
• Platform independent
• Free and open source
• High level language
• Simple
• Embeddable
• Robust
• Reach library support
Identifiers, Keywords and Indentation
• Keywords in Python are reserved words that can not be used as a
variable name, function name, or any other identifier.
• False, None, True, and, as, assert, async, await, break, class, continue,
def, del, elif, else, except, finally, for, from, global, if, import, in, is,
lambda, nonlocal, not, or, pass, raise, return, try, while, with, yield
• By using keyword library’s kwlist function you can find all this
keywords.
• Indentation is a very important concept of Python because without
proper indenting the Python code, you will end up
seeing IndentationError and the code will not get compiled.
• A Python identifier is a name used to identify a variable, function, class,
module or other object. An identifier starts with a letter A to Z or a to z or
an underscore (_) followed by zero or more letters, underscores and digits
(0 to 9).
• Python does not allow punctuation characters such as @, $, and % within
identifiers. Python is a case sensitive programming language.
Thus, Manpower and manpower are two different identifiers in Python.
• Here are naming conventions for Python identifiers −
• Class names start with an uppercase letter. All other identifiers start with a lowercase
letter.
• Starting an identifier with a single leading underscore indicates that the identifier is
private.
• Starting an identifier with two leading underscores indicates a strongly private
identifier.
• If the identifier also ends with two trailing underscores, the identifier is a language-
defined special name.
Comments and Documentation in python
• Comments in Python are the lines in the code that are ignored by the
compiler during the execution of the program. Comments enhance the
readability of the code and help the programmers to understand the code
very carefully.
• Types of comments in Python – Single line, Multiline, Docstring Comments
Python – Data types
• Numeric • Sequence Type
1. Integer 1. String
2. Float 2. List
3. Tuple
3. Complex Number
• Dictionary
Every value in Python has a datatype. Since
• Boolean everything is an object in Python
• Set programming, data types are actually classes
and variables are instance (object) of these
classes.
Python Numbers
• Integer, floating point numbers and complex numbers fall under
Python numbers category.
• They are defined as int, float and complex classes in python.
• We can use the type() function to know which class a variable or a
value belongs to.
• Similarly, the isinstance() function is used to check if an object
belongs to a particular class.
• Integers can be of any length; it is only limited by the memory
available.
• A floating-point number is accurate up to 15 decimal places. Integer
and floating points are separated by decimal points. 1 is an
integer, 1.0 is a floating-point number
Complex numbers are written in the form, x + yj, where x is the real part
and y is the imaginary part.
Python List
• List is an ordered sequence of
items. It is one of the most used
datatype in Python and is very
flexible. All the items in a list do
not need to be of the same type.
• In list item separated by commas
are enclosed within brackets [ ].
• We can use the slicing operator [
] to extract an item or a range of
items from a list. The index starts
from 0 in Python.
• Lists are mutable, meaning, the value of elements of a list can be
altered.
Python Tuple
• Tuple is an ordered sequence of items same as a list. The only
difference is that tuples are immutable. Tuples once created cannot
be modified.
• Tuples are used to write-protect data and are usually faster than lists
as they cannot change dynamically.
• It is defined within parentheses ( ) where items are separated by
commas.
• We can use the slicing operator [ ], to extract items but we cannot
change its value.
Python Strings
• String is sequence of Unicode characters. We can use single quotes or
double quotes to represent strings. Multi-line strings can be denoted
using triple quotes.
• Just like a list and tuple, the slicing operator [ ] can be used with
strings. Strings, however, are immutable.
Python Set
• Set is an unordered collection of
unique items. Set is defined by values
separated by comma inside braces { }.
Items in the set are not ordered.
• We can perform set operations like
union, intersection on two sets. Sets
have unique values. They eliminate
duplicates.
• Since, set are unordered collection, indexing has no meaning. Hence,
the slicing operator does not work.
Python Dictionary
• Dictionary is an unordered collection of key-value pairs.
• It is generally used when we have a huge amount of data. Dictionaries
are optimized for retrieving data. We must know the key to retrieve
the value.
• In Python, dictionaries are defined within braces { } with each item
being a pair in the form key:value. Key and value can be of any type.
• We use key to retrieve the respective value. But not the other way
around.
Conversion between data type
• We can convert between
different data types by
using different type
conversion functions like
int(), float(), str().
• Conversion from float to
int will truncate the value
(make it closer to zero).
• Conversion to and
from string must
contain compatible
values.
• We can even convert
one sequence to
another.
• To convert to
dictionary, each
element must be a
pair:
Loops in Python
• The main advantages of using loops in python is that it saves your
time, you don’t have to write the same code every time to perform
the same functionality; also loops make your code look clean.
• Types of Loops in python
1. For Loop
2. While Loop
3. Do-While Loop
While Loop
• A while loop
in python continues to
execute the code if the
given condition is true,
if it becomes false, then
the loop stops.
• Another reason to use
while loop is when we
aren’t sure about how
many times to iterate.
For Loop
• For loop is a python
loop which repeats
a group of
statements for a
given number of
times. It is always a
good practice to use
the for loop when
we know the
number of
iterations.
Nested Loops
• Python supports
using the nested
loop that is a loop
within a loop. The
following example
is an explanation
of how a nested
loop works.
Control Statement in Python
• control statements change the way we execute a loop from its
normal behavior. There are many types of control statements in
python that you can use to control the loops:
• Break Statement
• Continue Statement
• Pass Statement
Break Statement
• Break statement is used to
terminate or abandon the loop.
Once the loop breaks then the
next statement after
the break continues. The main
reason we could use the break
statement is to take a quick exit
from a nested loop (i.e. a loop
within a loop).
The break statement is used with
both while and for loop.
Example of Break Statement
Example of Continue statement
Pass Statement
• The pass statement is used when
comment cannot be printed to
show the program’s status to the
programmer. It is always going to
be a null operation. For example, if
a programmer has written a
comment within the code, then
that comment will be ignored but
the pass statement won’t be
ignored. It will be used as a
placeholder.
Functions in python
• Functions help break our program into smaller and modular chunks.
As our program grows larger and larger, functions make it more
organized and manageable.
• Keyword def that marks the start of the function header.
• A function name to uniquely identify the function. Function naming
follows the same rules of writing identifiers in Python.
• Parameters (arguments) through which we pass values to a function.
They are optional.
• A colon (:) to mark the end of the function header.
• Optional documentation string (docstring) to describe what the
function does.
• One or more valid python statements that make up the function
body. Statements must have the same indentation level (usually 4
spaces).
• An optional return statement to return a value from the function.
Built-in Functions
• One of the reasons for which Python is preferred over the other
languages is the huge collection of built-in functions. You would have
come across some of these like print(), int(), etc
• These get stored in the interpreter and come into action when they
are called. These can be accessed from any part of the program. The
Python 3.6 version has 69 built-in functions
• Learn more about Built-Functions on link provided below.
• Built-in Functions in Python - Python Geeks
User Define Functions
• The user defined functions are the function that grants the user the
access and write their own custom logics. This UDF is registered in
Python session and can be used in the code function in Python.
• The def is used to declare the function in Python. The custom logic is
defined inside the Python UDF function, which can be used further as
the user defined function and can be applied to elements needed.
• The function takes up arguments called as a parameter in Python that
works as the input for the logics to be used in. This user defined
function can take up some variable and returns the result that can be
stored back in a variable in Python and then can be used for analysis
function.
• Once defined, the functions can be used further anytime in a Python
session that can accept multiple inputs further and process results.
• This makes the code encapsulated, and the reuse of code becomes
easier in the Python library.
Anonymous Functions in Python
• These functions are called anonymous because they are not declared
in the standard manner by using the def keyword. You can use
the lambda keyword to create small anonymous functions.
• Lambda forms can take any number of arguments but return just one
value in the form of an expression. They cannot contain commands or
multiple expressions.
• An anonymous function cannot be a direct call to print because
lambda requires an expression
• Lambda functions have their own local namespace and cannot access
variables other than those in their parameter list and those in the
global namespace.
• Although it appears that lambda's are a one-line version of a function,
they are not equivalent to inline statements in C or C++, whose
purpose is by passing function stack allocation during invocation for
performance reasons.
Range, Generators, Iterators,
Comprehensions in Python