Python for Chemical Engineering Guide
Python for Chemical Engineering Guide
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.
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,
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
Concatenating strings............................................................................................15
Other Numbers21
Review problems.............................................................................................24
Development problems............................................................................26
Understanding lists.............................................................................................31
Revision problems.............................................................................................47
Development problems............................................................................49
References..............................................................................................................70
Review problems.............................................................................................90
Development problems............................................................................91
References..............................................................................................................95
Using matplotlib..............................................................................................96
Using subplots...........................................................................................104
Using functions....................................................................................................110
Building a 3D graph...............................................................................121
Review issues...........................................................................................126
Development issues
References............................................................................................................129
Conditional operators.....................................................................................133
Logical operators..............................................................135
Development problems..........................................................................142
References............................................................................................................143
Newton-Raphson Method.............................................................................147
Development issues..........................................................................164
References............................................................................................................166
References............................................................................................................205
Algorithm...............................................................................................................208
Pseudocode
Flowchart
Program................................................................................................................216
Review Problems..........................................................................................218
References
Definition of Functions
Recursive function......................................................................................................255
Development problems..........................................................................264
NumPy...................................................................................................................269
Curve adjustment.........................................................................................................272
Coefficients of a polynomial................................................................................275
Arrays........................................................................................................................283
Matrices....................................................................................................................286
SciPy
Interpolation
Linear regression.......................................................................................................298
SymPy
Matplotlib..............................................................................................................311
Pandas
Review Problems..........................................................................................322
Development problems..........................................................................325
References............................................................................................................327
Syntax errors........................................................................................................330
Review problems...........................................................................................345
Development problems
References............................................................................................................347
What is formatting?
Printing titles...................................................................................................361
Importing data from a file and printing a table with the function
tabulate
Review problems...........................................................................................389
References............................................................................................................391
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
References............................................................................................................452
Development problems
References............................................................................................................503
Overview of data.......................................................................................509
First case: History with reference data (setpoint and variation defined)
519
Control rules.................................................................538
Project development..............................................................................540
Study proposals
Finishing Chapter 16...................................................................................552
References............................................................................................................553
Appendices
Index.......................................................................................................568
1
Introduction to Python for Chemical Engineering
Quick Box
Access the link above and,
when the page
open, select the
system version
operational of your
computer.
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
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.
Quick Box
After installation, look for the
spyder icon and click on it
Figure 1.3: Spyder access icon. to open the program.
Quick Box
1–Write your
codes here;
2 2–Explore as
active variables;
3–Here are
1
printed the
results.
3
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).
"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
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.
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.
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( ).
Quick Box
In addition to text, the variables
• 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
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.
Quick Box
Python does not complete
words. In case you forget
to write something
letter, an error will occur.
Quick Box
This is a temporary file.
You don't need to use it.
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
Quick Box
Can you create a
new file, which will already come
of creation.
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.
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
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.
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
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.
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.
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
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.
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
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
Quick Box
Usestr( ) for
transform
Figure 1.27: Converting number to text. number in text.
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.
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.
Quick Box
No console, use os
mathematical operators
for the realization of
simplified calculations.
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.
Quick Cash
To apply an exponent,
utilize '**'. In the case of
scientific notation, Python
accepts 'e' or 'E'.
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!
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.
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
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.
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.
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
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
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:
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
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
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 "
= (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
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.
− ±√ (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 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.
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 .