2. First Steps in Python¶
There 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)
2.1. Simple Calculations¶
After installation, open Spyder and try some of the following in the command line:
x = 2.5
y = 3.0
x + y
5.5
print("x= ", x)
x= 2.5
print("y= ", y)
y= 3.0
print("x + y = ", x + y)
x + y = 5.5
Then try the following:
Operation |
Expression |
---|---|
Subtraction: |
|
Division: |
|
Multiplication: |
|
Power: |
|
Square root: |
|
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.
import math as m
x = 2.455555
y = 3.12344
print(" --- OUTPUT: --- ")
print(x + y)
print(x * y)
print(x / y)
print(x ** y)
print(m.sqrt(x))
--- OUTPUT: ---
5.578995
7.6697787092
0.7861700560920011
16.542802038492464
1.5670210592075653
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.
2.2. The Print Function¶
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
x = 2.455555
y = 3.12344
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
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
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.
2.3. Script Files¶
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.
2.4. iPython Notebook¶
A different way to write your codes is via 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 ipython-notebook. This
will start your browser and get you to the iPython-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 iPython Notebook on the internet.
2.5. Key Concepts and Summary¶
Note
The
print()
function allows you to show output in the command line.The
.format()
option allows you to format how numbers are printed.A script file is a text file with python commands.
2.6. Self-Check Questions¶
Todo
Generate a list with numbers from 1 to 10
Print the first 5 elements of this list
Replace the last entry of the list with 100 and print the list again
Sort the list from largest to smallest element
Go to www.learnpython.org