= 2.5
x = 3.0
y + y x
5.5
TThere are many online resource available that provide good introduction material to programming in Python. Here is a very good website to start with: www.learnpython.org This is an interactive site where you can directly type Python code into your web browser to try out code snippets without installing anything.
You should also check out some of the documentation of Python’s main scientific libraries such as:
- NumPy (numpy.org)
- Pandas (pandas.pydata.org)
- Matplotlib (matplotlib.org)
After installation, open Spyder and try some of the following in the command line:
= 2.5
x = 3.0
y + y x
5.5
x = 2.5
y = 3.0
x + y
[1] 5.5
= 2.5
x = 3.0
y + y x
Or try it in a script file, save it and run it.
Then try the following mathematical operators.
Operation | Expression |
---|---|
Subtraction | x - y |
Division | x / y |
Multiplication | x * y |
Power | x ** y |
Square root | m.sqrt(x) |
Modulus | x % y |
Floor division | x // y |
Note that the power function is not ^
but **
. Also in Python we need to import the math-module in order to use certain math functions like sqrt()
etc. When importing a module, we actually import a library of functions that all start with the module name. By typing import math
at the beginning of your script you can then call all the functions of the math-module (or library) by typing math.functionName()
. So if you want to take the square root of number 9, you would then simply call math.sqrt(9)
. You can also abbreviate the name of the module by typing import math as m
in which case you can now take the square root with m.sqrt(9)
as in the following script.
= 7
x = 2
y
print(" --- OUTPUT: --- ")
# addition
print("x + y = {}".format(x + y))
# subtraction
print("x - y = {}".format(x - y))
# multiplication
print("x * y = {}".format(x * y))
# division
print("x / y = {}".format(x / y))
# exponentiation
print("x ** y = {}".format(x ** y))
# square root
import math as m
print("m.sqrt(x) = {}".format(m.sqrt(x)))
# modulus
print("x % y = {}".format(x % y))
# floor division
print("x // y = {}".format(x // y))
--- OUTPUT: ---
x + y = 9
x - y = 5
x * y = 14
x / y = 3.5
x ** y = 49
m.sqrt(x) = 2.6457513110645907
x % y = 1
x // y = 3
Operation | Expression |
---|---|
Subtraction | x - y |
Division | x / y |
Multiplication | x * y |
Power | x ^ y |
Square root | sqrt(x) |
Modulus | x %% y |
Floor division | x %//% y |
x = 7
y = 2
print(paste("x + y = ", x + y))
print(paste("x * y = ", x * y))
print(paste("x / y = ", x / y))
print(paste("x^y = ", x ^ y))
print(paste("sqrt(x) = ", sqrt(x)))
print(paste("x%%y = ", x %% y))
print(paste("x%/%y = ", x %/% y))
[1] "x + y = 9"
[1] "x * y = 14"
[1] "x / y = 3.5"
[1] "x^y = 49"
[1] "sqrt(x) = 2.64575131106459"
[1] "x%%y = 1"
[1] "x%/%y = 3"
If you want to see a list of all the functions in the math module you can type: dir(math)
or dir(m)
and you will get a list of all methods/functions embedded in the module.
If you want to format your print output and combine text with numbers you need to use the .format
method of the print function. You will learn more about objects and methods in a later chapter. Just hang in there fore now.
If you want to format the numbers (e.g., round etc.) that print
will output you need to type the double brackets {}
in your text string as a placeholder for where the number will be inserted.
import math as m
= 2.455555
x = 3.12344
y
print(" --- OUTPUT: --- ")
# Unformatted
print("x+y", x+y)
# Still unformatted but using the .format() method
print("Unformatted: x + y = {}".format(x+y))
# Formatted, finally ...
print("Formatted: x + y = {:5.2f}".format(x+y))
--- OUTPUT: ---
x+y 5.578995
Unformatted: x + y = 5.578995
Formatted: x + y = 5.58
x <- 2.455555
y <- 3.12344
cat(" --- OUTPUT: --- \n")
# Unformatted
cat("x+y", x+y, "\n")
# Still unformatted but using the sprintf() method
cat(sprintf("Unformatted: x + y = %f \n", x+y))
# Formatted, finally ...
cat(sprintf("Formatted: x + y = %5.2f \n", x+y))
--- OUTPUT: ---
x+y 5.578995
Unformatted: x + y = 5.578995
Formatted: x + y = 5.58
The format instruction :5.2f means that the output of the number is formatted as a five digit number with two fixed decimal places. If you want to see more details about how you can format numbered output have a look at this link: https://www.python-course.eu/python3_formatted_output.php
Here are some more examples:
print("x * y = {:5.2f}".format(x*y))
print("x / y = {:5.2f}".format(x/y))
print("x ** y = {:5.2f}".format(x**y))
print("sqrt(x)= {:5.2f}".format(m.sqrt(x)))
x * y = 7.67
x / y = 0.79
x ** y = 16.54
sqrt(x)= 1.57
cat(paste0("x * y = ", format(x*y, digits = 5, nsmall = 2), "\n"))
cat(paste0("x / y = ", format(x/y, digits = 5, nsmall = 2), "\n"))
cat(paste0("x ** y = ", format(x^y, digits = 5, nsmall = 2), "\n"))
cat(paste0("sqrt(x)= ", format(sqrt(x), digits = 5, nsmall = 2), "\n"))
x * y = 7.6698
x / y = 0.78617
x ** y = 16.543
sqrt(x)= 1.567
You can write more complex output with more than one number embedded in a line of text as follows:
print(" --- OUTPUT: --- ")
print("""We want to use variable x = {0:4.2f} \n and divide by
variable y = {1:4.2f},\n so that we end up with expression
x/y = {2:4.2f}""".format(x, y, x/y))
--- OUTPUT: ---
We want to use variable x = 2.46
and divide by
variable y = 3.12,
so that we end up with expression
x/y = 0.79
The symbol \n
that you see above is not printed but indicates a line break.
Before we go on, let’s save all our commands in a so called Script file. These are basically text files that contain all commands in one big “laundry list” that we can then execute all at once. In order to open such a script file in Spyder simply click on File
\(\rightarrow\) New
. Copy/paste the above commands into this script file and save it under a name of your choosing. Note that the file has the extension .py
which indicates that it is a Python script file. You can then edit this file at will and add commands etc.
If you want to run or execute the script file simply click the Source
button on top of your editor window. You can also execute the script file line by line. Simply mark the line, right click, and choose to execute selection or click on the Run
icon on top of your editor window. This is the green button with the “running man symbol” on top of your editor window. If you’d like to execute just one line, mark the line and click on the “running man symbol” to the right of the first green button.
For the remainder of the class I highly recommend that you always use script files. This will help you to quickly run your code and evaluate your results.
A different way to write your codes is via the Jupyter Notebook, formerly known as the IPython Notebook. Read the instructions carefully, it should be pretty self explanatory. All you need to do is you open a terminal window.
- Windows: Go to the start button and type cmd in the search box. This will open a black terminal window.
- Mac: Open a terminal by clicking on the terminal symbol in the dashboard at the bottom.
In this window, after the dollar prompt, you simply type jupyter notebook
. This will start your browser and get you to the Jupyter-Notebook dashboard. You can start a new notebook from there and start typing code into the input boxes. You can immediately evaluate python code pressing: shift-enter
. There are many tutorials about the Jupyter Notebook on the internet.
print()
function allows you to show output in the command line..format()
option allows you to format how numbers are printed.