Python - Math
OverviewQuestions:Objectives:
How do I do math in Python?
Requirements:
Understand the fundamentals of object assignment and math in python and can write simple statements and execute calcualtions in order to be able to summarize the results of calculations and classify valid and invalid statements.
Translate some known math functions (e.g. euclidean distance, root algorithm) into python to transfer concepts from mathematics lessons directly into Python.
Time estimation: 30 minutesLevel: Introductory IntroductorySupporting Materials:Last modification: Sep 28, 2022
Best viewed in a Jupyter NotebookThis tutorial is best viewed in a Jupyter notebook! You can load this notebook one of the following ways
Launching the notebook in Jupyter in Galaxy
- Instructions to Launch JupyterLab
- Open a Terminal in JupyterLab with File -> New -> Terminal
- Run
wget https://training.galaxyproject.org/training-material/topics/data-science/tutorials/python-math/data-science-python-math.ipynb
- Select the notebook that appears in the list of files on the left.
Downloading the notebook
- Right click one of these links: Jupyter Notebook (With Solutions), Jupyter Notebook (Without Solutions)
- Save Link As..
Here we’ll learn some of the fundamentals of python and how to do basic maths in Python.
AgendaIn this tutorial, we will cover:
Python Fundamentals
Variables
Any Python interpreter can be used as a calculator. We can do simple sums
3 + 5 - 4
Multiplication
5 * 4
Division
5 / 4
Just like you’ve probably learned in maths courses, we can assign values to variables
x = 10
y = 2.5
z = 3
From now on, whenever we use x
or y
or z
, Python will substitute the value we assigned to it.
You’ll notice when we assign things to a variable, nothing is printed out. If we’ve assigned a value to a variable we can print it by doing:
print(x)
print(y, z)
You can print out multiple variables if you separate them with a comma ,
.
In Python, variable names:
- can include letters, digits, and underscores
- cannot start with a digit
- are case sensitive
This means that, for example:
x
is a valid nameweight0
is a valid variable name, whereas0weight
is notweight
andWeight
are different variables
x * (y + z)
What do you think the following will result in? The best way to find out is trying things for yourself. If it’s wrong, can you correct it?
xy
Time to check what we’ve learned!
Question: Exercise 0: Simple EquationsGiven the equation:
\[y = x * 921 + 534\]What is the value of
y
whenx = 452
You can test out solutions in the box below this question.
x = 452 y = x * 921 + 534 # Remember to print it out! print(y)
416826
# Test solutions here!
# By the way, lines starting with a # are comment lines!
# You can use that to take notes, and not affect how your code runes
# People use it for documentation: explaining what the function does,
# what a variable means, why they chose this or that algorithm.
Libraries
A library is a collection of files (called modules) that contains functions for use by other programs. It may also contain data values (e.g., numerical constants) and other things. A library’s contents are supposed to be related, but there’s no way to enforce that. The Python standard library is an extensive suite of modules that comes with Python itself. Many additional libraries are available from PyPI (the Python Package Index).
Libraries and modules
A library is a collection of modules, but the terms are often used interchangeably, especially since many libraries only consist of a single module, so don’t worry if you mix them.
A program must import a library module before using it.
You can use import
to load a library module into a program’s memory, then refer to things from the module as module_name.thing_name
. Python uses .
to mean “part of”. For example, using datetime
, one of the modules in the standard library:
import datetime
# it is currently
datetime.datetime.now()
First, you can use
help
to learn about the contents of a library module. it works just like help for a function.help(datetime)
You can import specific items from a library module to shorten programs. You can use
from ... import ...
to load only specific items from a library module. Then refer to them directly without library name as prefix.from datetime import datetime datetime.now()
You can create an alias for a library module when importing it to shorten programs. Use
import ... as ...
to give a library a short alias while importing it. Then refer to items in the library using that shortened name.from datetime import datetime as dt dt.now()
Math Module
Let’s import the math module:
import math
This imports the math module. If you ever don’t know what a function does, you can use the help()
command:
help(math)
And you’ll see a list of the functions and properties available. Let’s try out one of those functions now:
math.sqrt(9)
When we import a module like
import math
, we need to use that as a prefix. Imagine we had two different modules,math
andother_math
, and both have asqrt
function. How would Python know whichsqrt
function we wanted? So we usemath.sqrt
to be explicit about which function we need.
You might also have done powers (e.g. 2 cubed, or \(2^3\)) in the past, too:
math.pow(2, 3)
Above we computed 2 cubed, but how did we know what to write? We might have seen math.pow
in the help(math)
page above, but how did we know 2, 3
? The same way of course:
help(math.pow)
That would tell us that if we want 2 cubed, we need to write 2
and 3
. So let’s do some exercises now and practice some of our maths skills.
Question: Exercise 1: BasicsPlease convert this function from an equation, into python code:
\[x = 2^8\]x = math.pow(2, 8) print(x)
# Test solutions here!
x =
print(x)
Question: Exercise 2: Averaging two valuesSee if you can find the average of these two values, using the math operations
- 23484
- 12345
You can find the average by summing, and dividing by 2:
(23484 + 12345) / 2
# Test solutions here!
Question: Exercise 3: Round-tripPlease convert this function from an equation, into python code. Remember, you can assign values to variables, if you want to split this into multiple steps.
\[x = \sqrt{9^2}\]y = math.pow(9, 2) x = math.sqrt(y)
Or
x = math.sqrt(math.pow(9, 2))
# Test solutions here!
Question: Exercise 4: Pythagorean TheoremThe formula for a 90° triangle can be expressed as:
\[a^2 + b^2 = c^2\]Or, expressed in terms of c, \(c = \sqrt{a^2 + b^2}\)
Please convert this to python and find
c
whena = 65 b = 72
c = 97
c = math.sqrt(math.pow(a, 2) + math.pow(b, 2))
# Test solutions here!
Question: Exercise 5: Quadratic RootsWay back in algebra class, you might have been given a quadratic equation, something like:
\(y = 2*x^2 + x - 1\) and were told to find the roots of this function, using a complicated equation. So challenge time: reproduce this equation in Python:
Given the following variables:
a = 2 b = 1 c = -1
Convert the following formulas to Python, and find the answers
\(\dfrac{-b + \sqrt{b^2 - 4ac}}{2a}\) and \(\dfrac{-b - \sqrt{b^2 - 4ac}}{2a}\)
Since we’re checking your ability to write Python, not do math, it should give
-1
and0.5
to let you check your work. If you got those values, you got it right!Make sure you save each root as it’s own variable, and then print them out.
root1 = (-b + math.sqrt(math.pow(b, 2) - 4 * a * c))/(2 * a) root2 = (-b - math.sqrt(math.pow(b, 2) - 4 * a * c))/(2 * a) print(root1) print(root2)
# Test solutions here!
root1 =
root2 =
print(root1)
print(root2)
Key points
Converting mathematics equation to python is pretty easy!
In real life you’ll occasionally need to do this, either converting from a formula you read in a paper, or a description of an algorithm, into code that you’ll re-use.
Did you forget how a particular module or function works? Try
help()
Frequently Asked Questions
Have questions about this tutorial? Check out the FAQ page for the Foundations of Data Science topic to see if your question is listed there. If not, please ask your question on the GTN Gitter Channel or the Galaxy Help ForumFeedback
Did you use this material as an instructor? Feel free to give us feedback on how it went.
Did you use this material as a learner or student? Click the form below to leave feedback.
Citing this Tutorial
- Helena Rasche, Donny Vrins, Bazante Sanders, 2022 Python - Math (Galaxy Training Materials). https://training.galaxyproject.org/training-material/topics/data-science/tutorials/python-math/tutorial.html Online; accessed TODAY
- Batut et al., 2018 Community-Driven Data Analysis Training for Biology Cell Systems 10.1016/j.cels.2018.05.012
Congratulations on successfully completing this tutorial!@misc{data-science-python-math, author = "Helena Rasche and Donny Vrins and Bazante Sanders", title = "Python - Math (Galaxy Training Materials)", year = "2022", month = "09", day = "28" url = "\url{https://training.galaxyproject.org/training-material/topics/data-science/tutorials/python-math/tutorial.html}", note = "[Online; accessed TODAY]" } @article{Batut_2018, doi = {10.1016/j.cels.2018.05.012}, url = {https://doi.org/10.1016%2Fj.cels.2018.05.012}, year = 2018, month = {jun}, publisher = {Elsevier {BV}}, volume = {6}, number = {6}, pages = {752--758.e1}, author = {B{\'{e}}r{\'{e}}nice Batut and Saskia Hiltemann and Andrea Bagnacani and Dannon Baker and Vivek Bhardwaj and Clemens Blank and Anthony Bretaudeau and Loraine Brillet-Gu{\'{e}}guen and Martin {\v{C}}ech and John Chilton and Dave Clements and Olivia Doppelt-Azeroual and Anika Erxleben and Mallory Ann Freeberg and Simon Gladman and Youri Hoogstrate and Hans-Rudolf Hotz and Torsten Houwaart and Pratik Jagtap and Delphine Larivi{\`{e}}re and Gildas Le Corguill{\'{e}} and Thomas Manke and Fabien Mareuil and Fidel Ram{\'{\i}}rez and Devon Ryan and Florian Christoph Sigloch and Nicola Soranzo and Joachim Wolff and Pavankumar Videm and Markus Wolfien and Aisanjiang Wubuli and Dilmurat Yusuf and James Taylor and Rolf Backofen and Anton Nekrutenko and Björn Grüning}, title = {Community-Driven Data Analysis Training for Biology}, journal = {Cell Systems} }
Do you want to extend your knowledge? Follow one of our recommended follow-up trainings: