Predictive Analytics
Data440 – Intro to python
Reeta Suman © 2024
Python for data analytics
• Python is a programming language frequently used for
data analysis and data visualization.
• The Python interpreter is a computer program that
executes Python code .
• An interactive interpreter is a program that allows
the user to execute one line of code at a time.
Python development environments:
➢ Visual Basic
➢ Jupyter Notebook [ Anaconda ]
➢ Colab
➢ Cloud9
Reeta Suman © 2024
Data types
Type Description Examples
int An integer number. 0, -1, 4
2.7168, -
float A decimal number or number in scientific notation.
2.0, 1.618, 6.02e23, 1.60e-19
A sequence of characters (stored and output surrounded
string 'Hello', 'pie', '3.14'
by single or double quotes).
boolean A value that is either true or false. True, False
Reeta Suman © 2024
Data Structures
Type Description Examples
{1, 2, 3}, { 'First name', 'Last name'
set An unordered collection of items.
}
An ordered collection of changeable items.
[1, 2, 3], ['Height', 6.1], [ [1, 2], [3,
list Two-dimensional arrays can be formed from
4] ]
lists of lists.
tuple An ordered collection of unchangeable items. (1, 2, 3), ('Hello', 'World')
{'Home': '310-555-5555', 'Office':
A collection of mappings between keys and
dictionary (or dict) '951-555-5555'}, {'C': 'do', 'D': 're',
values.
'E': 'mi', 'F': 'fa', 'G': 'sol'}
Reeta Suman © 2024
Common Python data visualization
and analysis modules
Module name Alias Description
numpy np Mathematical functions, required by other libraries
scipy.stats st Statistical functions
pandas pd Data frames, statistical functions
matplotlib.pyplot plt Data visualization
scikit-learn sks Machine learning and data analysis
seaborn sns Data visualization
Reeta Suman © 2024
Statements
• Statement: a command/instruction/task that the
programmer writes and gives to the computer to
perform
➢ Example: y = -10
print(“Hello”)
• A program is a set of statements/commands
Reeta Suman © 2024
Assignment statements
• Creation of a variable and assigning a value to it using the
assignment symbol =
• Example: a = 6
b=4
a+b
10
sum = a + b
sum
10
• The = symbol is not an operator. The right side of the = executes
first then the result is assigned to the variable on the left
• Remark: Good practice is to insert one space on both sides of the
operators like =, +, …
Reeta Suman © 2024
Arithmetic Expression
• Expression is combination of variables, operators,
parenthesis that evaluate the value
• e.g. Mass-Energy equivalence equation E=mc2
• Task: What is Arithmetic expression for E=mc2
Reeta Suman © 2024
Getting an Integer input from the User
• If you need to read an integer from the user, you should
convert the string to an integer using built-in int function
• Ex: age = input(“How old are you ? “ )
How old are you? 20
age = int(age)
print (age)
20
• You should convert the inputs to int type if you want to use
them as integers, otherwise, they are treated as strings.
E.g. adding 2 strings concatenates them not add them
Reeta Suman © 2024
Exercise - Real Estate Summary
• Write a program with two inputs, current price and last
month's price (both integers). Then, output a
summary listing the price, the change since last month,
and the estimated monthly mortgage computed as
(current_price * 0.051) / 12.
• Task 1
• Identify the inputs
• Choose meaningful names
• Types of variables
Reeta Suman © 2024
Exercise - Real Estate Summary
Task 2
• Math operations or Expression
• What formula I need?
• Example:
• Change_price = current_price - last_months_price
• Monthly_Mortgage=(current_price * 0.051) / 12
Reeta Suman © 2024
Exercise - Real Estate Summary
• Task 3 - Outputs
• What are the outputs?
• Listing the price,
• The change since last month
• The estimated monthly mortgage
Reeta Suman © 2024
Comparison operators
Algebraic operator Python operator Sample condition Meaning
> > x>y x is greater than y
< < x<y x is less than y
≥ >= x >= y x is greater than or equal
to y
≤ <= x <= y x is less than or equal to
y
= == x == y x is equal to y
≠ != x != y x is not equal to y
Reeta Suman © 2024
Conditions
• A condition is a Boolean expression with the value True
or False
• True and False are Python Keywords
• Comparison operators are used to create conditions
• Example:
In [1]: 8 > 3
Out[1]: True
In [2]: 8 < 3
Out[2]: False
Reeta Suman © 2024
Equality operator == not =
• Using the assignment symbol (=) instead of the
equality operator (==) in an if statement’s condition is
a common syntax error. To help avoid this, read == as
“is equal to” and = as “is assigned.” You’ll see in the
next chapter that using == in place of = in an
assignment statement can lead to subtle problems.
Reeta Suman © 2024
Control Statements
• Python provides three selection statements that
execute code based on a condition that evaluates to
either True or False:
• The if statement performs an action if a condition is True or
skips the action if the condition is False.
• The if…else statement performs an action if a condition is
True or performs a different action if the condition is False.
• The if…elif…else statement performs one of many different
actions, depending on the truth or falsity of several
conditions.
Reeta Suman © 2024
Decision Making: The if Statement
• Syntax: if test_expression:
statement(s)
• The program evaluates the test_expression and will
execute statement(s) only if the test_expression is
True
• If the test_expression is False, the statement(s) are
not executed
• An “test_expression” is a logical condition. It’s value is
True or False
• The body of the if block is indicated by indentation and
is called a suite
Reeta Suman © 2024
Decision Making: The if Statement
• Example: if number1 == number2:
print(number1, 'is equal to', number2)
• If the condition is True, print “number1, 'is equal to',
number2”
Reeta Suman © 2024
If-else statement
• The if…else statement performs an action if a
condition is True or performs a different action if the
condition is False.
Syntax: if experssion1: Example:
#statements If x > 10:
Else: num_val = 100
#statements else:
num_val = 50
Reeta Suman © 2024
Multi-branch if-else statements
• The if…elif…else statement performs one of many
different actions, depending on the truth or falsity
of several conditions.
Syntax: if experssion1:
Example: if num == 1:
#statements
print(" first year ")
elif expression2:
elif num == 2:
#statements
print("second year")
else:
else:
#statements
print("third year")
Reeta Suman © 2024
Precedence rules for arithmetic, logical
and relational operators
Operator/convention Grouping Description
() Left to right Parentheses evaluate first
** Right to left Exponentials
*/%+- Left to right Arithmetic operator
< <= > >= == != Left to right Relational, (in)quality and membership operator
not Not (logical NOT)
and Logical AND
or Logical or
Reeta Suman © 2024
Logical operators
• Write an expression that prints "Eligible" if user_age is
between 18 and 25 inclusive, else prints "Ineligible".
Example:
user_age = int(input())
if (user_age >= 18) and (user_age <= 25):
print('Eligible')
else:
print('Ineligible')
Reeta Suman © 2024
loops
• A loop is a set of statements that repeatedly executes
while the loop's expression is true and exits when
false. Each time the program loops through the
statements called iteration.
Reeta Suman © 2024
While Statement
• The while statement allows you to repeat one or more
actions while a condition remains True.
• Example expression:
• while expression: # Loop expression
• # Loop body: Sub-statements to execute
• # if the loop expression remains True
•
• # Statements to execute when the expression
become False
Reeta Suman © 2024
While Statement
• Example:
In [1]: product = 3
In [2]: while product <= 50:
product = product * 3
In [3]: print (product)
Out[3]: 81
Reeta Suman © 2024
For Statement
• The for statement allows you to repeat an action or
several actions for each item in a sequence of items.
• Example expression :
• for variable in container:
• # Loop body: Sub-statements to execute
• # for each item in the container
•
• # Statements to execute after the for loop is
complete
Reeta Suman © 2024
For statement
• Problem:
• Example:
weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri’ ]
Weekends = [‘sat’, ‘sun’]
for weekday in weekdays:
print(weekday)
Reeta Suman © 2024
Nested for loop
• Problem: Given the number of rows and the number of
columns, write nested loops to print a rectangle.
Example:
num_rows = int(input())
num_cols = int(input())
for rows in range(num_rows):
for cols in range(num_cols):
print('*', end=' ')
print()
Reeta Suman © 2024
Built-In range function
• Let’s use a for statement and the built-in range
function to iterate precisely 10 times, displaying the
values from 0 through 9:
• Example:
for counter in range(10):
print(counter, end=' ')
Output:
0123456789
Reeta Suman © 2024
Built-In Function range: A Deeper Look
range(y) range(3) generates a sequence of all non- 0,1,2
negative integers less than Y.
range(x,y) range(-7, -3) generates a sequence of all integers >= X -7, -6, -5, -4
and < Y.
range(X, Y, Z) range(0, 50, 10) where Z is positive, generates a 0, 10, 20, 30, 40.
sequence of all integers >= X and
< Y, incrementing by Z
range(X, Y, Z) range(3, -1, -1) where Z is negative, generates a 3, 2, 1, 0
sequence of all integers <= X and > Y,
incrementing by Z
Reeta Suman © 2024
Break Statement
• Break Statement : Executing a break statement in a while or
for immediately exits that statement. In the following code,
range produces the integer sequence 0–99, but the loop
terminates when number is 10:
Example: for number in range(100):
if number == 10:
break
print(number, end=' ')
Output
0123456789
Reeta Suman © 2024
Continue Statement
• Continue statement : Executing a continue statement
in a while or for loop skips the remainder of the loop’s
suite. In a while, the condition is then tested to
determine whether the loop should continue executing.
In a for, the loop processes the next item in the
sequence (if any):
Example: for number in range(10):
if number == 5:
continue
print(number, end=' ')
Output
012346789
Reeta Suman © 2024
Loop else construct
• Sometime a loop can include an else clause that
executes only if the loop terminates normally, and it is
optional. We use else when we are not using a break
statement.
Reeta Suman © 2024
Lists
• List is a comma-separated collection of items enclosed
in square brackets [ ]. Each sequence has an iterator.
• We will be learning about lists in detail in coming
sessions
• Ex:
In [3]: total = 0
In [4]: for number in [2, -3, 0, 17, 9]:
total = total + number
Print(total)
Out[5]: 25
Reeta Suman © 2024
Functions
• Function – is a block code which only runs when it is
called
• Parameter/argument - information or data that passed
to the function
• Parameter is the variable inside the parenthesis in function
• An argument is the value that is sent to the function
• Python has two types of functions:
• Built-in functions
• User-defined functions
Reeta Suman © 2024
Functions
• Built-in functions:
• int, float, print, input, type, sum, len, min and max
• statistics module (mean, median and mode, Each performed
a single, well-defined task.
• User defined functions: user can define function
using def as follows
def square(number): #defining function
#Calculate the square of number
return number ** 2
square(7)
Reeta Suman © 2024
Functions
• A function begins with the def keyword, followed by
the function name (square), a set of parentheses and a
colon (:).
• function names should begin with a lowercase letter
and in multiword names underscores should separate
each word.
Reeta Suman © 2024
Functions
• Parameters: The required parentheses contain the
function’s parameter list—a comma-separated list
of parameters representing the data that the function
needs to perform its task.
Reeta Suman © 2024
Functions
• When a function finishes executing, it returns control to
its caller—that is, the line of code that called the
function. In square’s block, the return statement:
return number ** 2
Reeta Suman © 2024
Functions
def celsius_to_kelvin(value_celsius): value_c = 10.0
value_kelvin = 0.0
print(value_c, 'C is',
value_kelvin = value_celsius + 273.15 celsius_to_kelvin(value_c), 'K')
return value_kelvin
def kelvin_to_celsius(value_kelvin): value_k = float(input())
value_celsius = 0.0 print(value_k, 'K is',
value_celsius = value_kelvin - 273.15 kelvin_to_celsius(value_k), 'C')
return value_celsius
Reeta Suman © 2024
Functions - modules
• A programmer may find themselves writing the same function over and over again
in multiple scripts
• A solution is to use a module, which is a file containing Python code that can be
imported and used by scripts or other modules
• To import a module means to execute the code contained by the module, and
make the definitions within that module available for use by the importing program
Reeta Suman © 2024
Create your own module
Reeta Suman © 2024