Python Programing Final
Python Programing Final
Continuous Assessment
Attendance – 10 marks
programming is by doing.
INTRODUCTION TO COMPUTER PROGRAMMING
❖ So, what is programming? The term programming means to create (or develop) software,
which is also called a program. In basic terms, software contains the instructions that tell a
computer—or a computerized device—what to do.
❖ Software developers create software with the help of powerful tools called programming
languages
❖ Knowing that there are so many programming languages available, it would be natural for
you to wonder which one is best. But, in truth, there is no “best” language.
❖ Each one has its own strengths and weaknesses. Experienced programmers know that one
language might work well in some situations, whereas a different language may be more
appropriate in other situations
INTRODUCTION TO COMPUTER PROGRAMMING
❖ If you learn to program using one language, you should find it easy to pick up other
languages. The key is to learn how to solve problems using a programming approach
Python is a general-purpose
programming language. That means you
can use Python to write code for any
programming task. Python is now used
in the Google search engine, in mission-
critical projects at NASA, and in
transaction processing at the New York
Stock Exchange.
WHY PYTHON?
❖ Python is open-source
❖ Python is easy : It is built based on human language (feels like we’re “having conversation” with the
programs)
❖ Python is fast and efficient : The use of “list comprehension” instead of “for-loop” makes consuming much
❖ Python is flexible : We can build and deploy programs almost anywhere (in local PC systems and in the cloud)
❖ Python is scientific : For scientific task, Python is as capable as scientific programming languages like
❖ Software developers create software with the help of powerful tools called
programming languages
❖ If you learn to program using one language, you should find it easy to pick up
other languages.
INTRODUCTION TO PYTHON PROGRAMMING LANGUAGE
(a) An interpreter translates and executes a program one statement at a time. (b) A compiler translates the entire
source program into a machine-language file for execution.
INTRODUCTION TO PYTHON PROGRAMMING LANGUAGE
INTRODUCTION TO PYTHON PROGRAMMING LANGUAGE
Python from IDLE. Python from the command window (console) PyCharm
INTRODUCTION TO PYTHON PROGRAMMING LANGUAGE
❖ python filename.py
❖ In Python, comments are preceded by a pound sign (#) on a line, called a line
comment.
❖ When the Python interpreter sees #, it ignores all text after # on the same line.
When it sees ''', it scans for the next ''' and ignores any text between the triple
quotation marks.
Don’t put any punctuation at the end of a statement. For example, the Python
interpreter will report errors for the following code:
Python programs are case sensitive. It would be wrong, for example, to replace
print in the program with Print.
Python programs can perform all sorts of mathematical computations and display
the result. To display the addition, subtraction, multiplication, and division of two
numbers, x and y, use the following code:
print(x + y)
print(x – y)
print(x * y)
print(x / y)
INTRODUCTION TO PYTHON PROGRAMMING LANGUAGE
Proper Spacing
A consistent spacing style makes programs clear and easy to read, debug (find and
fix errors), and maintain. A single space should be added on both sides of an
operator, as shown in the following statement:
Syntax Errors
It should be 1.66.
In Python, syntax errors are actually treated like runtime errors because they are
detected by the interpreter when the program is executed. In general, syntax and
runtime errors are easy to find and easy to correct, because Python gives
indications as to where the errors came from and why they are wrong. Finding
logic errors, on the other hand, can be very challenging.
ELEMENTARY PROGRAMMING
❖ Along the way, you learn the basic steps that go into analyzing a problem,
designing a solution, and implementing the solution by creating a program.
Example Problem
❖ Consider the simple problem of computing the area of a circle. How do we
write a program for solving this problem?
ELEMENTARY PROGRAMMING
❖ Designing algorithms and then translating them into programming
instructions, or code
Assignment statement
❖ Python automatically figures out the data type according to the value assigned
to the variable.
The value entered is a string. You can use the function eval to evaluate and
convert it to a numeric value.
ELEMENTARY PROGRAMMING
ELEMENTARY PROGRAMMING
Identifiers
Identifiers are the names that identify the elements such as variables and functions
in a program. When Python detects an illegal identifier (2A, D+4), it reports a
syntax error and terminates the program. All identifiers must obey the following
rules:
❖ An identifier is a sequence of characters that consists of letters, digits, and
underscores (_).
❖ An identifier must start with a letter or an underscore. It cannot start with a
digit.
❖ An identifier cannot be a keyword. (See Appendix A, Python Keywords, for a
list of keywords.) Keywords, also called reserved words, have special meanings
in Python. For example, import is a keyword, which tells the Python
interpreter to import a module to the program.
❖ An identifier can be of any length.
ELEMENTARY PROGRAMMING
You can use a variable in an expression. A variable can also be used in both sides
of the = operator.
For example, x = x + 1
If a value is assigned to multiple variables, you can use a syntax like this:
i=j=k=1
which is equivalent to
k=1
j=k
i=j
ELEMENTARY PROGRAMMING
Simultaneous Assignments
ELEMENTARY PROGRAMMING
Named Constants
A named constant is an identifier that represents a permanent value.
ELEMENTARY PROGRAMMING
Numeric Data Types and Operators
❖ Python has two numeric types—integers and floating-point numbers—for
working with the operators +, -, *, /, //, **, and %.
❖ Real types are for representing numbers with a fractional part. Inside the
computer, these two types of data are stored differently. Real numbers are
represented as floating-point (or float) values.
ELEMENTARY PROGRAMMING
❖ A number that has a decimal point is a float even if its fractional part is 0. For
example, 1.0 is a float, but 1 is an integer.
❖ These two numbers are stored differently in the computer. In the programming
terminology, numbers such as 1.0 and 1 are called literals.
❖ The +, -, and * operators are straightforward, but note that the + and - operators
can be both unary and binary. A unary operator has only one operand; a binary
operator has two.
Computing Distances
MATHEMATICAL FUNCTIONS, STRINGS, AND OBJECTS
❖ The focus of this chapter is to introduce functions, strings, and objects, and to
use them to develop programs.
❖ These are built-in functions and they are always available in the Python
interpreter
MATHEMATICAL FUNCTIONS, STRINGS, AND OBJECTS
Common Python Functions
MATHEMATICAL FUNCTIONS, STRINGS, AND OBJECTS
The Python math module provides the mathematical functions
MATHEMATICAL FUNCTIONS, STRINGS, AND OBJECTS
import math
MATHEMATICAL FUNCTIONS, STRINGS, AND OBJECTS
Strings and Characters
A string is a sequence of characters. Python treats characters and strings the same
way.
❖ The \f character forces the printer to print from the next page.
❖ The \r character is used to move the cursor to the first position on the same
line
MATHEMATICAL FUNCTIONS, STRINGS, AND OBJECTS
MATHEMATICAL FUNCTIONS, STRINGS, AND OBJECTS
MATHEMATICAL FUNCTIONS, STRINGS, AND OBJECTS
MATHEMATICAL FUNCTIONS, STRINGS, AND OBJECTS
The augmented assignment += operator can also be used for string concatenation.
For example, the following code concatenates the string in message with the
string " and Python is fun".
MATHEMATICAL FUNCTIONS, STRINGS, AND OBJECTS
The equal to comparison operator is two equal signs (==), not a single equal sign (=).
The latter symbol is for assignment.
True and False are literals, just like a number such as 10. They are reserved words
and cannot be used as identifiers in a program.
Internally, Python uses 1 to represent True and 0 for False. You can use the int
function to convert a Boolean value to an integer.
For example,
SELECTION
You can also use the bool function to convert a numeric value to a Boolean value.
The function returns False if the value is 0; otherwise, it always returns True.
Since randint is more intuitive. You can also use the random() function to
generate a random float r such that 0 <= r <1.0. For example:
SELECTION
if Statements
Python has several types of selection statements: one-way if statements, two-
way if-else statements, nested if statements, multi-way if-elif-else statements
and conditional expressions.
The statement(s) must be indented at least one space to the right of the if keyword
and each statement must be indented using the same number of spaces.
SELECTION
Process operations are represented in these boxes, and arrows connecting them
show flow of control.
A diamond box is used to denote a Boolean condition and a rectangle box is for
representing statements
SELECTION
SELECTION
In fact, there is no limit to the depth of the nesting. For example, the following is a
nested if statement:
Write a program that prompts the user to enter a weight in pounds and height in
inches and then displays the BMI. Note that one pound is 0.45359237
kilograms and one inch is 0.0254 meters.
SELECTION
SELECTION
Logical Operators
The logical operators not, and, and or can be used to create a composite
condition.
Table contains the operators you have learned so far, with the operators listed in
decreasing order of precedence from top to bottom. The logical operators have
lower precedence than the relational operators and the relational operators have
lower precedence than the arithmetic operators. Operators with the same
precedence appear in the same group.
SELECTION
Operator Precedence Chart
A loop is a construct that controls the repeated execution of a block of statements. The concept
of looping is fundamental to programming.
Python provides two types of loop statements: while loops and for loops.
The while loop is a condition-controlled loop; it is controlled by a true/false condition. The for
loop is a count-controlled loop that repeats a specified number of times.
LOOPS
A while loop executes statements repeatedly as long as a condition remains true.
Single execution of a loop body is called an iteration (or repetition) of the loop. Each loop
contains a loop-continuation-condition.
A Boolean expression that controls the body’s execution. It is evaluated each time to determine
if the loop body should be executed.
If its evaluation is True, the loop body is executed; otherwise, the entire loop terminates and the
program control turns to the statement that follows the while loop.
LOOPS
while-loop flowchart
The while loop repeatedly executes the statements in the loop body as long as the loop
continuation-condition evaluates to True.
LOOPS
Here is another example illustrating how a loop works
LOOPS
LOOPS
LOOPS
It is important to think before coding. Think about how you would solve the problem without
writing a program.
For programs involving loops, if you don’t know how to write a loop right away, you might
first write the program so it executes the code once.
Another common technique for controlling a loop is to designate a special input value, known
as a sentinel value, which signifies the end of the input. A loop that uses a sentinel value in
this way is called a sentinel-controlled loop.
Calculates the sum of an unspecified number of integers. The input 0 signifies the end of the
input. You don’t need to use a new variable for each input value.
Instead, use a variable named data (line 1) to store the input value and use a variable named
sum (line 5) to store the total.
Whenever a value is read, assign it to data (line 9) and add it to sum (line 7) if it is not zero.
LOOPS
LOOPS
LOOPS
The for Loop
A Python for loop iterates through each value in a sequence.
Often you know exactly how many times the loop body needs to be executed, so a control
variable can be used to count the executions. A loop of this type is called a counter-controlled
loop. In general, the loop can be written as follows
range(a, b, k). The first number in the sequence is a. Each successive number in the sequence
will increase by the step value k. b is the limit. The last number in the sequence must be less
than b. For example:
LOOPS
The range(a, b, k) function can count backward if k is negative.
LOOPS
LOOPS
LOOPS
LOOPS
Nested Loops
A loop can be nested inside another loop.
LOOPS
LOOPS
LOOPS
LOOPS
Minimizing Numerical Errors
Using floating-point numbers in the loop-continuation-condition may cause numeric errors.
Numerical errors involving floating-point numbers are inevitable. This section provides an
example showing you how to minimize such errors.
The program sums a series that starts with 0.01 and ends with 1.0. The numbers in the series
will increment by 0.01, as follows: 0.01 + 0.02 + 0.03 and so on.
LOOPS
Minimizing Numerical Errors
The result displayed is 49.5, but the correct result is actually 50.5. What went wrong? For each
iteration in the loop, i is incremented by 0.01. When the loop ends, the i value is slightly
larger than 1 (not exactly 1).
This causes the last i value not to be added into sum. The fundamental problem is that the
floating-point numbers are represented by approximation.
LOOPS
Minimizing Numerical Errors
Two keywords, break and continue, can be used in loop statements to provide additional
controls.
Overusing or improperly using them, however, can make programs difficult to read and debug.
You can use the keyword break in a loop to immediately terminate a loop.
LOOPS
LOOPS
You can also use the continue keyword in a loop. When it is encountered, it ends the current
iteration and program control goes to the end of the loop body.
In other words, continue breaks out of an iteration, while the break keyword breaks out of a
loop
LOOPS
Functions
Functions can be used to define reusable code, organize and simplify code. A function is a
collection of statements grouped together that performs an operation. A function definition
consists of the function’s name, parameters, and body.
Functions
Suppose that you need to find the sum of integers from 1 to 10, 20 to 37, and 35 to
49. If you create a program to add these three sets of numbers, your code might
look like this:
Functions
You may have observed that the code for computing these sums is
very similar, except that the starting and ending integers are different.
Wouldn’t it be nice to be able to write commonly used code once and
then reuse it? You can do this by defining a function, which enables
you to create reusable code. For example, the preceding code can be
simplified by using functions, as follows:
Functions
Examples
larger = max(3, 4)
print(max(3, 4))
Functions with/without Return Values
A function does not have to return a value. This section shows how to define and
invoke a function that does not return a value. Such a function is commonly known
as a void function in programming terminology.
Defines a function named printGrade and invokes it to print the grade for a given
score.
Functions with/without Return Values
Functions with/without Return Values
Returning Multiple Values
Defines a function that takes two numbers and returns them in ascending order.
Functions
Error
Import Functions
MATLIBPLOT
Data Visualization with Python
Data visualization is the discipline of trying to understand data by placing it in a visual context so that patterns,
trends and correlations that might not otherwise be detected can be exposed.
Python offers multiple great graphing libraries that come packed with lots of different features. No matter if
you want to create interactive, live or highly customized plots python has an excellent library for you.
matplotlib:
▪python 2D plotting library which produces publication quality figures in a variety of hardcopy formats
Matplotlib is specifically good for creating basic graphs like line charts, bar charts, histograms and many more.
It can be imported by typing:
matplotlib.pyplot is a collection of command style functions that make Matplotlib work like MATLAB.
Example of MATLAB Plot
Matplotlib has a procedural interface named the Pylab, which is designed to resemble MATLAB, a proprietary
programming language developed by MathWorks. Matplotlib along with NumPy can be considered as the open
Line plot
Pie chart
Type of Plots
Scatter plot Polar plot
❖ The fundamental unit of data in any python program is the array. An array is a collection of data values
❖ By python—they are simply arrays with only one row and one column.
❖ Arrays can be classified as either vectors or matrices. The term “vector” is usually used to describe an
❖ while the term “matrix” is usually used to describe an array with two or more dimensions.
Arrays
NumPy in Python
Numpy is the core library for scientific computing in Python.
It provides a high-performance multidimensional array object and tools for working with these arrays. Numpy is a
powerful N-dimensional array object which is Linear algebra for Python.
Numpy arrays essentially come in two flavors: Vectors and Matrics. Vectors are strictly 1-d array whereas Matrices
are 2-d but matrices can have only one row/column.
NumPy in Python
NumPy in Python
How to create a basic array
This section covers np.array(), np.zeros(), np.ones(), np.empty(), np.arange(), np.linspace(), dtype
NumPy in Python
Adding, removing, and sorting elements
NumPy in Python
A class defines the properties and behaviors for objects. Objects are
created from classes. Object-oriented programming (OOP) involves
the use of objects to create programs. An object represents an entity in
the real world that can be distinctly identified.
For example, a student, a desk, a circle, a button, and even a loan can
all be viewed as objects. An object has a unique identity, state, and
behavior.
Defining Classes
You will gain insight into the differences between procedural and object-oriented programming and see the benefits of
developing reusable code using objects and classes
Computing Body Mass Index
You can use nested if statements to write a program that interprets body mass
index.
Body mass index (BMI) is a measure of health based on weight. It can be
calculated by taking your weight in kilograms and dividing it by the square of your
height in meters. The interpretation of BMI for people 16 years and older is as
follows:
Write a program that prompts the user to enter a weight in pounds and height in
inches and then displays the BMI. Note that one pound is 0.45359237
kilograms and one inch is 0.0254 meters.
TRIAL EXERCISE