100% found this document useful (2 votes)
142 views45 pages

Python for Chemical Engineering Guide

The document presents a book on introduction to Python programming for chemical engineering. The book contains over 180 example codes applying programming to problems in chemical engineering and 50 review problems to consolidate the studies.

Translated by

ScribdTranslations
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
100% found this document useful (2 votes)
142 views45 pages

Python for Chemical Engineering Guide

The document presents a book on introduction to Python programming for chemical engineering. The book contains over 180 example codes applying programming to problems in chemical engineering and 50 review problems to consolidate the studies.

Translated by

ScribdTranslations
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

Sidinei Silva

INTRODUCTION TO
PYTHON FOR
Chemical Engineering
Introduction to Python for
chemical engineering
Sidinei Silva
Department of Chemical Engineering
Federal University of Campina Grande
Introduction to Python for Chemical Engineering
© Sidnei Silva
Edgard Blücher Ltda. Publishing House.

Publisher Edgard Blücher


Editors Eduardo Blücher and Jonatas Eliakim
Editorial Coordination Andressa Lira
Text preparation and review MPMB
Typesetting Author
CapLeandro Cunha

Pedroso Alvarenga Street, 1245, 4th floor

04531-934–São Paulo–SP–Brasil
Tel.: 55 11 3078-5366
contato@[Link]
[Link]

According to the New Orthographic Agreement, as per the 5th edition of the Orthographic Vocabulary of the Portuguese Language,

Academia Brasileira de Letras, março de 2009.


Total or partial reproduction by any means is prohibited without the written permission of the publisher.

International Cataloging in Publication Data (CIP)


Angélica Ilacqua CRB-8/7057

Silva, Sidinei
Introdução ao Pyhton para engenharia química / Sidinei Silva. - São Paulo : Blucher, 2023.
624 p. : ill., color.

Bibliography
ISBN 978-65-5506-671-5

1. Linguagem de programação 2. Python (Linguagem de programação de computador) 3. Engenharia


Chemistry I. Title
23-2143 CDD 005.13

Indexes for systematic catalog:


Programming language
Content

Chapter 1: Introduction to Pythonn .1

Downloading and installing Anaconda1

First steps: getting to know Anaconda– Python3

Defining and using variables5

Tips for using variables.................................................................................8

Using *.py files10

Knowing some internal methods of Python............................................14

Concatenating strings............................................................................................15

Mathematical operations with Python19

Other Numbers21

Requesting information from the user23

Review problems.............................................................................................24

Development problems............................................................................26

Finishing Chapter 129

Chapter 2: Using Lists.....................................................................................31

Understanding lists.............................................................................................31

Accessing elements of a list......................................................................32

Changing elements of a list.......................................................................34

Adding elements to a list.............................................................35

Removing items from a list.............................................................................36


How to organize a list.....................................................................................37

Identifying the size of a list................................................................39

Entering a list through the input command...................................................41

Learning to build and use dictionaries........................................................42

Tuple type declaration.......................................................................................46

Revision problems.............................................................................................47

Development problems............................................................................49

Finishing Chapter 2.......................................................................................51

Chapter 3: First case studies ...................................................................53

Example 3.1 – Replacement of evaporated water....................................................53

Example 3.2 - Colligative properties

Example 3.3 - Estimate the cost of a heat exchanger.................................63

Example 3.4 – Calculation of future value...............................................................68

Concluding Chapter 3.......................................................................................69

References..............................................................................................................70

Chapter 4: For Loop............................................................................71

Structure of the loop...................................................................................71

Loop with range interval..............................................................75

Traversing intervals of a list...................................................................79

Importing some internal functions of Python............................................82

Calculation of the pH of a solution.................................................................85

Returning to the problem of calculating the future value............................................89

Review problems.............................................................................................90
Development problems............................................................................91

Concluding Chapter 4.......................................................................................94

References..............................................................................................................95

Chapter 5: Building Graphs

Using matplotlib..............................................................................................96

Standards for graph markers........................................................100

Using subplots...........................................................................................104

Using functions....................................................................................................110

Building vertical bar charts..........................................................112

Building horizontal bar graphs.....................................................115

Building graph with secondary axis.......................................................117

Building a 3D graph...............................................................................121

Displaying special characters in graphs...................................................124

Review issues...........................................................................................126

Development issues

Concluding Chapter 5.....................................................................................129

References............................................................................................................129

Chapter 6: Conditional Loop if..............................................................................131

Structure of the conditional if loop.........................................................................131

Conditional operators.....................................................................................133

Logical operators..............................................................135

Structure of the if/else conditional loop.....................................................137

Structure of the conditional loop if/elif/else.........................................................139


Review problems...........................................................................................141

Development problems..........................................................................142

Finalizing Chapter 6.....................................................................................143

References............................................................................................................143

Capítulo 7: Repetição com while...........................................................................144

Structure of the while loop................................................................144

Newton-Raphson Method.............................................................................147

Calculation of the radius of a cylinder.......................................................151

Calculation of the friction factor of a pipe..............................................................155

Development issues..........................................................................164

Concluding Chapter 7.....................................................................................165

References............................................................................................................166

Capítulo 8: Outros estudos de caso......................................................................167

Example 8.1: Comparison of state equations.......................................167

Example 8.2: Construction of a titration curve.....................................174

Example 8.3: False position method.............................................................183

Example 8.4: Membrane modules for desalination..........................190

Finishing Chapter 8.....................................................................................205

References............................................................................................................205

Chapter 9: Understanding Programming Concepts...........................................208

Algorithm...............................................................................................................208

Pseudocode

Flowchart
Program................................................................................................................216

Review Problems..........................................................................................218

Concluding Chapter 9.....................................................................................219

References

Chapter 10: Developing Functions..................................................221

Definition of Functions

Passing an argument in the function..................................................................224

Forgetting the argument in the function.................................................................225

Passing more than one argument in the function...................................................226

Leaving an optional argument....................................................................229

Using lists as arguments.........................................................................231

Development issues Part 1...........................................................233

Receiving the result of a function............................................................235

Example of application: returning the result of a function...........................238

Returning more than one result....................................................................240

Importing and using our functions...............................................................242

Scripts with more than one function......................................................................246

Writing functions in different formats.................................................247

Lambda type function............................................................................................247

Lambda function with more than one variable..............................................248

Other constructions with the lambda type function...............................................249

Construction of function with 'decorator'.................................................................252

Recursive function......................................................................................................255

Describing your function.....................................................................................261


Review Problems...........................................................................................263

Development problems..........................................................................264

Finalizing Chapter 10......................................................267

References..............................................................Error! Indicator not defined.

Chapter 11: Importing functions from native libraries...................................268

Overview of native libraries....................................................................268

NumPy...................................................................................................................269

Curve adjustment.........................................................................................................272

Coefficients of a polynomial................................................................................275

Derivative and integral...................................................................................................279

Working with arrays and matrices..............................................................282

Arrays........................................................................................................................283

Matrices....................................................................................................................286

Using the matrix function..........................................................................................288

SciPy

Interpolation

Linear regression.......................................................................................................298

Optimization of a function and root finding.......................................................298

SymPy

Working with symbols.....................................................................................304

Replacing symbols with numbers......................................................................305

Integration, derivation, and limit.................................................................................306

Systems of linear equations................................................................................308

Matplotlib..............................................................................................................311
Pandas

First steps with Pandas

Data storage and loading...........................................................316

Building graphs with database...........................................................319

Review Problems..........................................................................................322

Development problems..........................................................................325

Finalizing Chapter 11...................................................................................326

References............................................................................................................327

Chapter 12: Error Handling.........................................................................329

What is considered a mistake?..........................................................................329

Syntax errors........................................................................................................330

Logic errors...................................................Error! Indicator not defined.

Understanding and handling exceptions in simple programs......................................331

Handling exceptions in for loops.......................................................335

Handling exceptions in while loops...................................................338

Handling exceptions in functions ............................................................................... 340

Why did my function return an error?............................................................343

Review problems...........................................................................................345

Development problems

Concluding Chapter 12...................................................................................346

References............................................................................................................347

Capítulo 13: Impressão e formatação....................................................................348

What is formatting?

Using print with placeholder (%) formatting...................................349


Using separators and finishers..........................................................352

Using the format command in the print function....................................................355

Using the .format command in the print function...................................................357

Printing titles...................................................................................................361

Using literal formatting (or f-string) in the print function.............................362

Using special characters with f-text...............................................................366

Printing tables using print...................................................................369

Printing lines and borders in tables..............................................................375

Printing tables with the tabulate function.....................................................379

Printing lines and borders in tables with the tabulate function.........................382

Importing data from a file and printing a table with the function
tabulate

Review problems...........................................................................................389

Concluding Chapter 13...................................................................................390

References............................................................................................................391

Chapter 14: More case studies.................................................................392

Example 14.1: Determination of roots of an equation of state............392

Example 14.2: Integrating the heat capacity equation....................401

Example 14.3: Systems of linear equations - mass balance.............406

Expanding the viewpoint for linear equation systems..................410

Example 14.4: Constructing a ternary plot.............................................423

Part 1: Review and plotting of the ternary graph for the proposed substances

Part 2: Review, calculations, and plotting of the mixing and rectification/extraction lines
...................................................................................................................................437
Development problems..........................................................................448

Concluding Chapter 14...................................................................................451

References............................................................................................................452

Chapter 15: Exciting Case Studies..........................................................455

Example 15.1: Calculation of compositions in phase separations...............456

Example 15.2: Optimization of the Otto-Williams process............................472

Example 15.3: Ordinary Differential Equations in a reaction of


thermal decomposition.........................................................................................483

Development problems

Finalizing Chapter 15...................................................................................503

References............................................................................................................503

Chapter 16: Control Chart Project ..............................................................508

Understanding the project..........................................................................................508

Overview of data.......................................................................................509

Clarifying the normal distribution...............................................................511

Understanding Statistical Process Control..................................................517

Understanding control charts...............................................................................517

First case: History with reference data (setpoint and variation defined)
519

Second case: History without reference values (setpoint and variation)


indefinite)

Control rules.................................................................538

Project development..............................................................................540

Study proposals
Finishing Chapter 16...................................................................................552

References............................................................................................................553

Appendices

Appendix 1: Anaconda Python Installation..................................................555

Appendix 2: Updating Anaconda Python.................................................562

Appendix 3: Installing the Ternary-Diagram Library.................................565

Index.......................................................................................................568
1
Introduction to Python for Chemical Engineering

Chapter 1: Introduction to Python

In this chapter, we aim to present the graphical interface of


developer that we will use, called Spyder, from the Anaconda® package;
we will see where to find this program and how to install it. We will still see the
first steps in using this fabulous program, getting to know the main features
types of variables that we can use in our thematic area: Engineering
Chemistry! We will use the Spyder console, we will see how to call functions.
internally and we will also develop our first programs.

Downloading and installing Anaconda

Python is a computational tool that professionals from various fields


they are used for solving mathematical problems, simple or complex.
To access this amazing tool, we use the page address of
software distribution [Link] (see theFigure
1.1next).

Quick Box
Access the link above and,
when the page
open, select the
system version
operational of your
computer.

Figure 1.1: Mirror of the Anaconda Python download page.


2
Chapter 1: Introduction to Python

If you click on 'download', the selected default version is 64-bit. If you


click on the logo of the operating system you use, or 'scroll' the page to
below, we will see in more detail that there is the possibility of downloading the program

for three distinct operating systems: Windows, macOS, and Linux.

The program mentioned here will be explored on the Windows® platform. Thus, it is
It is important to pay close attention when choosing the desired version, as in the case of

attempt to install Anaconda on a system version


operational different from your computer, in addition to there being no installation,
future problems will occur in an attempt to install the correct version of
program. Let's seeFigure 1.2follow for more details. The version that
will be used is the most recent and is based on Python 3.0 or higher.

Quick Cash
After selection, the logo
of the system
operational turns gray.
Now click on the
desired version.

Figure 1.2: Mirror of the downloads page after downloading the scrollbar.

After downloading, install Anaconda using all the defaults (selections)


pre-defined) of the windows that will appear. If there are any questions regarding
relation to software access after installation, whether it is just for you or for
all users of the computer you are using, select the option in
which Anaconda should be installed only for the current user, that is, for
you. This will minimize any possibility of errors during the installation.

If you have questions regarding the installation steps, see Appendix 1


from this book for more details.
3
Introduction to Python for Chemical Engineering

First steps: getting to know Anaconda-Python


After the installation process, some icons will be available on your
computer. Among them, the Spyder icon, our developer! Note the
Figure 1.3Logo below to know which icon we are talking about.

Quick Box
After installation, look for the
spyder icon and click on it
Figure 1.3: Spyder access icon. to open the program.

Let's take a look at the development area provided by Spyder.


AFigure 1.4show us an example of this workspace. Let's move on.
through the main parts that make it up so we have a better understanding of where
the essential mechanisms for using the tool are. Note that the
the Spyder interface on your computer should appear in dark mode because it is
the standard installation version. Dark mode improves contrast and reduces the
eye strain due to reduced brightness. We use the light version in this work
just for educational purposes. If you prefer to use the same version presented here,
go to "Tools/Preferences/Appearance/Syntax highlighting theme" and, in the list
suspense where the description 'Spyder Dark' is found, select Spyder, click
click on "Apply" and then "OK".

Quick Box
1–Write your
codes here;
2 2–Explore as
active variables;
3–Here are
1
printed the
results.
3

Figure 1.4: Main window of Spyder.


4
Chapter 1: Introduction to Python

Every time you open Spyder, this area appears. In it we have, in a way
very summarized, three essential parts. Box with the number 1: File
temporary that can be edited so that our programs are saved
in the future. We will work a lot with it further ahead.

The box with the number 2 refers to one of the available tabs called
"Variable Explorer". In it, you can observe
any variable that has been created during the execution of some code.
This makes it easier to identify if the variable exists, if it is in the right format,
size or type is correct, if the value recorded in it is correct, etc. Do not
Don't worry! We will also look at this tab and its content in more detail.

In the box with the number 3, we have the console, which functions as a
calculator, if we want to do some quick calculation. Just type in some
value and press "Enter" for the result to be printed on the same screen right away
next. She is also responsible for presenting the results of any
program that runs in the development area (box with the
number 1).

Don't worry if the interface on your computer has a color


different from the one that was exposed in theFigure [Link] intentionally placed the
white interface to facilitate the visualization of the codes here in the book. A
dark screen is preferable for programmers as it reduces the amount and
intensity of white light. If you want to change the color of your interface
Spyder, follow the path: 'Tools/Preferences/Appearance/Syntax highlighting'
Select the "theme" and choose your preferred theme.

"In [1]", "In [2]", "In [3]" in the console indicates "Input", which means input.
of information. In order to demonstrate the functionality of the console, we are going to write

our first command: print( )! This command is an internal feature


in Python, it is used to print a blank line or print when
properly filled in, any argument that is between the parentheses.
Write the command line in your console as shownSee Figure 1.5:
5
Introduction to Python for Chemical Engineering

Quick Box
No console, use the function
print() in Python for
Figure 1.5: First command using the Console.
run your first code.

You should have a result similar to that of theFigure 1.6after pressing 'Enter'.

Quick Box
After pressing 'Enter', see the
result of your first
code in the console itself.
Figure 1.6: Result of the print command in the Console.

Try to repeat the command print( ), now putting your name as


argument! The argument is any value or variable that you place between the
parentheses of the function print( ). Note: for the command to be executed
correctly through the console, it is necessary to use quotation marks (") or apostrophes ('') before and

after the text (e.g. your name) that will be used.

Defining and using variables


A variable is an element that carries a certain piece of information entered.
by the programmer, in this case you, or another user who is using your
program or by the program that is being executed. Let's define
our first variable named "message". This variable called
I want to program!Figure 1.7to follow
We observe that we are still using the console. Right after the insertion of the variable.
And from the suggested text, press 'Enter'.

Quick Box
Store a text between
quotes in the variable called
Message me press "Enter".
Figure 1.7: Writing a variable to the console.
6
Chapter 1: Introduction to Python

Observe in the Variable Explorer a table format. In it, we have the name
of the variable, the type, the size, and the value that is stored in the variable. In
in our case, after the insertion of our first variable, you seeto Figure 1.8,
in which the variable name is mensagem, of type "string" (text) with size
unitary and with the value equal to "I want to program!".

Quick Box
See in Variable Explorer
that the text written now is in
computer memory.
Figure 1.8: Variable Explorer.

Now that the variable message is in memory of Spyder, we can use it.
it while the program is open. This variable is volatile! But what does that mean?
What does that mean? This is the behavior of the variables that are loaded by
Spyder when executing a command, whether in the console or in some
program in the developer, and remain temporarily active in the Explorer of
Variables while Spyder is open. But when Spyder is closed,
these variables disappear from memory. If you close Spyder and open it again,
you will see this behavior more clearly.

Let's conduct a new test. In the console, use the command print( ) and put
As an argument, the name of our first variable: [Link] 1.9
illustrate this procedure.

Quick Box
Use the print() function to
show the content of the variable
message in the console.

Figure 1.9: Calling and printing variables.

You can also just write the name of the variable in the console and press
Press 'Enter', as Spyder will print the content of this variable (seea Figure 1.10).
7
Introduction to Python for Chemical Engineering

Then you might ask yourself: 'If the console prints the content of the variable that
I write, why use the print() command? The answer is that the command
print() is used to format (print elegantly, with characteristicsQuick Box
pre-defined) an impression that your program willTomake
identifyinin the
a wayfuture. Seo

the moment only requires checking the content ofquick or the content of a
a variable, that's all
variable, just write it in the
write it in the console and press 'Enter' for its content to be displayed.
console and press "Enter".
We will have Chapter 13 just to learn how to use some of the various
functionalities of the commandprint( ).

Figure 1.10: Printing the content of a variable.

Variables can also receive numbers. And these variables can be


manipuladas de forma que seu conteúdo seja utilizado em algum cálculo
specific. For example: x = 1 and y = 2, if we add x + y, the result appears.
no console. This happens because the value 1 was stored in x and the value 2 was
stored in y. These two variables are distinct and independent of each other.
another, which can be used in various parts of a code. Note the
examplein Figure 1.11next.

Quick Box
In addition to text, the variables

they can also store


numbers.

Figure 1.11: Variables storing numbers.


8
Chapter 1: Introduction to Python

Tips for using variables


Aiming for the correct use of variables, we will see some tips on how
name a variable minimizing potential reading errors of the software
Spyder. Here are the tips:

• Variable names should be written in such a way that they have only
letters, numbers, and underlines, but no special characters
like ç, %, &, *, $, #, @, !, ‘’, “”, ?, ;, [, ], <, >, ^, /, +, -, (, ), words
with accentuation or any other special character that you can
find
• They can start with a letter or an underscore, but not with a
number. For example, we can call a variable message_1,
handof1_message
• Do not use spaces in variable names. If necessary, use
underscores to separate words in variable names. For example,
the first_message works, but the first message will cause an error
of indefinition, that is, it is as if you were writing two
consecutive variables, but only assigning value to one of them. How
the other one remains empty, the console responds to this undefined with a

error message;
• Do not use words that Python has reserved for built-in functions.
ins).Por exemplo, digamos que você tenha esquecido essa dica e escreva
no consoleprint= 5. Then you try to use the command print(print)
to print this number. How you overrode the functionality
from the print() function for a value, at the moment you execute your
code, the console will return an undefined error. In other words, you said
the Python print function no longer had the function of printing, but rather of

load the preset value 5. Try to learn as much as possible from


names of the internal functions of Python that this type of error never gives you

will bore
9
Introduction to Python for Chemical Engineering

• You should use concise and descriptive names for the variables. This means
to say that you don't need to write a huge text to define a
only variable. It should also not use only letters, otherwise, in
in a future moment, you will not know what that "d" in your code
represents. For example: name is better than; student_name is
better what n_e; tamanho_nome é better what
tamanho_do_nome_da_pessoa;
• There are exceptions, such as in the use of letters in counters.
of loops. In this case it is acceptable because the variable that is
being used is limited to the use of the loop (which we will see with more
details in the upcoming chapters);
• Be careful when using the lowercase l and the uppercase O, because
they can be confused with the numbers 1 and 0;
• Python is case sensitive! 'What does that mean?' It means that the
Python treats lowercase and uppercase as distinct things. If you
writeMessage instead of message, an error will appear in
console informing that the variable message was not defined (see the
Figure 1.12).The error message is called Traceback. It will assist you.
indicating the cause or the possible position of a potential error in your
code.

Quick Box
For Python,
lowercase letters
are different from the
uppercase.
M≠m
Figure 1.12: Error of lowercase and uppercase letters.

• Another typical error that may occur is when we forget to type.


some letter of the variable name. For example: message is different from
message. Note theFigure [Link] variable message was not defined
10
Chapter 1: Introduction to Python

previously, so the error message appears in the console. In this


In case, a 'NameError' type error occurred.

Quick Box
Python does not complete
words. In case you forget
to write something
letter, an error will occur.

Figure 1.13: Error when a letter is missing.

Using *.py files


Just like a text editor, e.g. Microsoft Word®, Spyder uses files
to store the codes developed by programmers. These
.py files. The asterisk here represents the name
of the file, which can have any name. But be careful! The rules of
file naming must be the same as variable naming, such as
seen before.

When you open Spyder, if there are no previous applications,


by default, the program opens a temporary file called [Link],
accordingFigure 1.14.

Quick Box
This is a temporary file.
You don't need to use it.

Figure 1.14: Developer's temporary file.

You do not need to edit this file. We will create a file and save it with the
first_code_name.py. First, look in the upper left corner
11
Introduction to Python for Chemical Engineering

dFigure 1.14the image of a page with a folded edge. Click on this


button to create a file. By default, the file is named
with [Link] (ousemtitulo0 in the Brazilian Portuguese version), seea the Figure
1.15next.

Quick Box
Can you create a
new file, which will already come

with a standard header


and will contain your name and date

of creation.

Figure 1.15: New file named [Link].

To rename the file or save it in a location of interest, click on the


top left corner in (File). A new dialog box will appear.
Look for Save as and click on it. Save the file with the
previously suggested name, first_code.py, in some place of interest
on your computer. Observe theFigure 1.16for more details.

Quick Cash
To rename your
file, just click on
“File” e procurar por
"Save as". A new box
the dialogue will appear there
you must rename your
file.

Figure 1.16: Saving a new *.py file.


12
Chapter 1: Introduction to Python

Note that in our new file there is a text in gray (line 1) and
another text next in green. Both texts are comments! They are
explanatory parts, or information, that we can add to our code
in such a way that they may serve as aids for understanding in the future
code itself. These comments are not executed when you run it.
your code. By default, Spyder sets the current date and the name of the active account
no Windows®.

If you want to modify this template (reference file), just follow the
pathTools/Preferences/Editor/Advanced Settings and click the Edit button
Template for New Modules. The reference file will be opened in the editor and there
you can modify the pattern as desired. If there is any
modification, to save the modified file, click the Save button according to
mostsee Figure 1.17.
Save Button

Play Button

Figure 1.17. Template used by Spyder.

With the name of our modified file, let's now write our
first executable code. For this, we just need to write in the area of
develop a message with content and ask Python
print this message. After entering the code, save it by clicking on the icon
"Save". Observe the result nFigure 1.18next.
13
Introduction to Python for Chemical Engineering

Quick Box
The example next to it shows the

definition of a variable
that stores a text and
it will be printed next

Figure 1.18: First code in a *.py file. with the command print( ).

From what we have seen so far, the code insertedin Figure 1.18It's easy to understand.
In it, a variable message receives text on line 8, and on line 9, we are
asking Spyder to print the content of the variable message. Now
It's time to execute the code. To do this, just look for an icon in the bar.
of tasks with a Playverde format. Click on it and see the result on
console. It must be something similar to what is displayed in theFigure 1.19.

Quick Box
After clicking on Play you
you will see the printed result

no console.

Figure 1.19: Result of the execution of our first code.

Do not be alarmed by the content exposed in theFigure 1.19!What is printed

in green is nothing more than the path that Python had to follow to find
your file and run it. Remember: the graphical interface is from Spyder, but
Behind it all, Python is the one executing everything! Notice that right after the green lines

it is printing the content stored in the variable message.

The good thing about developing in a *.py file is that you can execute it.
as many times as necessary without loss of information when
turn off the computer. You can also edit the file, adding more
lines of code according to what's necessary to solve some of the problems
of Chemical Engineering.
14
Chapter 1: Introduction to Python

Believe me, some will be solved in just a few lines of code like the
demonstratedin Figure 1.18,but other problems will be more elaborated and will have
hundreds of codes and will depend not only on a single *.py file, but
of several others.

Apply what you learned:

1–Create a module (file *.py) and save it with a desired name;


2 –Store a message (any message) in a variable in the
newly created module;
3–Write a code so that the message is printed;
4–Execute your code and see the result in the console.

Knowing some internal methods of Python


Just like the internal function print() (we call it internal or native because
it is part of the Python package, regardless of the interface being used), the
Python loads several other functions and methods as we will see in the next ones.
chapters. The difference between a function and a method is that the function, here
described, may need an argument for it to be used. A
method is usually a characteristic that is inherent to a variable as soon as
she is raised.

For example: a string type variable can contain formatting methods


of the content that is saved in the mentioned variable, such as the methods .title(), .upper()

let's see this application in more detail below.

Quick Box
.title( ), .upper( ) and
.lower( ) are editors
Figure 1.20: Examples of internal methods of Python. applied to the variables of

Every time you place a dot '.' right after a variable, it will appear
a small dropdown list with suggested methods that can be used.
In our case, we use the title() right after the dot. Pay close attention to
15
Introduction to Python for Chemical Engineering

Figure 1.20that the variable [Link]() feeds the internal function print(). You
You can, without worry, use a function as an argument of another.

Python, like other current programming languages, solves


first what is inside the parentheses so that, then, execute the
external functionalities. The same explanation can be applied to the
other methods presented.

After running the code shown in theFigure 1.20,the printed result on


console shows a first impression with the first letters of each name
in uppercase, refers to the method .title(). In the following print line,
we have both names printed in capital letters, which is the result of
application of the method .upper() and, finally, in the third line of printing, we
we have the names printed in lowercase due to the use of the method
lower( ). See this resultin Figure 1.21.

Quick Box
See the result of the
application of .title()
.upper( ) and .lower( )
Figure 1.21: Result of using some internal methods of Python. respectively.

Concatenating strings
Often, it will be convenient to concatenate (combine) strings. For example,
you may want to store a first and a last name in variables
separated and then combine them when you want to display the text in full. Create
a file, and name it name2. Note the lines of code in theFigure 1.22
and try to reproduce them in your developer. To minimize the exposed content
in the Figures, hereinafter, in this chapter, when it is necessary to show
any image of the development area will not be presented
first lines of comments already mentioned.
Quick Box
Concatenation using
just the function print( ).
16
Chapter 1: Introduction to Python

Figure 1.22: String concatenation.

Note that lines 1 and 2 show texts separated in the variables name_1 and
nome_2, os quais juntamos ao texto “Eu escolhi” na linha 3 com o auxílio da
internaprint( ) function. It is possible to concatenate each of the variables simply
to separate them by comma.

Python uses special codes to skip lines or apply indentation in


texts that will be printed on the console. Observe the lines of code from theFigure
1.23The code is a continuation of the example already [Link] 1.22.

Quick Box
Skipping lines
(╲n) and applying
tabulation (╲t)
Figure 1.23: Skipping lines and applying tabulation.
no Python.

The line 4 dFigure 1.23shows an empty print(). This means that the console
it will print a line with no text at all. In line 5 we have a new sentence
I will learn:n-Programming in Python!”. When we execute this
program, the console will display the text 'I will learn:' on one line and on the line

following the continuation 'Programming in Python!'. The element '╲n' is the


responsible for this "jump".

Still in theFigure 1.23line 5 shows a variation of print( ) already presented


on line 4, but now with a new term: '╲t'. This element is responsible
for applying a tabulation to the text "Programming in Python!". See more
details of this applicationin Figure 1.24.
17
Introduction to Python for Chemical Engineering

Quick Box
See the result in the console
when is the tabulation applied
or when it is necessary to jump
a line.
Figure 1.24: Results of line break and tabulation.

If you want to concatenate variables before printing them, it is necessary to pay attention.

regarding the type of variable you are working with. Let's observe
the presented codein Figure [Link] line 3, we have a sum of variables!
That's right: to concatenate them, just add them considering
that they are of the same type.

Quick Box
Concatenation adding
string type variables.
Figure 1.25: Direct concatenation of variables.

Click on the big Play button to run your code and notice that only one word
it was printed on the console: chemicalengineering. Ah! But we don't want the
words will come out grouped in this way when printed along with the
results. We need to apply a 'space' between these words. Let's observe
now the code of theFigure 1.26.

Quick Box
Use apostrophes, or quotes,
to apply spaces between
Figure 1.26: Adjusting the direct concatenation. the words in the concatenation.

It seems that we have the same code already presented in theFigure 1.25, con everything, the
the difference is in the sum presented in line 3. Note that we are now
adding a "space". Adjust your code and press the Play button again to
see the difference.
18
Chapter 1: Introduction to Python

You might be wondering: 'What if we have a number in one of the


variables, how do I do it? Well, you can use the simplest way
previously presented in theFigure 1.22and Figure 1.23,for example. Or
you can concatenate it with the text using a new internal function of
Python, calledstr( ). Note the example code in theFigure 1.27.

Quick Box
Usestr( ) for
transform
Figure 1.27: Converting number to text. number in text.

Na linha 1 temos um número, na linha 2 temos um texto e na linha 3 estamos


concatenating the text to the number. To avoid errors, we need to
transform the number into text. This is the function str() that transforms the

content of the variable press text. Another way to perform concatenation is


use a "comma" inside the print. It will be responsible for separating the
different types of variables and the printf function itself will perform the task of joining them

involved parties. Example: lines 3 and 4 of theFigure 1.27can be


replaced by the following line of code:

print("The pressure value was", press, unit)

In case you forget to apply this transformation and run your code, the following
an error will appear in your console: "TypeError: must be str, not float". This is the error

What tells you that you are trying to combine variables of different types, which the
Python does not accept! Translating the error message, we have: 'Type error: A'
variable must be text, not number. At the end of your studies in Python you
will be familiar with these small details.

Apply what you learned:

In a new file called name_cases.py program the following situations:


19
Introduction to Python for Chemical Engineering

Personal message: store a person's name in a variable


e apresente uma mensagem a essa pessoa. Sua mensagem deve ser
simple, like: "Hello Maria, would you like to learn a little about
Python today?
2. Uppercase and lowercase letters in names: store the name of a
person in a variable and then present that person's name in
lowercase letters, in uppercase letters and then only with the first one
uppercase letter.
3. Write a sentence that can be concatenated with the variable Temp =
325K. Print the result of the concatenation.
4. Remember to use each combination of characters, " ╲t" and " ╲n", by
one less time.

Mathematical operations with Python


Numbers are used very frequently in programming to solve
engineering problems, represent data in visualizations, store
information in web applications and so on. With the operators that already
we know, we can add (+), subtract (-), multiply (*) and divide (/)
numbers in Python.

For this, just use the console directly, if you want to use it as a
calculator, or program the desired operations in some new module in
editor. Observe aFigure 1.28and see the result of some applications.

It is important to emphasize that in Python, just like in countless others


engineering software, the operator "." represents the decimal point, e.g. when
we write 5.0 (five point zero in Brazilian Portuguese) we will have the same
value written as 5.0 (five point zero) due to the basis of mathematical operation
be foreign. Just observe the data input In[22]in Figure 1.28to which
show division 3/2. The result (Out[22]) of the operation will be 1.5, or 1.5 in
console.
20
Chapter 1: Introduction to Python

Quick Box
No console, use os
mathematical operators
for the realization of
simplified calculations.

Figure 1.28: Basic mathematical operations with Python.

If you want to write 10,000 (ten thousand) in Python, you will have to remember this
rule and rewrite this value as 10000, without the point "." that defines the thousand.

To represent the exponential, use '**' (double asterisks) in series. In case


If you want to use scientific notation, use 'e' between the numbers. Note theFigure
1.29where the applications are illustrated 23(2x2x2) and 5x103(5,000).

Quick Cash
To apply an exponent,
utilize '**'. In the case of
scientific notation, Python
accepts 'e' or 'E'.

Figure 1.29: Exponent and scientific notation in Python.

The Python language allows us to specify the order of execution of


mathematical operations in an expression (function). For this, we must use
parentheses to apply the order of execution of mathematical operations
what we wish. Therefore, what is in parentheses will be calculated first
by Python. If there is more than one consecutive pair of parentheses, the pair most
the inner will be executed first and then the outer.

Note that this rule is not limited to the use of the Spyder console. It also
will be followed when we develop our programs in some module in
developer. This is a standard rule already used by several software of
engineering. See the example in theFigure [Link] the input In[26], we have 9**1/2.
21
Introduction to Python for Chemical Engineering

At first, we might think it would be the square root of nine. However, the
Python, by internal priority order, performs multiplication first. By
the result in the console appears: Out[26]= 4.5!

If we really want to calculate the square root, we need to tell Python


that first calculates the exponent of the numerator and that is why we use parentheses.
Note that the desired result is achieved when we write 9**(1/2) in
inputIn[27]. The same logic applies in inputIn[28] of the console. The
multiplication is done first, and then addition takes place.

When we put the parentheses, the sum is carried out before there is a
multiplication. If you want Python to perform a given calculation in a
pre-determined order, use parentheses.

Quick Box
If you want to determine the
order of operations
mathematics, apply
parentheses in your equation.

Figure 1.30: Modifying the order of execution of mathematical operations.

Other Numbers
In the previous examples, we had the experience of dealing with the variable of type
strings, also, as presented in theFigure 1.29eFigure 1.30we saw the
called integers as input values for the desired calculations.
The different types of variables exist to avoid overload of the
computational system. "What do you mean?" Would you pay for a sheet of paper for a
same amount needed to buy a car? I believe your answer
don't be! In the same sense, the computer does not use the same amount of
memory to store a number or text. This means that, for
22
Chapter 1: Introduction to Python

to store text, Python "borrows" an amount of memory from the


your computer much smaller compared to the amount needed to
store an integer number.

When it is said that Python 'borrows' a certain amount of memory


of the computer, it is because the variables have a finite lifespan. In other words, the
variables of your program, just like all the others that are now
running on your computer, are managed by RAM memory
(Random-Access Memory), which the computer uses to perform calculations.
If you close the Python program, or the computer is turned off, the data
that are in RAM memory are lost.

If you want to store all the information recorded in the variables in some
a place where I can access them again at a later time, we will have
to record this data in a file in ROM (Read-Only Memory)
Memory) which is the storage and reading memory of the computer.
Veremos esse procedimento mais detalhadamente em um momento oportuno.

Going back to our different types of variables that Python works with.
Among the numbers, there are also the so-called floating-point numbers.
These numbers require a much larger space in memory compared to
to the integers. Note that a greater effort is required to store
a value like 2.698547854052154 compared to the number 2.

If you are interested in knowing what type of variable you are dealing with, just
check the 'Variable Explorer' panel, already presented earlierthe Figure
1.8you use the internatype() function in the console. The variable of interest is the
necessary argument for the operation of this function. Let's see its
applicationin Figure [Link] variable press was used to store the value of the
pressure in example dFigure 1.27mentioned earlier. Observe in the result
that this number is of the type 'floating point' (float). To know what value it is
stored in it, just write it in the console and press "Enter".
23
Introduction to Python for Chemical Engineering

Quick Box
Use type() to know which
it is the type of the variable.

Figure 1.31: Identifying the type of variable.

We will see other types of variables later on.

Requesting information from the user


Many times you need to request information from the user. For them to
"Enter" with this information in the program that is running, it is necessary
Caixa Rápido
use the input() command. See the code example of the Useinput( ) para
decipher what this code does. request information
to the user. The
information comes in
like text!

Figure 1.32: Requesting information from the user.

In line 1, we have a comment! When you click on Play, Python 'jumps'


any comments as they are not interpreted as code line.
In line 2, there is a variable called 'temp' that will receive information from

user, this is using the console, through the function internainput(). Line 3
presents the variable chamadamsg, which stores a string. In line 4, nothing
It was written. In line 5, one more comment.

Line 6 presents another variable called tempK. It is responsible for


store the result of the temperature value conversion into Celsius,
entered by the user, for Kelvin. And finally, line 7 that prints the
message contained in the variable msg, concatenating it with the stored value
in the variable tempK.
24
Chapter 1: Introduction to Python

Pay close attention to one detail: the commented programin Figure 1.32will only outline
the results of line 7 if you enter the requested value in the console! See the
result of the execution of your code nFigure 1.33to follow. Quick Box
When executing a program
what contaminates input( ), or

console waits until the


user enters with the
Figure 1.33: Requesting information from the user. requested information.

Notice that there is a text requesting an input! It is you, as the user,


you have to insert the requested information. Otherwise, you will think that
your program crashed, as it will only terminate the program when you enter
the information or when the Spyder is closed.

Pay attention to a red 'square' in the upper right bar of theFigure


[Link] small square is indicating that Python is 'running' and still
it didn't stop. When you type the temperature on your numeric keypad, this
the small square will be gray again.

Review issues
1.1. Write, in your own words, what each of the native functions does.
Python lists below:
• print, title, lower, upper, input, str, float.
1.2. What characters should be avoided in *.py file names?
1.3. What is the best way to name a variable? By which
reason?
[Link] a code that asks the user for the name of a reagent. This
text must be printed in the following formats:
a) Title;
b) Upper case;
c) Lowercase.
25
Introduction to Python for Chemical Engineering

[Link] os diferentes tipos de variáveis que você conheceu neste capítulo.


Explain when they should be used and if it is possible to mix the different ones.
types of variable.
1.6. What do you understand by text concatenation? Explain when
We need to use this type of procedure.
1.7. What is the difference between an integer type variable and a variable of type
float?
1.8. Many times we can skip lines without having to write "\ ”
several times within the command print. For this task, it is enough that you
write in your code, for example, print(3*"\ ) that, when executed,
Python will understand that you want to skip 3 lines. This works for
any integer multiple. Knowing this detail, develop a code that
request two equipment names from the user. After the insertion of these
texts, your code will print these names in uppercase, but there will be a
five lines gap between each print.
1.9.A student in the applied computer science class is having difficulty with
to find an error in a newly developed code. When asking what
The student wanted to do it, he replied the following: "My code should perform the
following steps:
a) Request the 1to the user;
b) Requested 2to the user;
c) Calculate the value = 1/(1 + ( 2))
d) Imprimir o resultado com um texto bacana.
However, an error appears saying that it is not possible to use a
mathematical operator with texts.
Based on your knowledge acquired up to this moment,
develop a code that repeats the steps commented by the colleague and points
What was the mistake he was making during the development of
code that generated the described output. Note: the native function abs(x)
returns the absolute value of the value x.
26
Chapter 1: Introduction to Python

1.10. What is the difference between developing code in a script


develop a code in the console?

Development problems
1.11. In a new file called [Link] program the following
situations:
a. Write the input() command to request the temperature in° ;
b. Convert the previously entered temperature to° with a
following equation:

( ° ) = 1.8 (° ) + 32 (Ex 1.1)

c. Write a variable that receives this information by concatenating it.


in a friendly sentence;
d. Print the sentence formed in the previous item.
1.12. Develop a code that requests the following items from the user:
a) Name of the reagent;
b) Value of the mass of a reagent;
c) Volume of the solution;

Your code should calculate the common concentration ( = / )e


print, for example, the following sentence to the console: 'The solution of
NaCl has a concentration equal to 25.0g/L
1.13. potassium nitrate (KNO)3) is a reagent that can be used in
smoked meats, or sausages, such as sausages and sausages, to avoid
the proliferation of the bacteria that causes botulism. The said reagent also
it serves to enhance the color and flavor.

Considering the above, write a program that:


a) Ask the user for the concentration in amount of substance,
( );
b) Request the user the volume of solution that should be prepared,
( );
27
Introduction to Python for Chemical Engineering

c) Print the result of the necessary mass of the reagent for the preparation
of the solution ( 1( )= . . Where MM is the molar mass of
compound, g/mol.
1.14. Use the print command to print the following items:
a) Msg = “Aprendendo Python!”
b) Massa = 54,86 kg
c) Pressure = 85.89kPa
d) A = 15,0; B = 985,9; C = B/A
e) x = 2.5; use x in the function = 2– 10 The value f(x) = result
of the fx

1.15. Develop a code that:


a) request the user for the value of x;
b) calculate the function ( ) = 2− 10 + 10;
c) print the result to the console so that it appears as follows
way: For = 0, we have ( ) = 10.
d) your code should perform the calculation of ( ) for any value of
and print these different values.
1.16. Develop a code that calculates the volume of a tank with
cylindrical format according to the following equation:

2ℎ (Ex 1.2)
=
Your code should request the radius r and the height h from the user and print the
calculated volume V in the console.

1.17. Develop a code that calculates the volume of a tank with a base
hexagonal according to the following equation:

2√
3
=6 ℎ (Ex 1.3)
4
For the calculation to be carried out, your code must request the value of
side L of the hexagon and the height h to the user. The result of the volume
calculated should be printed to the console.
28
Chapter 1: Introduction to Python

1.18. Potassium permanganate KMnO (Molar mass = 158.027g/mol) is


a colored reagent that can be used for the determination of iron in
aqueous solution through a redox reaction. Develop a
Program that requests the user for the mass of the reactant and the volume of the solution.

After this step, your code should calculate the concentration in quantity of
subject:

1
= (Ex 1.4)
×
and print the result in the console concatenated with the following phrase: "A "

concentration in quantity of material solution is 'calculated result'


mol/L.
1.19. Considering an ideal state, develop a code that calculates and
print the pressure of methane gas (Molar mass = 16.043g/mol)
stored in a gas cylinder, with a volume of 25L, and that stores
a mass of 2Kg of gas at a temperature of 293.15K, using the
following formulas:

= (Ex 1.5)
= 1/ (Ex 1.6)
Where it is the pressure to be calculated (in atm); it is the volume of the gas (in

Liter ), n is the amount of substance (in moles, calculated by Ex 1.6); é


the constant of ideal gases (0.0820574587 in [Link]/mol.K) and is the
temperature in Kelvin (K); m_1 is the mass in g of the substance and MM is
molar mass. Pay attention to the order in which the values should be presented
Python script so that the equations work when you run it
your program.

1.20. An engineering team estimated that, as of today, the cost of


acquisition of a cylindrical stainless steel vase 360, with a capacity of 10L,
is R$ 87,500.00. However, the immediate supervisor postponed the investment in
5 years. Considering that the current interest rate of 8.5% does not change.
29
Introduction to Python for Chemical Engineering

during this period, develop a code that calculates the future value of
investment with the help of the following equation:

= 1( + ) (Ex 1.7)
Where it is the future value (R$); it is the present value (R$); it is the interest rate
(dimensionless) and it is the number of years.

1.21. The two real roots of a quadratic function 2+ + = 0(where


it is different from zero) is calculated by the following equation:

− ±√ (Ex 1.8)
=
2
where the discriminant = 2− 4∗ ∗ Write a program that calculates
and return the roots of a quadratic function. For this, your program
must make the user enter the values of , and .

Finalizing Chapter 1
In summary, in this chapter we get to know the graphical interface of Spyder-Anaconda
that uses the Python language as the standard programming language. We also gave
the first steps in variable manipulation when we store them
chamadasstrings. Usamos o console do Spyder para imprimir pequenos textos
and we also learned to store our codes in *.py files.

We wrote our first programs using internal methods of


Python, such as, print( ), title( ), lower( ), upper( ). We learned to
concatenate words, skip lines (╲ ) and apply tabulation (╲ ) so that, in the
console output, the texts become more organized. We use the console
to perform simple mathematical operations with numbers, as well as to
print small texts concatenated with numbers.

We know how to request information from the user using the input() method, besides
of writing programs using other internal methods of Python, such as
30
Chapter 1: Introduction to Python

for example, str() and float() for standardizing the type of variable that will be
printed on the console.

In the next chapter we will see how to build another type of variable called
lista. Como manipular esse tipo de variável bem como aplicá-la em exemplos
practical.
The present work can be adopted by beginner students of the courses of
chemical engineering or those who are already in the professional phase of
course. It can also serve as a reference for already graduated engineers.
once the user has this work in hand, depending on the
level of knowledge in programming, will start your studies from scratch or
will review programming content previously explored in other languages by
through access to various real examples of programming applications in
problems of chemical engineering.
In addition to the more than 180 codes of various examples, during the
chapters, you will find more than 50 review problems to consolidate the
studies conducted and more than 60 development problems for you
you can broaden your view of programming [Link] will also have
access to the example codes provided in the chapters so that you can
use them and run them on your computer, simply by going to the website of
editor, look for this book and find the topic "support material".With
withtheexamplecodesinhand,youwillalsobeabletotakeadvantageofpartsof
codes that are already ready to help in solving the exercises during
your studies or, furthermore, optimize them by giving your contribution.

Sidinei Silva
Professor with a PhD in Chemical Engineering.
involved in the development of applications, based on Python programming,
in research in the field of industrial property, economic analysis of
processes, analytical chemistry laboratory and classification of areas. It is also
laboratory coordinator Radar - Research and Industrial Innovation with
filed patents, development of for assistance with writing
on patents and guidance of undergraduate students in initiation projects
[Link]
is part of the teaching staff of the undergraduate course in Chemical Engineering
from the Federal University of Campina Grande - PB.

Common questions

Powered by AI

To concatenate strings with spaces, you can add a space character (' ') between strings. A common pitfall is forgetting to add such spaces, which results in words being grouped together without separation. This can be avoided by adding a plus (+) operator with a string containing a space or using commas within the print() function for auto-spacing .

Using the ideal gas law (PV = nRT), develop a Python program that accepts inputs for volume (V), temperature (T), and mass (m) of gas, converts mass to moles (n = m/MM), and calculates pressure (P). You incorporate constants such as the gas constant (R = 0.0820574587 L.atm/mol.K) to perform these calculations, then use print() to display the result .

User interaction in Python is achieved through the input() function, which allows programs to receive input from users. These inputs, usually strings, can be converted into the appropriate data type (e.g., int or float) for subsequent calculations or processing .

The print() function in Python is used to format output, allowing you to print messages in a readable and organized manner. Although simply typing a variable's name in the console will display its content, the print() function is preferable for structured output, especially for future program developments that require specific formatting. It is omitted when only a quick check of a variable's content is needed .

To compute the future value of an investment in Python, you need to use the formula F = P(1 + r)^t, where P is the present value, r is the interest rate, and t is the number of years. Accept input values for these parameters, apply the formula, and then print the calculated future value .

The '\n' is used to create line breaks in text output, effectively inserting a 'jump' to the next line, while '\t' adds tabulation or horizontal spaces in the console output. These elements are used to organize outputs and improve readability by structuring the text in user-friendly ways .

Developing code in a script means writing a .py file that can be saved and executed as a complete program, allowing for comprehensive program structuring and reuse. In contrast, console development is more ad-hoc, suitable for testing small code snippets quickly. Script development has the advantages of version control, complex structure capabilities, and reusability, while consoles are useful for immediate feedback and testing .

To improve visibility while coding in Spyder, especially reducing the strain of white light, you can change the appearance settings to a dark theme. This is achieved by navigating to 'Tools/Preferences/Appearance/Syntax highlighting', selecting the 'theme', and then choosing your preferred dark theme option . Such adjustments facilitate better visibility and reduce eye strain.

To develop a program for calculating the roots of a quadratic equation, follow these steps: 1) Use input() to get coefficients a, b, and c from the user; 2) Calculate the discriminant (b² - 4ac); 3) Use the quadratic formula (-b ± √discriminant)/(2a) to compute the roots; 4) Print the results. This involves managing both real and complex roots depending on the discriminant .

Before concatenating a numeric variable with a string in Python, it's crucial to convert the number to a string using the str() function to avoid TypeErrors. This conversion allows the numeric value to be treated as a text string, thereby enabling seamless concatenation with other text strings .

You might also like