SlideShare uma empresa Scribd logo
1 de 46
Python for Machine Learning
Course Code : CST283
Category : Minor
Offered by : Dept. of Computer Science and Engg.
Faculty in charge : Jaseela Beevi S
1
Dept. of CSE, TKMCE
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.
2
Dept. of CSE, TKMCE
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.
3
Dept. of CSE, TKMCE
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.
4
Dept. of CSE, TKMCE
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.
5
Dept. of CSE, TKMCE
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.
6
Dept. of CSE, TKMCE
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
7
Dept. of CSE, TKMCE
Quit Command
Leaving help and returning to the python interpreter
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
8
Dept. of CSE, TKMCE
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
>>>
9
Dept. of CSE, TKMCE
• 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
>>>
10
Dept. of CSE, TKMCE
11
Dept. of CSE, TKMCE
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).
12
Dept. of CSE, TKMCE
Behind the Scenes: How Python Works
13
Dept. of CSE, TKMCE
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.
14
Dept. of CSE, TKMCE
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.
15
Dept. of CSE, TKMCE
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
16
Dept. of CSE, TKMCE
17
Dept. of CSE, TKMCE
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.
18
Dept. of CSE, TKMCE
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
19
Dept. of CSE, TKMCE
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.
20
Dept. of CSE, TKMCE
# 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.
23
Dept. of CSE, TKMCE
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.
24
Dept. of CSE, TKMCE
Escape Sequences
Escape sequences are the way Python expresses special characters, such as the tab,
the newline, and the backspace (delete key), as literals.
25
Dept. of CSE, TKMCE
• 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.
26
Dept. of CSE, TKMCE
year = 2020
name = 'Ammu'
27
Dept. of CSE, TKMCE
memory
2020
Ammu
Year
Name
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!
28
Dept. of CSE, TKMCE
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.
29
Dept. of CSE, TKMCE
• 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.
30
Dept. of CSE, TKMCE
Numeric Data Types and Character Sets
31
Dept. of CSE, TKMCE
Numeric Data Types and Character Sets
32
Dept. of CSE, TKMCE
• 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'
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 '&'.
33
Dept. of CSE, TKMCE
Arithmetic Expressions
34
Dept. of CSE, TKMCE
35
Dept. of CSE, TKMCE
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
36
Dept. of CSE, TKMCE
37
Dept. of CSE, TKMCE
ü 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.
Mixed-Mode Arithmetic and Type Conversions
38
Dept. of CSE, TKMCE
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
32.153600000000004
39
Dept. of CSE, TKMCE
40
Dept. of CSE, TKMCE
• 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.
Program Comments and Docstrings
41
Dept. of CSE, TKMCE
• 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.
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)
42
Dept. of CSE, TKMCE
Using Functions and Modules
43
Dept. of CSE, TKMCE
• 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
The math Module
44
Dept. of CSE, TKMCE
• 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 *
Program Format and Structure
45
Dept. of CSE, TKMCE
• 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.
46
Dept. of CSE, TKMCE
Thank you

Mais conteúdo relacionado

Mais procurados

Chapter 1 - INTRODUCTION TO PYTHON -MAULIK BORSANIYA
Chapter 1 - INTRODUCTION TO PYTHON -MAULIK BORSANIYAChapter 1 - INTRODUCTION TO PYTHON -MAULIK BORSANIYA
Chapter 1 - INTRODUCTION TO PYTHON -MAULIK BORSANIYAMaulik Borsaniya
 
NETWORK SECURITY
NETWORK SECURITYNETWORK SECURITY
NETWORK SECURITYafaque jaya
 
Os lab file c programs
Os lab file c programsOs lab file c programs
Os lab file c programsKandarp Tiwari
 
Control structures in c++
Control structures in c++Control structures in c++
Control structures in c++Nitin Jawla
 
Python coding standards
Python coding standardsPython coding standards
Python coding standardsSharad Singla
 
OOP Unit 1 - Foundation of Object- Oriented Programming
OOP Unit 1 - Foundation of Object- Oriented ProgrammingOOP Unit 1 - Foundation of Object- Oriented Programming
OOP Unit 1 - Foundation of Object- Oriented Programmingdkpawar
 
CSE-Ethical-Hacking-ppt.pptx
CSE-Ethical-Hacking-ppt.pptxCSE-Ethical-Hacking-ppt.pptx
CSE-Ethical-Hacking-ppt.pptxAnshumaanTiwari2
 
Periféricos de comunicación
Periféricos de comunicaciónPeriféricos de comunicación
Periféricos de comunicacióncarloseduardoz10
 
Lecture 10 intruders
Lecture 10 intrudersLecture 10 intruders
Lecture 10 intrudersrajakhurram
 
Python debugging techniques
Python debugging techniquesPython debugging techniques
Python debugging techniquesTuomas Suutari
 
Introduction to python programming
Introduction to python programmingIntroduction to python programming
Introduction to python programmingSrinivas Narasegouda
 
Presentation on-exception-handling
Presentation on-exception-handlingPresentation on-exception-handling
Presentation on-exception-handlingNahian Ahmed
 

Mais procurados (20)

c++ lab manual
c++ lab manualc++ lab manual
c++ lab manual
 
Types of attacks
Types of attacksTypes of attacks
Types of attacks
 
Chapter 1 - INTRODUCTION TO PYTHON -MAULIK BORSANIYA
Chapter 1 - INTRODUCTION TO PYTHON -MAULIK BORSANIYAChapter 1 - INTRODUCTION TO PYTHON -MAULIK BORSANIYA
Chapter 1 - INTRODUCTION TO PYTHON -MAULIK BORSANIYA
 
NETWORK SECURITY
NETWORK SECURITYNETWORK SECURITY
NETWORK SECURITY
 
Python for Data Science
Python for Data SciencePython for Data Science
Python for Data Science
 
Os lab file c programs
Os lab file c programsOs lab file c programs
Os lab file c programs
 
Control structures in c++
Control structures in c++Control structures in c++
Control structures in c++
 
Python coding standards
Python coding standardsPython coding standards
Python coding standards
 
OOP Unit 1 - Foundation of Object- Oriented Programming
OOP Unit 1 - Foundation of Object- Oriented ProgrammingOOP Unit 1 - Foundation of Object- Oriented Programming
OOP Unit 1 - Foundation of Object- Oriented Programming
 
C# Lab Programs.pdf
C# Lab Programs.pdfC# Lab Programs.pdf
C# Lab Programs.pdf
 
CSE-Ethical-Hacking-ppt.pptx
CSE-Ethical-Hacking-ppt.pptxCSE-Ethical-Hacking-ppt.pptx
CSE-Ethical-Hacking-ppt.pptx
 
Mutual exclusion and sync
Mutual exclusion and syncMutual exclusion and sync
Mutual exclusion and sync
 
Periféricos de comunicación
Periféricos de comunicaciónPeriféricos de comunicación
Periféricos de comunicación
 
Lecture 10 intruders
Lecture 10 intrudersLecture 10 intruders
Lecture 10 intruders
 
Python debugging techniques
Python debugging techniquesPython debugging techniques
Python debugging techniques
 
Introduction to python programming
Introduction to python programmingIntroduction to python programming
Introduction to python programming
 
Python Intro
Python IntroPython Intro
Python Intro
 
Cyber security
Cyber securityCyber security
Cyber security
 
Presentation on-exception-handling
Presentation on-exception-handlingPresentation on-exception-handling
Presentation on-exception-handling
 
Nmap
NmapNmap
Nmap
 

Semelhante a Python for Machine Learning

Python Programming | JNTUK | UNIT 1 | Lecture 3
Python Programming | JNTUK | UNIT 1 | Lecture 3Python Programming | JNTUK | UNIT 1 | Lecture 3
Python Programming | JNTUK | UNIT 1 | Lecture 3FabMinds
 
python presentation
python presentationpython presentation
python presentationVaibhavMawal
 
265 ge8151 problem solving and python programming - 2 marks with answers
265   ge8151 problem solving and python programming - 2 marks with answers265   ge8151 problem solving and python programming - 2 marks with answers
265 ge8151 problem solving and python programming - 2 marks with answersvithyanila
 
chapter-04(Computational Thinking).pptx
chapter-04(Computational Thinking).pptxchapter-04(Computational Thinking).pptx
chapter-04(Computational Thinking).pptxssuserf60ff6
 
Python for Physical Science.pdf
Python for Physical Science.pdfPython for Physical Science.pdf
Python for Physical Science.pdfMarilouANDERSON
 
Chapter 2(1)
Chapter 2(1)Chapter 2(1)
Chapter 2(1)TejaswiB4
 
Program concep sequential statements
Program concep sequential statementsProgram concep sequential statements
Program concep sequential statementsankurkhanna
 
02 intel v_tune_session_02
02 intel v_tune_session_0202 intel v_tune_session_02
02 intel v_tune_session_02Vivek chan
 
Lab manual object oriented technology (it 303 rgpv) (usefulsearch.org) (usef...
Lab manual object oriented technology (it 303 rgpv) (usefulsearch.org)  (usef...Lab manual object oriented technology (it 303 rgpv) (usefulsearch.org)  (usef...
Lab manual object oriented technology (it 303 rgpv) (usefulsearch.org) (usef...Make Mannan
 
GE3151 PSPP _Unit 1 notes and Question bank.pdf
GE3151 PSPP _Unit 1 notes and Question bank.pdfGE3151 PSPP _Unit 1 notes and Question bank.pdf
GE3151 PSPP _Unit 1 notes and Question bank.pdfAsst.prof M.Gokilavani
 
S D D Program Development Tools
S D D  Program  Development  ToolsS D D  Program  Development  Tools
S D D Program Development Toolsgavhays
 
PYTHO programming NOTES with category.pdf
PYTHO programming NOTES with category.pdfPYTHO programming NOTES with category.pdf
PYTHO programming NOTES with category.pdfdeivasigamani9
 
PYTHON PROGRAMMING NOTES.pdf
PYTHON PROGRAMMING NOTES.pdfPYTHON PROGRAMMING NOTES.pdf
PYTHON PROGRAMMING NOTES.pdfRajathShetty34
 
Introduction to Computer Programming
Introduction to Computer ProgrammingIntroduction to Computer Programming
Introduction to Computer ProgrammingProf. Erwin Globio
 

Semelhante a Python for Machine Learning (20)

Python Programming | JNTUK | UNIT 1 | Lecture 3
Python Programming | JNTUK | UNIT 1 | Lecture 3Python Programming | JNTUK | UNIT 1 | Lecture 3
Python Programming | JNTUK | UNIT 1 | Lecture 3
 
python presentation
python presentationpython presentation
python presentation
 
265 ge8151 problem solving and python programming - 2 marks with answers
265   ge8151 problem solving and python programming - 2 marks with answers265   ge8151 problem solving and python programming - 2 marks with answers
265 ge8151 problem solving and python programming - 2 marks with answers
 
Resume
ResumeResume
Resume
 
INTERNSHIP REPORT.docx
 INTERNSHIP REPORT.docx INTERNSHIP REPORT.docx
INTERNSHIP REPORT.docx
 
chapter-04(Computational Thinking).pptx
chapter-04(Computational Thinking).pptxchapter-04(Computational Thinking).pptx
chapter-04(Computational Thinking).pptx
 
Python for Physical Science.pdf
Python for Physical Science.pdfPython for Physical Science.pdf
Python for Physical Science.pdf
 
Chapter 2(1)
Chapter 2(1)Chapter 2(1)
Chapter 2(1)
 
L1
L1L1
L1
 
Program concep sequential statements
Program concep sequential statementsProgram concep sequential statements
Program concep sequential statements
 
02 intel v_tune_session_02
02 intel v_tune_session_0202 intel v_tune_session_02
02 intel v_tune_session_02
 
Lab manual object oriented technology (it 303 rgpv) (usefulsearch.org) (usef...
Lab manual object oriented technology (it 303 rgpv) (usefulsearch.org)  (usef...Lab manual object oriented technology (it 303 rgpv) (usefulsearch.org)  (usef...
Lab manual object oriented technology (it 303 rgpv) (usefulsearch.org) (usef...
 
GE3151 PSPP _Unit 1 notes and Question bank.pdf
GE3151 PSPP _Unit 1 notes and Question bank.pdfGE3151 PSPP _Unit 1 notes and Question bank.pdf
GE3151 PSPP _Unit 1 notes and Question bank.pdf
 
S D D Program Development Tools
S D D  Program  Development  ToolsS D D  Program  Development  Tools
S D D Program Development Tools
 
PYTHON PROGRAMMING NOTES RKREDDY.pdf
PYTHON PROGRAMMING NOTES RKREDDY.pdfPYTHON PROGRAMMING NOTES RKREDDY.pdf
PYTHON PROGRAMMING NOTES RKREDDY.pdf
 
PYTHO programming NOTES with category.pdf
PYTHO programming NOTES with category.pdfPYTHO programming NOTES with category.pdf
PYTHO programming NOTES with category.pdf
 
PYTHON PROGRAMMING NOTES.pdf
PYTHON PROGRAMMING NOTES.pdfPYTHON PROGRAMMING NOTES.pdf
PYTHON PROGRAMMING NOTES.pdf
 
Introduction to Procedural Programming in C++
Introduction to Procedural Programming in C++Introduction to Procedural Programming in C++
Introduction to Procedural Programming in C++
 
Introduction to Computer Programming
Introduction to Computer ProgrammingIntroduction to Computer Programming
Introduction to Computer Programming
 
Beekman5 std ppt_13
Beekman5 std ppt_13Beekman5 std ppt_13
Beekman5 std ppt_13
 

Mais de Student

Decision Trees
Decision TreesDecision Trees
Decision TreesStudent
 
Introducing Technologies for Handling Big Data by Jaseela
Introducing Technologies for Handling Big Data by JaseelaIntroducing Technologies for Handling Big Data by Jaseela
Introducing Technologies for Handling Big Data by JaseelaStudent
 
A review of localization systems for robotic endoscopic
A review of localization systems for robotic endoscopicA review of localization systems for robotic endoscopic
A review of localization systems for robotic endoscopicStudent
 
Signature Free Virus Blocking Method to Detect Software Code Security (Intern...
Signature Free Virus Blocking Method to Detect Software Code Security (Intern...Signature Free Virus Blocking Method to Detect Software Code Security (Intern...
Signature Free Virus Blocking Method to Detect Software Code Security (Intern...Student
 
Sigfree ppt (International Journal of Computer Science and Mobile Computing)
Sigfree ppt (International Journal of Computer Science and Mobile Computing)Sigfree ppt (International Journal of Computer Science and Mobile Computing)
Sigfree ppt (International Journal of Computer Science and Mobile Computing)Student
 
Design and Implementation of Improved Authentication System for Android Smart...
Design and Implementation of Improved Authentication System for Android Smart...Design and Implementation of Improved Authentication System for Android Smart...
Design and Implementation of Improved Authentication System for Android Smart...Student
 
Desgn&imp authentctn.ppt by Jaseela
Desgn&imp authentctn.ppt by JaseelaDesgn&imp authentctn.ppt by Jaseela
Desgn&imp authentctn.ppt by JaseelaStudent
 
Google glass by Jaseela
Google glass by JaseelaGoogle glass by Jaseela
Google glass by JaseelaStudent
 

Mais de Student (8)

Decision Trees
Decision TreesDecision Trees
Decision Trees
 
Introducing Technologies for Handling Big Data by Jaseela
Introducing Technologies for Handling Big Data by JaseelaIntroducing Technologies for Handling Big Data by Jaseela
Introducing Technologies for Handling Big Data by Jaseela
 
A review of localization systems for robotic endoscopic
A review of localization systems for robotic endoscopicA review of localization systems for robotic endoscopic
A review of localization systems for robotic endoscopic
 
Signature Free Virus Blocking Method to Detect Software Code Security (Intern...
Signature Free Virus Blocking Method to Detect Software Code Security (Intern...Signature Free Virus Blocking Method to Detect Software Code Security (Intern...
Signature Free Virus Blocking Method to Detect Software Code Security (Intern...
 
Sigfree ppt (International Journal of Computer Science and Mobile Computing)
Sigfree ppt (International Journal of Computer Science and Mobile Computing)Sigfree ppt (International Journal of Computer Science and Mobile Computing)
Sigfree ppt (International Journal of Computer Science and Mobile Computing)
 
Design and Implementation of Improved Authentication System for Android Smart...
Design and Implementation of Improved Authentication System for Android Smart...Design and Implementation of Improved Authentication System for Android Smart...
Design and Implementation of Improved Authentication System for Android Smart...
 
Desgn&imp authentctn.ppt by Jaseela
Desgn&imp authentctn.ppt by JaseelaDesgn&imp authentctn.ppt by Jaseela
Desgn&imp authentctn.ppt by Jaseela
 
Google glass by Jaseela
Google glass by JaseelaGoogle glass by Jaseela
Google glass by Jaseela
 

Último

Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...anjaliyadav012327
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room servicediscovermytutordmt
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...Pooja Nehwal
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 

Último (20)

Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room service
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 

Python for Machine Learning

  • 1. Python for Machine Learning Course Code : CST283 Category : Minor Offered by : Dept. of Computer Science and Engg. Faculty in charge : Jaseela Beevi S 1 Dept. of CSE, TKMCE
  • 2. 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. 2 Dept. of CSE, TKMCE
  • 3. 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. 3 Dept. of CSE, TKMCE
  • 4. 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. 4 Dept. of CSE, TKMCE
  • 5. 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. 5 Dept. of CSE, TKMCE
  • 6. 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. 6 Dept. of CSE, TKMCE
  • 7. 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 7 Dept. of CSE, TKMCE Quit Command Leaving help and returning to the python interpreter
  • 8. 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 8 Dept. of CSE, TKMCE
  • 9. 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 >>> 9 Dept. of CSE, TKMCE
  • 10. • 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 >>> 10 Dept. of CSE, TKMCE
  • 12. 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). 12 Dept. of CSE, TKMCE
  • 13. Behind the Scenes: How Python Works 13 Dept. of CSE, TKMCE
  • 14. 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. 14 Dept. of CSE, TKMCE
  • 15. 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. 15 Dept. of CSE, TKMCE
  • 16. 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 16 Dept. of CSE, TKMCE
  • 18. 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. 18 Dept. of CSE, TKMCE
  • 19. 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 19 Dept. of CSE, TKMCE
  • 20. 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. 20 Dept. of CSE, TKMCE
  • 21. # 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))
  • 22. If there is a logic error in the code, it will almost certainly be caught using these data.
  • 23. 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. 23 Dept. of CSE, TKMCE
  • 24. 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. 24 Dept. of CSE, TKMCE
  • 25. Escape Sequences Escape sequences are the way Python expresses special characters, such as the tab, the newline, and the backspace (delete key), as literals. 25 Dept. of CSE, TKMCE
  • 26. • 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. 26 Dept. of CSE, TKMCE
  • 27. year = 2020 name = 'Ammu' 27 Dept. of CSE, TKMCE memory 2020 Ammu Year Name
  • 28. 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! 28 Dept. of CSE, TKMCE
  • 29. 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. 29 Dept. of CSE, TKMCE
  • 30. • 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. 30 Dept. of CSE, TKMCE
  • 31. Numeric Data Types and Character Sets 31 Dept. of CSE, TKMCE
  • 32. Numeric Data Types and Character Sets 32 Dept. of CSE, TKMCE • 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'
  • 33. 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 '&'. 33 Dept. of CSE, TKMCE
  • 35. 35 Dept. of CSE, TKMCE 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
  • 37. 37 Dept. of CSE, TKMCE ü 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.
  • 38. Mixed-Mode Arithmetic and Type Conversions 38 Dept. of CSE, TKMCE 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 32.153600000000004
  • 40. 40 Dept. of CSE, TKMCE • 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.
  • 41. Program Comments and Docstrings 41 Dept. of CSE, TKMCE • 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.
  • 42. 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) 42 Dept. of CSE, TKMCE
  • 43. Using Functions and Modules 43 Dept. of CSE, TKMCE • 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
  • 44. The math Module 44 Dept. of CSE, TKMCE • 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 *
  • 45. Program Format and Structure 45 Dept. of CSE, TKMCE • 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.
  • 46. 46 Dept. of CSE, TKMCE Thank you