0% found this document useful (0 votes)
100 views

M1 - Python For Machine Learning - Maria S

The document discusses a Python programming course that covers programming environment setup, Python basics like data types, operators, input/output, and a case study on building an income tax calculator program including requirements analysis, design with pseudocode, coding, and testing the program. The course will teach students how to get started with Python, work with basic data types, write and run scripts, and understand the software development process through a practical example.

Uploaded by

shyam krishnan s
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
100 views

M1 - Python For Machine Learning - Maria S

The document discusses a Python programming course that covers programming environment setup, Python basics like data types, operators, input/output, and a case study on building an income tax calculator program including requirements analysis, design with pseudocode, coding, and testing the program. The course will teach students how to get started with Python, work with basic data types, write and run scripts, and understand the software development process through a practical example.

Uploaded by

shyam krishnan s
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 46

Course Code : CST283

Category : Minor
Offered by : Dept. of Computer Science and Engg.
Faculty in charge : Jaseela Beevi S

Python for Machine Learning


Dept. of CSE, TKMCE 1
Syllabus - Module I

Programming Environment and Python Basics:


Getting Started with Python Programming - Running code in the interactive shell, Editing,
Saving, and Running a script. Using editors - IDLE, Jupyter. The software development process
- Case Study.

Basic coding skills - Working with data types, Numeric data types and Character sets, Keywords,
Variables and Assignment statement, Operators, Expressions, Working with numeric data, Type
conversions, Comments in the program. Input, Processing, and Output. Formatting output. How
Python works. Detecting and correcting syntax errors. Using built in functions and modules in
math module.

Dept. of CSE, TKMCE 2


Introduction to Python
• Guido Van Rossum invented the Python programming language in the
early 1990s.
• high-level, interpreted, interactive and object-oriented scripting language.

üPython is Interpreted − Python is processed at runtime by the interpreter. You do


not need to compile your program before executing it.

üPython is Interactive − You can actually sit at a Python prompt and interact with
the interpreter directly to write your programs.

üPython is Object-Oriented − Python supports Object-Oriented style or technique


of programming that encapsulates code within objects.
Dept. of CSE, TKMCE 3
Characteristics of Python
• It supports functional and structured programming methods as well as OOP.

• It can be used as a scripting language or can be compiled to byte-code for


building large applications.

• It provides very high-level dynamic data types and supports dynamic type
checking.

• It supports automatic garbage collection.

• It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.

Dept. of CSE, TKMCE 4


Why Python ?

• Python has simple, conventional syntax.


• Python has safe semantics.
• Python scales well.
• Python is highly interactive.
• Python is general purpose.
• Python is free and is in widespread use in industry.

Dept. of CSE, TKMCE 5


Getting Started with Python Programming

You can download Python, its documentation from


http://www.python.org/download/

To launch an interactive session with Python’s shell from a terminal


command prompt, open a terminal window, and enter python or python3
at the prompt.

Dept. of CSE, TKMCE 6


Running Code in the Interactive Shell
• The easiest way to open a Python shell is to launch the IDLE. This is an
Integrated program DeveLopment Environment that comes with the
Python installation.
Help command
• help() - to get a list of available 'modules','keywords','symbols' or
'topics'
• help> modules
• help> keywords
• help> symbols
• help> topics

Quit Command
Leaving help and returning to the python interpreter
Dept. of CSE, TKMCE 7
Input, Processing, and Output
• In terminal-based interactive programs, the input source is the keyboard,
and the output destination is the terminal display.
Inputs : Python expressions or statements.
outputs : Results displayed in the shell.

output functions
üprint(<expression>) - Python first evaluates the expression and
then displays its value.
>>> print('Hi there')
Hi there

Dept. of CSE, TKMCE 8


input functions
üinput() - This function causes the program to stop and wait for the user
to enter a value from the keyboard.

name=input(“Enter your name: “)


Enter your name: Ken Lambert
>>> name
'Ken Lambert'
>>> print(name)
Ken Lambert
>>>

Dept. of CSE, TKMCE 9


• variable identifier, or variable for short, is just a name for a value. When
a variable receives its value in an input statement, the variable then
refers to this value.

>>> first = int(input(“Enter the first number: “))


Enter the first number: 23
>>> second = int(input(“Enter the second number: “))
Enter the second number: 44
>>> print(“The sum is”, first + second)
The sum is 67
>>>

Dept. of CSE, TKMCE 10


Dept. of CSE, TKMCE 11
Editing, Saving, and Running a Script
To compose and execute programs without opening IDLE, you perform the
following steps:
1. Select the option New Window from the File menu of the shell window.
2. In the new window, enter Python expressions or statements on separate lines,
in the order in which you want Python to execute them.
3. At any point, you may save the file by selecting File/Save. If you do this,
you should use a .py extension.
4. To run this file of code as a Python script, select Run Module from
the Run menu or press the F5 key (Windows).

Dept. of CSE, TKMCE 12


Behind the Scenes: How Python Works

Dept. of CSE, TKMCE 13


Steps in interpreting a Python program
1) The interpreter reads a Python expression or statement, also called the
source code, and verifies that it is well formed.

2) If a Python expression is well formed, the interpreter then translates it


to an equivalent form in a low-level language called byte code.

3) This byte code is next sent to another software component, called the
Python virtual machine (PVM), where it is executed. If another error
occurs during this step, execution also halts with an error message.

Dept. of CSE, TKMCE 14


The software development process
- Case Study.
Waterfall Model - Different Phases
1. Customer request—In this phase, the programmers receive a broad
statement of a problem that is potentially amenable to a computerized
solution. This step is also called the user requirements phase.

2. Analysis—The programmers determine what the program will do. This


is sometimes viewed as a process of clarifying the specifications for the
problem.

3. Design—The programmers determine how the program will do its task.


Dept. of CSE, TKMCE 15
4) Implementation—The programmers write the program. This step is
also called the coding phase.

5) Integration—Large programs have many parts. In the integration phase, these


parts are brought together into a smoothly functioning whole, usually not an easy
task.

6) Maintenance—Programs usually have a long life; a lifespan of 5 to15 years is


common for software. During this time, requirements change,
errors are detected, and minor or major modifications are made

Dept. of CSE, TKMCE 16


Dept. of CSE, TKMCE 17
CASE STUDY : INCOME TAX CALCULATOR

Request:
The customer requests a program that computes a person’s income tax.
Analysis:
Analysis often requires the programmer to learn some things about the problem
domain, in this case, the relevant tax law.

ü All taxpayers are charged a flat tax rate of 20%.


ü All taxpayers are allowed a $10,000 standard deduction.
ü For each dependent, a taxpayer is allowed an additional $3,000 deduction.
ü Gross income must be entered to the nearest penny.
ü The income tax is expressed as a decimal number.

Dept. of CSE, TKMCE 18


Another part of analysis determines what information the user will have to provide.
user inputs - gross income and number of dependents.
Design:
we describe how the program is going to do it.
This usually involves writing an algorithm - pseudocode

1) Input the gross income and number of dependents


2) Compute the taxable income using the formula
3) Taxable income = gross income - 10000 - (3000 * number of dependents)
4) Compute the income tax using the formula
5) Tax = taxable income * 0.20
6) Print the tax

Dept. of CSE, TKMCE 19


Implementation (Coding):
Given the preceding pseudocode, an experienced programmer would now find it
easy to write the corresponding Python program.

Testing:
Only thorough testing can build confidence that a program is working correctly.
Testing is a deliberate process that requires some planning and discipline on the
programmer’s part.

A correct program produces the expected output for any legitimate input.
Testing all of the possible combinations of inputs would be impractical. The
challenge is to find a smaller set of inputs, called a test suite, from which we can
conclude that the program will likely be correct for all inputs.

Dept. of CSE, TKMCE 20


# Initialize the constants
TAX_RATE = 0.20
STANDARD_DEDUCTION = 10000.0
DEPENDENT_DEDUCTION = 3000.0
# Request the inputs
grossIncome = float(input("Enter the gross income: "))
numDependents = int(input("Enter the number of dependents: "))
# Compute the income tax
taxableIncome = grossIncome - STANDARD_DEDUCTION - \
DEPENDENT_DEDUCTION * numDependents
incomeTax = taxableIncome * TAX_RATE
# Display the income tax
print("The income tax is $" + str(incomeTax))
If there is a logic error in the code, it will almost certainly be caught using these data.
Data Types
A data type consists of a set of values and a set of operations that can be
performed on those values.
A literal is the way a value of a data type looks to a programmer. The
programmer can use a literal in a program to mention a data value.

Dept. of CSE, TKMCE 23


String Literals
üIn Python, a string literal is a sequence of characters enclosed in single or double
quotation marks.
>>> 'Hello there!'
'Hello there!'
>>> "Hello there!"
'Hello there!'
>>> '' ''
>>> ""

üTo output a paragraph of text that contains several lines

>>> print("""This very long sentence extends


all the way to the next line.""")
This very long sentence extends
all the way to the next line.

Dept. of CSE, TKMCE 24


Escape Sequences
Escape sequences are the way Python expresses special characters, such as the tab,
the newline, and the backspace (delete key), as literals.

Dept. of CSE, TKMCE 25


• Variables and the Assignment Statement
a variable associates a name with a value, making it easy to remember and use the value later
in a program.
üa variable name must begin with either a letter or an underscore ( _)
ü can contain any number of letters, digits, or other underscores.
üpython variable names are case sensitive.

Programmers use all uppercase letters for the names of variables that contain values that the
program never changes. Such variables are known as symbolic constants.

assignment statement
<variable name> = <expression>
The Python interpreter first evaluates the expression on the right side of the assignment
symbol and then binds the variable name on the left side to this value. When this happens to
the variable name for the first time, it is called defining or initializing the variable.
Dept. of CSE, TKMCE 26
year = 2020
name = 'Ammu'

2020

memory Year
Ammu

Name

Dept. of CSE, TKMCE 27


Exercises

1. Let the variable x be "dog" and the variable y be "cat". Write the values returned
by the following operations:
a. x + y
b. "the " + x + " chases the " + y
c. x * 4

2. Which of the following are valid variable names?


a. length
b. _width
c. firstBase
d. 2MoreToGo
e. halt!
Dept. of CSE, TKMCE 28
Numeric Data Types and Character Sets
• Integers - the integers include 0, all of the positive whole numbers, and all of the
negative whole numbers. range : –231 to 231 – 1
• Floating - Point Numbers - A real number in mathematics, such as the value of pi
(3.1416…), consists of a whole number, a decimal point, and a fractional part.
range : –10308 to 10308
• Character Sets - ASCII set
The term ASCII stands for American Standard Code for Information Interchange.
In the 1960s, the original ASCII set encoded each keyboard character and several
control characters using the integers from 0 through 127.

Dept. of CSE, TKMCE 29


• A floating-point number can be written using either ordinary decimal notation or
scientific notation. Scientific notation is often useful for mentioning very large
numbers.

Dept. of CSE, TKMCE 30


Numeric Data Types and Character Sets

Dept. of CSE, TKMCE 31


Numeric Data Types and Character Sets
• The digits in the left column represent the leftmost digits of an ASCII code, and
the digits in the top row are the rightmost digits. Thus, the ASCII code of the
character 'R' at row 8, column 2 is 82.

• Python’s ord() and chr() functions convert characters to their numeric ASCII
codes and back again, respectively.
>>> ord('a')
97
>>> ord('A')
65
>>> chr(65)
'A'
>>> chr(66)
'B'

Dept. of CSE, TKMCE 32


Exercises

3. Write the values of the following floating-point numbers in Python’s scientific notation:
a. 355.76
b. 0.007832
c. 4.3212

4. write the ASCII values of the characters '$' and '&'.

Dept. of CSE, TKMCE 33


Arithmetic Expressions

Dept. of CSE, TKMCE 34


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.
ü With two exceptions, operations of equal precedence are left associative,
so they are evaluated from left to right.
Exponentiation and assignment operations are right associative, so consecutive
instances of these are evaluated from right to left.
ü You can use parentheses to change the order of evaluation

Dept. of CSE, TKMCE 35


Dept. of CSE, TKMCE 36
ü Syntax is the set of rules for constructing well-formed expressions or
sentences in a language.

üSemantics is the set of rules that allow an agent to interpret the


meaning of those expressions or sentences.

ü A computer generates a syntax error when an expression or sentence is


not well formed.

üA semantic error is detected when the action that an expression


describes cannot be carried out, even though that expression is
syntactically correct.

Dept. of CSE, TKMCE 37


Mixed-Mode Arithmetic and Type Conversions
Performing calculations involving both integers and floating-point numbers is called mixed-mode arithmetic.
• eg: >>> 3.14 * 3 ** 2
28.26
You must use a type conversion function when working with the input of numbers. A type conversion
function is a function with the same name as the data type to which it converts.
Because the input function returns a string as its value, you must use the function int or float to convert the
string to a number before performing arithmetic, as in the following example:

>>> radius = input("Enter the radius: ")


Enter the radius: 3.2
>>> radius
'3.2'
>>> float(radius)
3.2
>>> float(radius) ** 2 * 3.14
Dept. of CSE, TKMCE 38
32.153600000000004
Dept. of CSE, TKMCE 39
• Another use of type conversion occurs in the construction of strings from numbers
and other strings.

>>> profit = 1000.55


>>> print('$' + str(profit))
$1000.55
• Python is a strongly typed programming language. The interpreter checks data
types of all operands before operators are applied to those operands. If the type of
an operand is not appropriate, the interpreter halts execution with an error
message.

Dept. of CSE, TKMCE 40


Program Comments and Docstrings
• A comment is a piece of program text that the computer ignores but that provides
useful documentation to programmers. At the very least, the author of a program
can include his or her name and a brief statement about the program’s purpose at
the beginning of the program file. This type of comment, called a docstring, is a
multi-line string.

• End-of-line comments - These comments begin with the # symbol and extend to
the end of a line. An end-of-line comment might explain the purpose of a variable or
the strategy used by a piece of code.

Dept. of CSE, TKMCE 41


Exercises

5) Let x = 8 and y = 2. Write 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

6) Let x = 4.66 Write the values of the following expressions:


a. round(x)
b. int(x)

Dept. of CSE, TKMCE 42


Using Functions and Modules
• Python includes many useful functions, which are organized in libraries of code
called modules.
• A function is a chunk of code that can be called by name to perform a task.
Functions often require arguments, that is, specific data values, to perform their
tasks.
• Names that refer to arguments are also known as parameters.
• The process of sending a result back to another part of a program is known as
returning a value.
Ex. round(7.563,2) return 7.56
abs(4-5) returns 1
The above functions belons to __builtin__ module

Dept. of CSE, TKMCE 43


The math Module
• The math module includes several functions that perform basic mathematical
operations.
• This list of function names includes some familiar trigonometric functions as well as
Python’s most exact estimates of the constants pi and e.
ex: 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc'..... etc.
ü syntax for using specific function from math module
ex: math.pi, math.sqrt(2)
to import specific functions
ex: from math import pi, sqrt
üto import all of the math module’s resources
ex: from math import *

Dept. of CSE, TKMCE 44


Program Format and Structure
• Start with an introductory comment stating the author’s name, the purpose of
the program, and other relevant information. This information should be in the
form of a docstring.
• Then, 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.

Dept. of CSE, TKMCE 45


Thank you

Dept. of CSE, TKMCE 46

You might also like