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

Python Programing Final

The document discusses an introduction to Python programming language. It covers what programming is, why Python is a popular language, how to get started with Python, basic Python syntax like comments and indentation, performing mathematical computations, and common errors.

Uploaded by

Para Dise
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Python Programing Final

The document discusses an introduction to Python programming language. It covers what programming is, why Python is a popular language, how to get started with Python, basic Python syntax like comments and indentation, performing mathematical computations, and common errors.

Uploaded by

Para Dise
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 218

UNIVERSITY OF MINES AND TECHNOLOGY, TARKWA

SCHOOL OF PETROLEUM STUDIES

PETROLEUM AND NATURAL GAS ENGINEERING DEPARTMENT

LECTURER: DR ERIC THOMPSON BRANTSON


CODE OF ETHICS FOR STUDENTS

❖ Lateness to class will not be allowed

❖ All phones should be on silence or turned off to avoid disturbance

❖ Chatting while lectures is ongoing will not be allowed

❖ Eating in class will not be allowed

❖ Copying verbatim from a colleague friend will not be allowed

❖ Covid-19 protocols must be observed at all times

❖ Late submission of assignments and group works will not be allowed


ASSESSMENT OF STUDENTS

Continuous Assessment

Attendance – 10 marks

Quizzes, Assignments, Group work and Presentation - 30 marks

Final Examination Assessment

Practical Exams – 40 marks (2 hours)

Written Exams (Theory) – 20 marks (1 hour)


COURSE OBJECTIVES

The objectives of this course are:

❖ To use high-level programming language (python) to solve Engineering problems

❖ To comprehend modern software development engineering principles

❖ To apply python programming language to 3D modeling and simulation workflows


TOPICS IN PYTHON PROGRAMMING LANGUAGE

❖ Introduction to Python Programming Language ❖ Matplotlib (Graphs and Applications)


❖ Elementary Programming ❖ GUI Programming
❖ Mathematical Functions, Strings, and Objects ❖ Lists

❖ Selections ❖ Multidimensional Lists


❖ Inheritance and Polymorphism
❖ Loops
❖ Files and Exception Handling
❖ Functions
❖ Tuples, Sets, and Dictionaries
❖ Objects and Classes
❖ Recursion
❖ More on Strings and Special Methods
The best way to teach programming is by

example, and the only way to learn

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

❖ You are about to begin an exciting journey: learning how to program.


INTRODUCTION TO PYTHON PROGRAMMING LANGUAGE

Python was created by Guido van Rossum in the

Netherlands in 1990 and was named after the

popular British comedy troupe Monty Python’s

Flying Circus. Van Rossum developed Python as a

hobby, and Python has become a popular

programming language widely used

in industry and academia due to its simple, concise,

and intuitive syntax and extensive library.


INTRODUCTION TO PYTHON PROGRAMMING LANGUAGE
INTRODUCTION TO PYTHON PROGRAMMING LANGUAGE

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

less lines of codes

❖ Python is flexible : We can build and deploy programs almost anywhere (in local PC systems and in the cloud)

❖ Python is abundant : 2 million ++ libraries and packages available to use

❖ Python is scientific : For scientific task, Python is as capable as scientific programming languages like

MATLAB, or even better


INTRODUCTION TO PYTHON PROGRAMMING LANGUAGE

❖ How to download python: www.python.org/download

❖ Python IDE (Where to write your codes): www.anaconda.com/download

❖ Python IDE :www.jetbrains.com/pycharm/download/

❖ Launching Python: IDLE (Interactive DeveLopment Environment) is an


integrated development environment (IDE) for Python. You can create, open,
save, edit, and run Python programs in IDLE. Both the command-line Python
interpreter and IDLE are available after Python is installed on your machine
INTRODUCTION TO PYTHON PROGRAMMING LANGUAGE

❖ 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

❖ If you learn to program using one language, you should find it easy to pick up
other languages.
INTRODUCTION TO PYTHON PROGRAMMING LANGUAGE

❖ A program written in a high-level language is called a source program or source


code. Because a computer cannot understand a source program, a source program
must be translated into machine code for execution. The translation can be done
using another programming tool called an interpreter or a compiler.

(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 is interpreted, which means that Python code is translated and


executed by an interpreter, one statement at a time.

❖ Python is an object-oriented programming (OOP) language. Data in


Python are objects created from classes. A class is essentially a type
or category that defines objects of the same kind with properties and
methods for manipulating objects. Object-oriented programming is
a powerful tool for developing reusable software.
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.

❖ Enclosed between three consecutive single quotation marks (''') on one or


several lines, called a paragraph 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.

# This program displays Welcome to Python


''' This program displays Welcome to Python and Python is fun
INTRODUCTION TO PYTHON PROGRAMMING LANGUAGE
BAD CODES
Indentation matters in Python. Note that the statements are entered from the first
column in the new line. The Python interpreter will report an error if the program is
typed as follows:

# Display two messages


print("Welcome to Python")
print("Python is fun")

Don’t put any punctuation at the end of a statement. For example, the Python
interpreter will report errors for the following code:

# Display two messages


print("Welcome to Python").
print("Python is fun"),
INTRODUCTION TO PYTHON PROGRAMMING LANGUAGE

Python programs are case sensitive. It would be wrong, for example, to replace
print in the program with Print.

Programming Style and Documentation


INTRODUCTION TO PYTHON PROGRAMMING LANGUAGE
Using Python to Perform Mathematical Computations

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

Syntax errors result from errors in code construction, such as mistyping a


statement, incorrect indentation, omitting some necessary punctuation, or using an
opening parenthesis without a corresponding closing parenthesis. These errors are
usually easy to detect, because Python tells you where they are and what caused
them.
INTRODUCTION TO PYTHON PROGRAMMING LANGUAGE
Runtime Errors
Runtime errors are errors that cause a program to terminate abnormally. They
occur while a program is running if the Python interpreter detects an operation
that is impossible to carry out. Input mistakes typically cause runtime errors. An
input error occurs when the user enters a value that the program cannot handle.
For instance, if the program expects to read in a number, but instead the user
enters a string of text, this causes data-type errors to occur in the program.
Another common source of runtime errors is division by zero. This happens when
the divisor is zero for integer divisions. For example, the expression 1 / 0 in the
following statement would cause a runtime error.
INTRODUCTION TO PYTHON PROGRAMMING LANGUAGE
Logic Errors
Logic errors occur when a program does not perform the way it was intended to.
Errors of this kind occur for many different reasons. For example, suppose you
wrote the program in converting a temperature (35 degrees) from Fahrenheit to
Celsius.

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

❖ You will learn fundamental programming techniques, such as the use of


variables, operators, expressions, and input and output.

❖ 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

❖ An algorithm describes how a problem is solved by listing the actions that


need to be taken and the order of their execution.

❖ Algorithms can be described in natural languages or in pseudocode (natural


language mixed with some programming code).

❖ A variable is a name that references a value stored in the computer’s memory.

1. Get the circle’s radius from the user.


2. Compute the area by applying the following formula:
3. Display the result.
ELEMENTARY PROGRAMMING

Assignment statement

❖ Python automatically figures out the data type according to the value assigned
to the variable.

❖ This method of reviewing how a program works is called tracing a program.


Tracing programs are helpful for understanding how programs work, and they
are useful tools for finding errors in programs.
ELEMENTARY PROGRAMMING

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

❖ Use lowercase letters for variable names, as in radius and area


❖ If a name consists of several words, concatenate them into one, making the
first word lowercase and capitalizing the first letter of each subsequent word.
❖ For example, numberOfStudents is better than numStuds, numOfStuds, or
numOfStudents.
❖ This naming style is known as the camelCase because the uppercase
characters in the name resemble a camel’s humps.
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 %.

❖ The information stored in a computer is generally referred to as data. There are


two types of numeric data: integers and real numbers. Integer types (int for
short) are for representing whole numbers.

❖ 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.

❖ A literal is a constant value that appears directly in a program.

❖ The operands are the values operated by an operator.


ELEMENTARY PROGRAMMING

Students should practice with


examples of numerical
operators

❖ 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.

❖ For example, the - operator in -5 is a unary operator to negate the number 5,


whereas the – operator in 4 - 5 is a binary operator for subtracting 5 from 4.
ELEMENTARY PROGRAMMING
ELEMENTARY PROGRAMMING
Scientific Notation
Floating-point values can be written in scientific notation in the form of a x 10b

Augmented Assignment Operators


The operators +, -, *, /, //, %, and ** can be combined with the assignment
operator (=) to form augmented assignment operators.
count = count + 1 There are no spaces in the augmented assignment operators

count += 1 The += operator is called the addition assignment operator


ELEMENTARY PROGRAMMING
ELEMENTARY PROGRAMMING

Type Conversions and Rounding


You can also use the round function to round a number to the nearest whole value
ELEMENTARY PROGRAMMING
ELEMENTARY PROGRAMMING
Software Development Process
The software development life cycle is a multistage process that includes
requirements specification, analysis, design, implementation, testing, deployment,
and maintenance. Developing a software product is an engineering process.
ELEMENTARY PROGRAMMING
Developers need to work closely with their customers (the individuals or
organizations that will use the software) and study the problem carefully to
identify what the software needs to do.
ELEMENTARY PROGRAMMING

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.

❖ Python functions are for performing common mathematical operations and


functions can be customized

❖ All data in Python are objects used to develop useful programs.

❖ A function is a group of statements that performs a specific task. Python, as


well as other programming languages, provides a library of functions.

❖ 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.

A single-character string represents a character. For example,

letter = 'A' # Same as letter = "A"

numChar = '4' # Same as numChar = "4"

message = "Good morning" # Same as message = 'Good morning'


MATHEMATICAL FUNCTIONS, STRINGS, AND OBJECTS
Escape Sequences for Special Characters
❖ Python uses a special notation to represent special characters.

❖ This special notation, which consists of a backslash (\) followed by a letter


or a combination of digits, is called an escape sequence.

❖ The \n character is also known as a newline, line break or end-of-line (EOL)


character, which signifies the end of a line.

❖ 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 String Concatenation Operator


You can use the + operator to add two numbers. The + operator can be used to
concatenate two strings.

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

Introduction to Objects and Methods


In Python, all data—including numbers and strings—are actually objects.
In Python, a number is an object, a string is an object, and every datum is an object. Objects of
the same kind have the same type. You can use the id function and type function to get these
pieces of information about an object. For example,
MATHEMATICAL FUNCTIONS, STRINGS, AND OBJECTS

The id for the object is automatically assigned a unique integer by Python


when the program is executed. The id for the object will not be changed
during the execution of the program. However, Python may assign a different
id every time the program is executed. The type for the object is determined
by Python according to the value of the object
MATHEMATICAL FUNCTIONS, STRINGS, AND OBJECTS

Formatting Numbers and Strings

You can use the format function to return a formatted string.


MATHEMATICAL FUNCTIONS, STRINGS, AND OBJECTS
MATHEMATICAL FUNCTIONS, STRINGS, AND OBJECTS
MATHEMATICAL FUNCTIONS, STRINGS, AND OBJECTS
MATHEMATICAL FUNCTIONS, STRINGS, AND OBJECTS
MATHEMATICAL FUNCTIONS, STRINGS, AND OBJECTS
MATHEMATICAL FUNCTIONS, STRINGS, AND OBJECTS
MATHEMATICAL FUNCTIONS, STRINGS, AND OBJECTS
MATHEMATICAL FUNCTIONS, STRINGS, AND OBJECTS
MATHEMATICAL FUNCTIONS, STRINGS, AND OBJECTS
MATHEMATICAL FUNCTIONS, STRINGS, AND OBJECTS
MATHEMATICAL FUNCTIONS, STRINGS, AND OBJECTS
MATHEMATICAL FUNCTIONS, STRINGS, AND OBJECTS
SELECTION
A program can decide which statements to execute based on a condition

Selection statements use conditions, which are Boolean expressions.


Boolean Types, Values, and Expressions
A Boolean expression is an expression that evaluates to a Boolean value True
or False. Python provides six comparison operators (also known as relational
operators).
SELECTION

The equal to comparison operator is two equal signs (==), not a single equal sign (=).
The latter symbol is for assignment.

A variable that holds a Boolean value is known as a Boolean variable


SELECTION

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.

Generating Random Numbers


The randint(a, b) function can be used to generate a random integer between a
and b, inclusively.
SELECTION
SELECTION
Python also provides another function, randrange(a, b), for generating a random
integer between a and b – 1, which is equivalent to randint(a, b – 1). For
example, randrange(0, 10) and randint(0, 9) are the same.

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.

A one-way if statement executes the statements if the condition is true.

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

The flowchart in Figure illustrates how Python executes the syntax of an if


statement.

A flowchart is a diagram that describes an algorithm or process, showing the steps


as boxes of various kinds, and their order by connecting these with arrows.

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

Two-Way if-else Statements


A two-way if-else statement decides which statements to execute based on whether
the condition is true or false.
SELECTION
SELECTION
Nested if and Multi-Way if-elif-else Statements

One if statement can be placed inside another if statement to form a nested if


statement.

In fact, there is no limit to the depth of the nesting. For example, the following is a
nested if statement:

The nested if statement can be used to


implement multiple alternatives.
SELECTION
In fact, Figure (b) is the
preferred coding style for
multiple alternative if
statements. This style,
called multiway if
statements, avoids deep
indentation and makes the
program easier to read.
The multi-way if
statements uses the syntax
if-elif-else; elif (short for
else if ) is a Python
keyword
SELECTION
SELECTION
The Chinese zodiac is based on a 12-year cycle.
SELECTION
Common Errors in Selection Statements
Most common errors in selection statements are caused by incorrect indentation.
Consider the following code in (a) and (b).
SELECTION
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:
SELECTION

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.

Sometimes, a combination of several conditions determines whether a


statement is executed. You can use logical operators to combine these
conditions to form a compound expression.

Logical operators, also known as Boolean operators, operate on Boolean values


to create a new Boolean value.
SELECTION
Truth Table for Operator not

Truth Table for Operator and


SELECTION
Truth Table for Operator or

Checks whether a number is divisible by 2 and 3, by 2 or 3, and by 2 or 3 but not


both.
SELECTION
SELECTION
Operator Precedence and Associativity
Operator precedence and associativity determine the order in which operators are
evaluated.

Operator precedence and operator associativity determine the order in which


Python evaluates operators. Suppose that you have this expression:
3 + 4 * 4 > 5 * (4 + 3) – 1

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

The operators in arithmetic expressions are evaluated in the order determined by


the rules of parentheses, operator precedence, and operator associativity.
SELECTION
Exercise
SELECTION
Testing the code
SELECTION
SUMMARY
LOOPS
A loop can be used to tell a program to execute statements repeatedly. Suppose that you need
to display a string (e.g., Programming is fun!) 100 times. It would be tedious to type the
statement 100 times. The loop statement can be written as follows:
LOOPS

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.

It is a good practice to code incrementally—that is, one step at a time.

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.

Then figure out how to execute it repeatedly in a loop.


LOOPS
Loop Design Strategies
LOOPS
Controlling a Loop with a Sentinel Value

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

The variable var takes on each successive


value in the sequence, and the statements in
the body of the loop are executed once for
each value.
LOOPS
The function range(a, b) returns the sequence of integers

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

To fix the problem, use


an integer count to
ensure that all the
numbers are added to
sum. Here is the new
loop:
LOOPS
Keywords break and continue

The break and continue keywords provide additional controls to a loop.

Two keywords, break and continue, can be used in loop statements to provide additional
controls.

Using break and continue can simplify programming in some cases.

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

NB: If a function returns a value, it is called a value-returning function


Calling a Function
Calling a function executes the code in the function.

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.

To get a little overview here are a few popular plotting libraries:

•Matplotlib: low level, provides lots of freedom


•Pandas Visualization: easy to use interface, built on Matplotlib
•Seaborn: high-level interface, great default styles
•ggplot: based on R’s ggplot2, uses Grammar of Graphics
•Plotly: can create interactive plots
Data Visualization with Python

matplotlib:
▪python 2D plotting library which produces publication quality figures in a variety of hardcopy formats

▪a set of functionalities similar to those of MATLAB

▪line plots, scatter plots, barcharts, histograms, pie charts etc.

▪relatively low-level; some effort needed to create advanced visualization


Data Visualization with Python
Matplotlib is the most popular python plotting library. It is a low-level library with a Matlab like interface which
offers lots of freedom at the cost of having to write more code.

To install Matplotlib pip can be used:


pip install matplotlib

Matplotlib is specifically good for creating basic graphs like line charts, bar charts, histograms and many more.
It can be imported by typing:

import matplotlib.pyplot as plt


Defining Import Library for Plotting in Python

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

source equivalent of MATLAB.


Example of MATLAB Plot
Type of Plots
Type of Plots
Type of Plots
Type of Plots
Type of Plots
Type of Plots
Type of Plots Barh
Bar

Boxplot Vertical Boxplot Horizontal


Type of Plots
Histogram 2D
Histogram

Line plot
Pie chart
Type of Plots
Scatter plot Polar plot

Stacked plot Stem plot


Type of Plots
Log plot
Subplot plot
Type of Plots
Ellipses Streamplot
Type of Plots
Images
Three-dimensional plotting
Type of Plots
Contouring
Info
NumPy, the numerical mathematics extension of Python
Wireframes and Surface Plots

The keyword arguments rstride= and cstride=


determine the row step size and the column
step size. These keyword arguments control
how close together the "wires" ...
Wireframes and Surface Plots
Matplotlib – Twin Axes
Matplotlib – Bar Plot
Matplotlib – Bar Plot
Matplotlib – Bar Plot
Matplotlib – Histogram
Matplotlib – Histogram
Matplotlib – Histogram
Matplotlib – Pie Chart
Matplotlib – Pie Chart
Matplotlib – Contour Plot
Matplotlib – Contour Plot
Matplotlib – Quiver Plot
Matplotlib – Quiver Plot
Arrays

❖ The fundamental unit of data in any python program is the array. An array is a collection of data values

organized into rows and columns and known by a single name

❖ Even scalars are treated as arrays

❖ 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

array with only one dimension; and

❖ 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

Can you reshape an array?

This section covers arr.reshape()


NumPy in Python
OBJECT ORIENTED PROGRAMMING
Classes and Object

Object-oriented programming enables you to develop large-scale


software and GUIs effectively.

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

In addition to using variables to store data fields and define methods,


a class provides a special method, __init__. This method, known as
an initializer, is invoked to initialize a new object’s state when it is
created. An initializer can perform any action, but initializers are
designed to perform initializing actions, such as creating an object’s
data fields with initial values

Python uses the following syntax to define a class:


class ClassName:
initializer
methods
Classes and Object

Define new class called point

init function: is to create new


point and which information
do l need

self is the point itself or object

set x and y attribute to x and y


value and it stores that value
inside (self.x.y)

The init function is called here


Object-Oriented Thinking
The procedural paradigm for programming focuses on designing functions. The object-oriented paradigm couples data
and methods together into objects. Software design using the object-oriented paradigm focuses on objects and
operations on objects.

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

You might also like