Python for Machine Learning
Python for Machine Learning
Introduction to Python
Dr. Ajay James
Asst. Professor in CSE
Government Engineering College Thrissur
Introduction
• Created by Guido van Rossum in 1991
• Works on different platforms (Windows, Mac,
Linux, Raspberry Pi, etc)
• Python has a simple syntax similar to the
English language
• Runs on an interpreter system
– code can be executed as soon as it is written.
– prototyping can be very quick.
• Python can be treated in a procedural way, an
object-oriented way or a functional way.
Python Installation
• Python Install
– To check if you have python installed on a Windows
PC, search in the start bar
– To check if you have python installed on a Linux or
Mac, then on linux open the command line or on Mac
open the Terminal and type:
python --version
• If you find that you do not have python installed
on your computer, then visit
https://www.python.org/
How to use Python?
• Interactive shell
• IDLE
• Editors
• Online (colab, kaggle etc.)
Running code in the interactive shell
• Python expressions and statements can be run
in the interactive shell
• Launch IDLE
• Examples
– 35 + 32
– "hello world "
– name = "Abin Thomas "
– " Hi, How are you? " + name
– print ('Hi, How are you?')
– print ("hi, how are you", name)
Input, Processing and Output
• Interactive shell – Keyboard and terminal
• print (<expression>)
• print ('Hi, How are you?')
• print (<expression>, ... , <expression>)
• print (<expression>, end=“”)
Input
• <variableƒidentifier> = input (<a string prompt>)
• name = input ("Enter your name")
• name
• print (name)
• Steps
– Displays a prompt for the input
– Receives a string of keystrokes, called characters,
entered at the keyboard and returns the string to the
shell
Type Conversion
• input function always builds a string from the
user’s keystrokes
• programmer must convert them from strings to
the appropriate numeric types
• two type conversion functions – int and float
– first = int(input("Enter the first number: "))
– second = int(input("Enter the second number: "))
– print("the sum is: ", first + second)
Summary of basic functions
Reference
• Fundamentals of Python – Kenneth A Lambert,
B L Juneja
Python for Machine Learning – 2
Editing, Saving and Running a Script
Dr. Ajay James
Asst. Professor in CSE
Government Engineering College Thrissur
Editing, Saving and Running a Script
• To compose, edit, and save longer, more
complex programs in files
• program files or scripts
• Run within IDLE or from the operating
system’s command prompt without opening
IDLE.
Steps
• Select the option New Window from the File
menu of the shell window
• In the new window, enter Python expressions or
statements on separate lines, in the order in
which you want Python to execute them
• At any point, you may save the file by selecting
File/Save. If you do this, you should use a .py
extension
• To run this file of code as a Python script, select
Run Module from the Run menu or press the F5
key (Windows) or the Control+F5 key (Mac or
Linux)
Behind the Scenes: How Python Works
Detecting and Correcting Syntax Errors
• typographical errors when editing programs
• syntax errors
• halts execution with an error message
Exercises - 1
1. Open a Python shell, enter the following expressions, and observe the
results:
a8
b8*2
c 8 ** 2
d 8 / 12
e 8 // 12
f8/0
2. Write a Python program that prints (displays) your name, address, and
telephone number.
3. Evaluate the following code at a shell prompt: print(“Your name is”,
name). Then assign name an appropriate value, and evaluate the
statement again.
4. Open an IDLE window, and enter the program that computes the area of
a rectangle. Load the program into the shell by pressing the F5 key, and
correct any errors that occur. Test the program with different inputs by
running it at least three times.
Exercise - 1
5. Modify the program of Exercise 4 to compute the area of
a triangle. Issue the appropriate prompts for the
triangle’s base and height, and change the names of the
variables appropriately. Then, use the formula .5 * base *
height to compute the area. Test the program from an
IDLE window.
6. Write and test a program that computes the area of a
circle. This program should request a number
representing a radius as input from the user. It should use
the formula 3.14 * radius ** 2 to compute the area, and
output this result suitably labeled.
7. Write and test a program that accepts the user’s name
(as text) and age (as a number) as input. The program
should output a sentence containing the user’s name and
age.
Exercise - 1
8. Enter an input statement using the input
function at the shell prompt. When the
prompt asks you for input, enter a number.
Then, attempt to add 1 to that number,
observe the results.
9. Enter an input statement using the input
function at the shell prompt. When the
prompt asks you for input, enter your first
name, observe the results.
Reference
• Fundamentals of Python by Kenneth Lambert
Python for Machine Learning – 3
Strings, Assignment, and Comments
Dr. Ajay James
Asst. Professor in CSE
Government Engineering College Thrissur
Introduction
• Text Processing is the most common
application
• Use of strings
• Documentation
Data Types
• Example – On 8th Friday, I took Python class from
GEC, Thrissur
• In computer programs – type of data is important
• What operations can be done on these data?
• Data type
– Consists of a set of values and a set of operations
• Literal
– The way a value of a data type looks to a programmer
Literals examples
String Literals
• Sequence of characters enclosed in single or
double quotation marks
• Examples
– 'hello there'
– "hello there "
–""
– ''
–" "
String Literals Examples
• "I'm going to US tomorrow"
• print ( "I'm going to US tomorrow")
• print (""" this is a very long sentence
so i am printing in the next line""")
• """ this is a very long sentence
so i am printing in the next line"""
Escape Sequences
• \n is called an escape sequence
String Concatenation
• join two or more strings to form a new string
using the concatenation operator +
• Example
– "hi, " + "jacob" + " how are you"
• * operator allows you to build a string by
repeating another string a given number of
times
• Example
– " " * 10 + "i am fine"
Variables
• variable associates a name with a value
• variable name must begin with either a letter or an
underscore ( _),
• can contain any number of letters, digits, or other
underscores
• variable names are case sensitive (weight/WEIGHT)
• typically use lowercase letters (area, interestRate)
• use all uppercase letters for the names of variables
that contain values that the program never changes
– Symbolic constants (TAX_RATE, PI)
Assignment Statement
• Variables receive their initial values and can be
reset to new values with an assignment
statement
• <variable name> = <expression>
• Example
– firstName = "Bill"
– secondName = "Clinton"
– fullName = firstName + " " + secondName
– fullName
Program Comments and Docstrings
• comment is a piece of program text that the
interpreter ignores
• useful documentation to programmers
Exercise - 2
1. Let the variable x be “dog” and the variable y be
“cat”. Find the values returned by the following
operations:
a) x + y
b )“the “ + x + “ chases the “ + y
c )x * 4
2. Write a string that contains your name and
address on separate lines using embedded
newline characters. Then write the same string
literal without the newline characters.
Reference
• Fundamentals of Python by Lambert
Thank You
Python for Machine Learning – 4
Numeric Data Types and Character Sets
Dr. Ajay James
Asst. Professor in CSE
Government Engineering College Thrissur
Integers
• include 0, all of the positive whole numbers,
and all of the negative whole numbers
• are written without commas
• a leading negative sign indicates a negative
value
• range of integers is infinite
• –2,147,483,648 (–231) to 2,147,483,647 (231 – 1)
Floating-Point Numbers
• Real numbers
• Real numbers have infinite precision
• floating-point numbers to represent real
numbers
• –10308 to 10308 and have 16 digits of precision
• can be written using either ordinary decimal
notation or scientific notation
Floating-Point Numbers
Character Sets
• character literals look just like string literals
and are of the string type
• belong to several different character sets,
among them the ASCII set and the Unicode
set
ASCII
Character set
• ord
– Function converts characters to their numeric ASCII
codes
• char
– Function converts numeric ASCII codes to characters
– chr(ord('A') + 3)
Reference
• Fundamentals of Python – Kenneth Lambert
Thank You
Python for Machine Learning – 5
Expressions
Dr. Ajay James
Asst. Professor in CSE
Government Engineering College Thrissur
Expressions
• provide an easy way to perform operations on
data values to produce other data values
• an expression’s operands are evaluated
• its operator is then applied to these values to
compute the value of the expression
Arithmetic Expressions
Precedence rules
• Exponentiation has the highest precedence and is
evaluated first
• Unary negation is evaluated next, before
multiplication, division, and remainder
• Multiplication, both types of division, and remainder
are evaluated before addition and subtraction
• Addition and subtraction are evaluated before
assignment
• Operations of equal precedence are left associative
– Exception - Exponentiation and assignment operations
are right associative
• Parentheses can change the order of evaluation
Arithmetic expression examples
Arithmetic expression
• When both operands of an arithmetic expression
are of the same numeric type (int, long, or float),
the resulting value is also of that type
• When each operand is of a different type, the
resulting value is of the more general type.
– float type is more general than the int type
• quotient operator // produces an integer
quotient ( 3//4 = 0)
• the exact division operator / always produces a
float ( 3/4 = .75)
Mixed-Mode Arithmetic and Type
Conversions
• Performing calculations involving both
integers and floating-point numbers is called
mixed-mode arithmetic
• 3.14 * 3 ** 2
– 3.14 * 9.0
Type Conversion functions
Exercise - 3
1. Let x = 8 and y = 2. find the values of the following
expressions:
a) x + y * 3
b) (x + y) * 3
c) x ** y
d) x % y
e) x / 12.0
f) x // 6
2. Let x = 4.66. Find the values of the following expressions:
a) round(x)
b) int(x)
3. Assume that the variable x has the value 55. Use an
assignment statement to increment the value of x by 1.
Reference
• Fundamentals of Python by Kenneth Lambert
Thank You
Python for Machine Learning – 6
Functions and Modules
Dr. Ajay James
Asst. Professor in CSE
Government Engineering College Thrissur
Functions and modules
• Python includes many useful functions
• Organized in libraries of code called modules
Calling Functions: Arguments and
Return Values
• Function is a chunk of code that can be called by
name to perform a task
• Functions require arguments, that is, specific
data values, to perform their tasks
• Arguments are also known as parameters
• When a function completes its task, the function
may send a result back to the part of the program
• Process of sending a result back to another part
of a program is known as returning a value
Function examples
• round(6.5)
• abs(4 – 5)
• print(abs(4 - 5) + 3)
• Optional arguments and required arguments
• round(7.563, 2)
• help(round)
The math Module
• Functions and other resources are coded in
components called modules
– import math
– dir(math)
– math.pi
– math.sqrt(2)
– help(math.cos)
– from math import pi, sqrt
– print(pi, sqrt(2))
– from math import *
Program Format and Structure
• Start with an introductory comment stating
the author’s name, the purpose of the
program, and other relevant information
• Include statements that do the following:
– Import any modules needed by the program
– Initialize important variables, suitably commented
– Prompt the user for input data and save the input
data in variables
– Process the inputs to produce the results
– Display the results
Running a Script from a Terminal
Command Prompt
• Windows – command prompt
• Linux/mac – terminal
• python scriptName.py
Exercise - 4
1. You can calculate the surface area of a cube if
you know the length of an edge. Write a
program that takes the length of an edge (an
integer) as input and prints the cube’s surface
area as output.
2. Five Star Video rents new videos for $3.00 a
night, and oldies for $2.00 a night. Write a
program that the clerks at Five Star Video can
use to calculate the total charge for a customer’s
video rentals. The program should prompt the
user for the number of each type of video and
output the total cost.
Exercise - 4
3. Write a program that takes the radius of a sphere (a
floating-point number) as input and outputs the
sphere’s diameter, circumference, surface area, and
volume.
4. An object’s momentum is its mass multiplied by its
velocity. Write a program that accepts an object’s
mass (in kilograms) and velocity (in meters per
second) as inputs and then outputs its momentum.
5. The kinetic energy of a moving object is given by the
formula KE=(1/2)mv2, where m is the object’s mass
and v is its velocity. Modify the program you created
in exercise 4 so that it prints the object’s kinetic
energy as well as its momentum.
Exercise - 4
6. Write a program that calculates and prints the number
of minutes in a year.
7. Light travels at 3 * 108 meters per second. A light-year
is the distance a light beam travels in one year. Write a
program that calculates and displays the value of a
light-year.
8. Write a program that takes as input a number of
kilometers and prints the corresponding number of
nautical miles. Use the following approximations:
– A kilometer represents 1/10,000 of the distance between
the North Pole and the equator.
– There are 90 degrees, containing 60 minutes of arc each,
between the North Pole and the equator.
– A nautical mile is 1 minute of an arc.
Exercise - 4
9. An employee’s total weekly pay equals the
hourly wage multiplied by the total number of
regular hours plus any overtime pay. Overtime
pay equals the total overtime hours multiplied
by 1.5 times the hourly wage. Write a program
that takes as inputs the hourly wage, total
regular hours, and total overtime hours and
displays an employee’s total weekly pay
Reference
• Fundamentals of Python by Kenneth Lambert
Thank You
Python for Machine Learning – 7
Control Statements – for loop
Dr. Ajay James
Asst. Professor in CSE
Government Engineering College Thrissur
Control statements - loops
• Loops - repetition statements
• Repetition of the action is known as a pass or
an iteration
• 2 types
– Definite iteration – defined no: of times
– Indefinite iteration – program determines
for loop
Count controlled loop
• Loops that count through a range of numbers
are called count controlled loops
Count controlled loop
Count controlled example
Augmented assignment
Loop Errors: Off-by-One Error
• Easy to write correctly
• Only one other possible error
– loop fails to perform the expected number of
iterations
– number is typically off by one
• Error is called an off-by-one error
• incorrectly specifies the upper bound of the
loop
Reference
• Fundamentals of Python by Kenneth Lambert
Thank You
Python for Machine Learning – 8
Control Statements – for loop (part 2)
Dr. Ajay James
Asst. Professor in CSE
Government Engineering College Thrissur
Traversing the Contents of a Data
Sequence
• Loop actually visits each number in a
sequence of numbers generated by the range
function
Traversing the contents of a data
sequence
Specifying the Steps in the Range
• We might want a loop to skip some numbers
• list(range(1,6,1))
• list(range(1,6,2))
• list(range(1,6,3))
• Example – count of even numbers till 10
Loops That Count Down
• counting in the opposite direction
• for count in range(10,0,-1):
print(count, end=" ")
• list(range(10,0,-1))
Else part in for loop
Exercise - 5
1. Write a loop that prints your name 100 times.
Each output should begin on a new line.
2. Write a loop that prints the first 128 ASCII values
followed by the corresponding characters
3. Assume that the variable testString refers to a
string. Write a loop that prints each character in
this string, followed by its ASCII value.
4. Find the output of the following statements
print(range(10))
print(list(range(10)))
print(list(range(2, 8)))
print(list(range(2, 20, 3)))
Reference
• Introduction to Python by Kenneth Lambert
Thank You
Python for Machine Learning – 9
Selection: if and if-else Statements
Dr. Ajay James
Asst. Professor in CSE
Government Engineering College Thrissur
Selection
• Computer might be faced with two alternative
courses of action
• Examine or test a condition
• Selection statements
Boolean Type, Comparisons, and
Boolean Expressions
• Boolean data type
• only two data values — true and false
COMPARISON OPERATOR MEANING
== Equals
!= Not equals
< Less than
> Greater than
<= Less than or equal
>= Greater than or equal
Examples
if-else Statements
• Called a two-way selection statement
Syntax of if- else stmt
One-Way Selection Statements
Multi-Way if Statements
• Testing several conditions
• More than two alternative courses of action
• Count down
while Loop Examples
• Example – 1 (while)
• Example – 2 (break and continue)
• Example - 3 (random)
• Example – 4 (else)
• Example – 5 (leap year)
• Example – 6 ( largest)
• Example – 7 (prime)
• Example – 8 (factorial)
• Example – 9 (fibonacci)
Exercise - 7
1. Write a program that accepts the lengths of
three sides of a triangle as inputs. The program
output should indicate whether or not the
triangle is an equilateral triangle or right
triangle.
2. Modify the guessing-game program discussed so
that the user thinks of a number that the
computer must guess. The computer must make
no more than the minimum number of guesses.
Exercise - 7
3. The greatest common divisor of two positive integers, A
and B, is the largest number that can be evenly divided
into both of them. Euclid’s algorithm can be used to find
the greatest common divisor (GCD) of two positive
integers. You can use this algorithm in the following
manner:
– Compute the remainder of dividing the larger number by the
smaller number.
– Replace the larger number with the smaller number and the
smaller number with the remainder.
– Repeat this process until the smaller number is zero
– The larger number at this point is the GCD of A and B
– Write a program that lets the user enter two integers and
then prints each step in the process of using the Euclidean
algorithm to find their GCD.
Exercise - 7
4. Write a program that receives a series of
numbers from the user and allows the user to
press the enter key to indicate that he or she
is finished providing inputs. After the user
presses the enter key, the program should
print the sum of the numbers and their
average.
Exercise - 7
5. Write a Python code to check whether a given
year is a leap year or not.
[An year is a leap year if it’s divisible by 4 but
not divisible by 100 except for those divisible
by 400].
6. Write a Python code to print prime numbers
between an interval.
Exercise - 7
7. Write a Python program to find the factorial of a
number.
8. Write a program to display the Fibonacci
sequence up to n-th term.
A Fibonacci sequence is the integer sequence of 0,
1, 1, 2, 3, 5, 8....
The first two terms are 0 and 1.
All other terms are obtained by adding the
preceding two terms. This means to say the nth
term is the sum of (n-1)th and (n-2)th term.
Exercise - 7
9. Write a program to check if the number is an
Armstrong number or not
abcd... = an + bn + cn + dn + ...
153 = 1*1*1 + 5*5*5 + 3*3*3 // 153 is an
Armstrong number.
Reference
• Fundamentals of Python by Kenneth Lambert
Thank You
Python for Machine Learning – 11
Strings
Dr. Ajay James
Asst. Professor in CSE
Government Engineering College Thrissur
Introduction
• String – compound data type
• Made up of smaller pieces – characters
• String is a sequence of zero or more characters
• Immutable data structure
– internal elements can be accessed
• Substring
– portion of a string
Length of a string
• Length – number of characters it contains
h i j a c k .
0 1 2 3 4 5 6 7
Subscript Operator
Example
• name = "Steve Jobs"
S t e v e J o b s
0 1 2 3 4 5 6 7 8 9
-10 -9 -8 -7 -6 -5 -4 -3 -2 -1
Example
Slicing for Substrings
• Segment of a string is called a slice
• dir(str)
• help(str)
String Methods
String Methods
String Methods
Reference
• Fundamentals of Python by Kenneth Lambert
Thank You
Python for Machine Learning – 14
Functions
Dr. Ajay James
Asst. Professor in CSE
Government Engineering College Thrissur
Function
• A block of organized, reusable code that is
used to perform a single, related action
• Provide better modularity for your application
• High degree of code reusing
Function
• Functions are not necessary
• If no function –
– Difficult to verify
– Impossible to maintain
• Humans can remember only 3 – 7 things
• Abstraction
Use of functions
• Functions Eliminate Redundancy
• Functions Hide Complexity
Use of functions
• Functions support general methods with
systematic variations
• Functions support the division of labour
Function Syntax
def FunctionName (parameters):
statement(s)
return [expression]
Defining a function
• Keyword def marks the start of function header
• Function name - to uniquely identify it
• Parameters (arguments) through which we pass
values to a function (optional)
• A colon (:) to mark the end of function header
• One or more valid python statements that make
up the function body (must have same
indentation level)
• An optional return statement to return a value
from the function
Example
Calling a Function
• Execute it by calling it from another function
or directly from the Python prompt
return Statement
• Used to exit a function and go back to the place
from where it was called
• Syntax of return
return [expression_list]
• Expression
– gets evaluated and the value is returned
• If no expression or the return statement itself is
not present
– function will return the None object
Example
Scope of variables
• Scope of a variable - the portion of a program
where the variable is recognized
• Parameters and variables defined inside a
function is not visible from outside
• Local scope
• Example
Lifetime of a variable
• Period throughout which the variable exits in
the memory
• Lifetime of variables inside a function is as
long as the function executes
• Destroyed once the function is returned
• Function does not remember the value of a
variable from its previous calls
• Example
Examples
• Example – 1 (add)
• Example – 2 (prime)
• Example – 3 (calculator)
Reference
• Fundamentals of Python by Kenneth Lambert
Thank you
Python for Machine Learning – 15
Functions – Part 2 (Function
Arguments, Higher order functions and
lambda function)
• filter function
Higher order functions and lambda
• map function
• reduce function
References
• Fundamentals of Python by Kenneth Lambert
• https://www.programiz.com/
• https://www.tutorialspoint.com/
Thank you
Python for Machine Learning – 16
Functions – Part 3 (Recursive
Functions)
• Repeat (*)
Tuple Methods
• count(x)
– Return the number of items that is equal to x
• index(x)
– Return index of first item that is equal to x
Tuple operations
• In operator
• Example – 1
• Example - 2
Tuple vs List
• Use tuple for heterogeneous (different)
datatypes
• Use list for homogeneous (similar) datatypes
• Iterating through tuple is faster than with list
• Tuples that contain immutable elements can
be used as key for a dictionary
• If you have data that doesn't change,
implementing it as tuple will guarantee that it
remains write-protected
References
• Fundamentals of Python by Kenneth Lambert
• https://www.geeksforgeeks.org/
• Learning with Python by Allen Downey
Thank You
Python for Machine Learning – 21
Sets, Creating, Modifying and
Removing elements
intersection_update() Updates the set with the intersection of itself and another
Methods
isdisjoint() Returns True if two sets have a null intersection
{'x': [11, 12, 13, 14, 15, 16, 17, 18, 19],
'y': [21, 22, 23, 24, 25, 26, 27, 28, 29],
'z': [31, 32, 33, 34, 35, 36, 37, 38, 39]}
15
25
35
References
• Fundamentals of Python by Kenneth Lambert
• https://www.programiz.com/
Thank you
Python for Machine Learning – 25
Object Oriented Programming -1
• writelines() :
– For a list of string elements, each string is inserted
in the text file
– Used to insert multiple strings at a single time
Reading from a file
• read()
– Returns the read bytes in form of a string
– Reads n bytes, if no n specified, reads the entire file
• readline() :
– Reads a line of the file and returns in form of a string.
– For specified n, reads at most n bytes.
– Does not reads more than one line, even if n exceeds
the length of the line
• readlines() :
– Reads all the lines and return them as each line a
string element in a list
Appending to a file
• Example
References
• www.geeksforgeeks.org
Thank You
Python for Machine Learning – 34
sys module