0% found this document useful (0 votes)
2 views57 pages

Python Programing

The document outlines the code of ethics and assessment criteria for students in the Petroleum and Natural Gas Engineering Department at the University of Mines and Technology. It details course objectives focused on using Python for engineering problem-solving and introduces various programming concepts and techniques. The document also emphasizes the importance of programming style, error handling, and the software development process.

Uploaded by

richyaws
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)
2 views57 pages

Python Programing

The document outlines the code of ethics and assessment criteria for students in the Petroleum and Natural Gas Engineering Department at the University of Mines and Technology. It details course objectives focused on using Python for engineering problem-solving and introduces various programming concepts and techniques. The document also emphasizes the importance of programming style, error handling, and the software development process.

Uploaded by

richyaws
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/ 57

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

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
MATHEMATICAL FUNCTIONS, STRINGS, AND OBJECTS

You might also like