Overview of Al: ML & DL
2
Training TWO
Basics of python programming
Training Hrs. 24 hrs.Training -
Basics of Python Programming
Python is a general-purpose programming language that is becoming ever
more popular for data
ience. Companies worldwide are using Python to
harvest insights from their data and gain a competitive edge. Python’s sim-
ple, easy to learn syntax emphasizes readability and therefore reduces the
cost of program maintenance. Python supports modules and packages, which
encourages program modularity and code reuse. The Python interpreter and
the extensive standard library are avaiTrainingle in source or binary form
without charge for all major platforms, and can be freely distributed. In this,
training, you'll learn about powerful ways to store and manipulate data,
and helpful data science tools to begin conducting your own analyses.
Training —2 Objectives
In this Training, trainees will learn:
¥ Computer programming with Python
v Fundamentals of how programming works
v Data Types, Operators and Strings
Y Collection Types: Tuple, List, Dictionary to store data
v Function and Lambda to reuse code
Y Object Oriented Programming with Classes
VY Modules, namespace and libraries
¥ Test Driven Development by Unit Test
Y Files Input and Output including JSON, CSV and Binary
¥ Web Scraping
Y SQLite Database Connectivity
Copyright 2023 FC, BiT eBasics of Python Programming
Training—2 Prerequisite
Trainees need to have basic skills in computer programming, script pro-
gramming and Java.
Training—2 Outlines and duration
No. | Training items Training mode Duration | Remark
1 |Int. to python programming| Theoretical Thr Noiellink
& Installation of python
2 [Python basics Practical Shs Noteshands-on
exercise
3 [Looping & Control state-|Practical Shes hands-on exer-
ments ose
4 |Python, tuples, lists and|Practical Shs Tpands-on exer-
dictionaries one
3 [Functions and packages __ | Practical 3 bis Thands-on exer-
cise
6 |Self-exercise Practical Thrs | Trainees own
example
Total duration 24 hrs
2.1.
Installing python on windows
On Windows machin
a Python installation is usually placed in C:\Users\
UserName\AppData\Local\Programs\Python\Python(Version), although you can
change this while running the installer.
To install Python on a Windows machine, follow these steps
@
@
Download Python for Windows (check the property of your windows)
Run the Python installer
Here you will see the Python wizard, which is very easy to use. Just ac-
cept the default recommended settings and click on the Next button, wait
until the install is complete and you are done.
Copyright 2023 FC, BiT (a0)Basics of Python Programming
iB Python 3.80 (68-bit Setup 7 x
Install Python 3.8.0 (64-bit)
Select Install Now to install Python with defauit settings, or choose
Customize to enable or disable features.
@ Install Now
C\Users eB app ata\Lo
Customize installation
Choose location and feetures
thon
ps install launcher forall users (recommencled)
windows ClAd¢ Python 3.8 to PATH [Cancel
2.2. Python GUI
There are various GUI based Python IDE that python programmers can use
for better coding experience. Some of Python interpreters are:
© Python IDLE
PyCharm
®
© The Python Bundle
® pyGUI
®
Sublime Text etc.
Copyright 2023 FC, BiT GpBi
of Python Programming
2.3. Basics of Python programming
Python is an interpreted programming language. Python source code is com-
piled to bytecode as a .py or .pye file, and this bytecode can be interpreted
There are two modes for using the Python interpreter:
1. Interactive Mode
2. Script Mode
© Interactive mode
Without passing the python script file to the interpreter, directly execute
code to Python prompt
Example:
D>>24+6
Output:
® Script mode
Alternatively, programmers can store Python script source code in a file
with the .py extension, and use the interpreter to execute the contents of the
file. To execute the script by the interpreter, you have to tell the interpreter
the name of the file. For example, if you have a script name MyFile.py and
youre working on Unix, to run the script you have to type:
python MyFile.py
Copyright 2023 FC, BiT (2)Basics of Python Programming
2.3.1. The first python program
Example
print(“Hello, World!”)
Output
Hello, World!
2.3.2. Comments in python
Comments are non-executable statements in Python. It means neither the
python compiler nor the python Virtual Machine (PVM) will execute them.
Comments are intended for human understanding, not for the compiler or
PVM. Therefore they are called non-executable statements. There are two
types of commenting features avaiTrainingle in Python: These are sin-
gle-line comments and multi-line comments.
2.3.3.
ingle-Line Comment
A single-line comment begins with a hash (#) symbol and is useful in men-
tioning that the whole line should be considered as a comment until the end
of the line.
Example:
#Defining a variable to store number.
n = 50 #Store 50 as value into variable n.
© In the above example program, the first line starts with the hash symbol,
so the entire line is considered a comment.
© In the second line of code, “N = 50” is a statement, and after the state-
ment, the comment begins with the # symbol. From the # symbol to the
end of this line, the line will be treated as a comment.
Copyright 2023 FC, BiT asBasics of Python Programming
2.3.4. Multi-Line Comment
Multi-line comment is useful when we need to comment on many lines. In
Python Triple double quote (“””) and single quote (*’) are used for Multi-
line commenting. It is used at the beginning and end of the block to com-
ment on the entire block. Hence it is also called block comments.
Example:
Author: www.w3schools.in
Description:
Writes the words Hello World on the screen.
Author: www.w3schools.in
Description:
Writes the words Hello World on the screen
2.3.5. Indentation in Python
Indentation in Python refers to the (spaces and tabs) that are used at the be-
ginning of a statement. The statements with the same indentation belong to
the same group called a suite. Consider the example of a correctly indented
Python code statement mentioned below.
Copyright 2023 FC, BiT aaBasics of Python Programming
Example:
if
print(a)
if b=:
print(»)
print(‘end’)
In the above code, the first and last line of the statement is related to the
same suite because there is no indentation in front of them. So after ex-
ecuting first “if statement”, the Python interpreter will go into the next
statement. If the condition is not true, it will execute the last line of the
statement. By default, Python uses four spaces for indentation, and the programmer can
manage it.
2.3.6. Python keywords
Keywords are reserved words in Python and used to perform an internal op-
cration. All the keywords of Python contain lower-case letters only.
and assert in
del else Taise
from if continue
not pass finally
while yield is
as break return
clit cxcept der
global import __|for
oF print Tambda
with class try
exer
Copyright 2023 FC, BiT Gas)Bi
2.3.7. Operators In python
of Python Programming
Python programming language is rich with built-in operators
Python supports the following types of operators:
v Arithmetic Operators
Y Assignment Operators
Y Comparison (Relational) Operators
Y Logical Operators
¥ Membership operators
© Arithmetic Operators
Symbol | Operator Name Description
Adds the values on either side of the op-
+ Addition
erator and calculate a result.
Subiracts values of right side operand|
- Subtraction
from left side operand.
_ Multiplies the values on both sides of
* Multiplication
the operator.
oe Divides left side operand with right side
if Division
operand.
Tt returns the remainder by dividing the|
% Modulus : :
left side operand with right side operand|
+ Exponent Calculates the exponential power
Here the result is the quotient in which
a Floor Division |the digits after decimal points are not
taken into account.
‘Copyright 2023 FC, BiTBasics of Python Programming
© Assignment Operators
Symbol | Operator Name Description
= Equal Assigns the values of the right side operand to
the left side operand.
+= Add AND Adds right-side operand value to the left side
operand value and assigns the results to the
left operand.
Subtract AND
Subtracts right-side operand value to the left
side operand value and assigns the results to
the left operand.
Multiply AND
Division AND
Modulus AND
Exponent AND
Similarly does their respective operations and
assigns the operator value to the left operand.
© Comparison operators
Symbol
Operator Name |Description
Double Equa
1 If the two value of its operands are equal,
then the condition becomes true, other-
wise false
or=>
Not Equal To {If two operand’s values are not equal,
then the condition becomes true. Both the
operators define the same meaning and
function
Equal To
> Greater Than If the value of the left-hand operand is
greater than the value of right-hand oper-
and, the condition becomes true.
=z Less Than Tf the value of the left-hand operand is
less than the value of the right operand,
then the condition becomes true.
= Less Than Equall[f the value of the left-hand operand is
To less than or equal to the value of right-
hand operand, the condition becomes true.
— Greater Than|If the value of the left-hand operand is
greater than or equal to the value of right-
hand operand, the condition becomes true.
‘Copyright 2023 FC, BiTBasics of Python Programming
© Logical operators
Symbol [Operator Name |Description
or Logical OR Tf any of the two operands are non-ze-
ro, then the condition is true
and Logical AND _|If both the operands are true, then
the condition is true.
not Logical NOT _|It is used to reverse the logical state
of its operand.
© Membership operators
Symbol | Operator Name] Description
in in The result of this operation becomes True
if it finds a value in a specified sequence
& False otherwise
not in not in result of this operation becomes True if]
it doesn’t find a value in a specified se-
quence and False otherwise
2.3.8. Python data types
Python data types are different in some aspects from other programming
languages. It is simple to understand and easy to use. Because Python is
interpreted programming language and Python interpreter can determine
which type of data is storing, so no need to define the data type of memory
location.
Everything in Python programming is an object, and each object has its own
unique identity (a type and a value). There are many native(built-in) data
types avaiTrainingle in Python.
Some important data types in python are:
© Numbers: An are integers (such as 1, 2, 3...), floats (such as 2.6, 4.8, ete.),
fractions (such as ¥. %, ete.), or even complex numbers.
Y int (signed integer)
Y float
Copyright 2023 FC, BiT Gs)@
®@ ©9008 O©8@
Basics of Python Programming
Y long
Y complex
Sequences:
Y Strings: Sequence of Unicode characters, like an HTML document.
Vv Bytes/Byte array: Any type of file.
Y Lists: An ordered sequence of values.
V Tuples: An ordered, immutable sequence of values.
Boolean: Holds either true or false values.
Sets: An unordered container of values.
Dictionaries: A key-paired values set in an unordered way.
Module
Function
Class
Method
File
2.3.9. Variables in python
In Python, like many other programming languages, there is no need to de-
fine variables in advance. As soon as a value is assigned to a variable, it is
automatically declared. This is why Python is called a dynamically typed
language
Example:
nane = “Packing box” # A string
neignt = 10 # An integer assignment
width = 20.5 #A floating point
print (name)
print (neigne)
print («iatn)
Copyright 2023 FC, BiT aof Python Programming
Output:
Packing box
10
20.5
2.4. Control statements in python
Python provides various types of conditional statements: if statement, If
Else statement and nested statements
2.4.1. If statement
Syntax:
if expression!
#execute your code
Example:
a=15
ifa>10:
print(“a is greater”)
Output:
a is greater
2.4.2. if else Statements
if expression:
#execute your code
else:
#execute your code
Copyright 2023 FC, BiT (20)Basics of Python Programming
Example:
a=15
b=20
ifa>b:
print(“a is greater”)
else:
print(“b is greater”)
Output:
b is greater
2.4.3. elif statements
elif - is a keyword used in Python replacement of else if to place another
condition in the program. This is called chained conditional.
Syntax:
if expression:
#execute your code
elif expression:
#execute your code
else:
#execute your code
Example:
a=15
b=15
ifa>b:
print(“a is greater”)
elif a == b:
print(“both are equal”)
else:
print(“b is greater”)
Output:
both are equal
Copyright 2023 FC, BiT (a)Basics of Python Programming
2.5. Loops in python
Python provides three types of looping techniques: for loop, while loop and
nested loops
2.5.1. For loop
Synta’
for iterating_var in sequence:
#execute your code
Example
for letter in ‘Python’:
print (‘Current letter is:’, letter)
Outpu
Current letter is : P
Current letter is : y
Current letter is: t
Current letter is: h
Current letter is : 0
Current letter is : n
5.2. While loop
while expression:
#execute your code
Example:
“initialize count variable to 1
count =1
while count < 6 :
print (count)
count+=1
Copyright 2023 FC, BiT (22)Output:
Basics of Python Programming
2.5.3. Nested loop
for iterating_var in sequence:
for iterating_var in sequence:
#execute your code
#execute your code
2.6. Arrays and Strings in python
A string
played to users. It is known to Python when you want to display a string.
This is because programmers use either double quote « or single quote « to
is usually a bit of text in programming that is written to be dis-
enclose a word or group of words to express a string
Example:
ch = “Hello Python”
strl = “String Chapter”
print (“First value is: “, ch)
print (“Second value is: “, strl)
print (“First single sub-string is: “, ch[0])
print (“Set of sub-string is: “, str1[2:5])
‘Copyright 2023 FC, BiTof Python Programming
Output:
First value is: Hello Python
Second value is: String Chapter
First single sub-string is: H
Set of sub-string is: rin
2.7. Functions in python
Using a ‘def’ statement for defining a function is the corner store of a ma-
jority of programs in Python. To group a set of statements, programmers
use functions, and they can be run more than once in a program. They act
like a pack of instructions that is invoked by a name
Example 1:
def avrg(cizst, *rests
return (first + sum(sests)) / (1 + len(cests))
# calling functions
print (avra(1, 2)
print (avra(1, 2, 3))
print (avro(1,2,3,4))
Output:
15
2.0
2.5
Copyright 2023 FC, BiTBasics of Python Programming
Example 2:
def karlos():
return 1, 2, 3
a, b, ¢ = karlos()
print (a)
print (b)
print (c)
Output:
2.8. Lists in python
Dealing with data in a structured format is quite generous, and this is pos-
sible if those data are set accordingly in a specific manner. So, Python
provides these data structures named ‘lists’ and ‘tuples’ that are used to
organize data in a single set. Python has six built-in sequences, and among
them, the most famous is “lists and tuples”.
To build a list, just put some expressions in square brackets. The syntax is:
Syntax:
isti = [] # stl is the name of the list
ist2 = [expressionl , ... , expression N]
Example:
istl = [‘computerse’, ‘IT’, ‘CSE"];
1st2 = [1993, 20161;
1st3 = [2, 4, 6, “9%, “k", "s"]7
Copyright 2023 FC, BiT (@s)Basics of Python Programming
2.8.1. Accessing list values
List apply the standard interface sequence in which len(L) returns the num-
ber of items present in the list, and L[i] represents the item at index i. Also
L[i:j] returns new list containing objects within ‘i’ and ‘j’.
Example:
asti = [‘computerse’, ‘IT’, ‘CSE”];
ast2 = [1993, 2016];
[2, 4, 6, “g”, “Kk”, “s”];
print (“Ist1[0]”, 1¢2[0])
1st3
print (“Ist3[2:4]”, 1s:3[2:4])
Output:
Ist1 [0] computerse
1st3[2:4] [6, ‘g’]
2.8.2. Updating Lists
Program to show how to add/update single or multiple elements in a list:
Example:
isti = [‘computerse’, ‘IT’, ‘CSE’];
print (“Second value of the list is:”)
print (1s¢i[1])
isti[l] = ‘Robotics’
print (“Updated value in the second index of list is:”)
print (1st2[1])
Output:
Second value of the list is:
11
Updated value in the second index of list is:
Robotics
Copyright 2023 FC, BiT 8)Basics of Python Programming
2.8.3. Delete Elements from Lists
To remove an element from the list, we can use the del-statement. The syn-
tax for deleting an clement from a list is:
Syntax:
del List_name[index_va1];
2.9. Tuples in python
Tuples are immutable lists and cannot be changed in any way once it is cre-
ated. Tuples are defined in the same way as lists. They are enclosed within
parenthesis and not within square braces.
2.9.1. Accessing values from tuple
Example
tupl1 = (‘computerse’, ‘IT’, ‘CSE”);
tupl2 = (1993, 2016);
tupl3 = (2, 4, 6, 8, 10, 12, 14, 16);
print (“tupl1[0]”, tupl1[0])
print (“tupl3[2:4]”, tupl3[2:4])
Output:
tupl1[0] computerse
tupl3[2:4] (6, 8)
2.9.2. Updating Tuples
They are immutable, i.e., the values can’t be changed directly. So we can
just update by joining tuples. Let’s demonstrate this with an example:
Copyright 2023 FC, BiT ®of Python Programming
Example:
tupll = (2, 3, 4);
tupl2 = (‘ab’, ‘ed”);
tupl3 = tupl1 + tupl2
print (tupl3)
This code snippet will execute a combination of two tuples using the “+”
operator,
Output:
(2, 3, 4, ‘ab’, ‘ed’)
2.9.3. Delete Elements from Tuples
To delete a tuple, we can use the del-statement.
syntax:
del tuple_name;
Example:
tupl3 = (2, 4, 6, 8, 10, 12, 14, 16);
del tup|3;
2.10. Dictionary in python
Dictionary is like a list but in a general form. It can think like this; a dic-
tionary is a mapping between a set of indexes or keys with a set of values,
where each key maps to a value. A combination of a key and its value is
called a key-value pair or item. in the Python dictionary, each key is sepa-
rated by a colon (:) from its values. Commas separate all the items, and the
whole dictionary is enclosed within ‘{* and ‘}’. In the dictionary, all the
keys should have to be unique with data type as strings, tuples, or numbers,
and the values can be of any of these three types.
Copyright 2023 FC, BiT e@Basics of Python Programming
2.10.1. Defining a dictionary
dicto = {‘Bookname’ : ‘Python’, ‘Price’ : 210}
2.10.2. Accessing Dictionary Values
Dictionaries’ values can be accessed by using the square braces, i.e. [ ],
along with the key name to obtain the value. This are multiple item decla-
ration procedures used to declare keys along with their values in Python’s
dictionary.
Example:
dicto = {‘Bookname’ : ‘Python’, ‘Price’ : 210}
print (dicto[ ‘Bookname’])
print (dicto[‘Price’])
Output:
Python
260
‘Copyright 2023 FC, BiT os