Using Python with seismic data
Lesson 3: Sequence and Selection

This script demonstrates sequence and selection.

Sequence
Scripts flow from top to bottom and left to right.

Selection
Branching occurs at if statements. When a selection is made, using if, an indented block of code is run.

== tests for equality,
: starts a block,
indent blocks of code with a tab, or with three spaces,
triple quotes allow multi-line strings.

A picture containing text

Description automatically generated

Common pitfalls in Python
1) == is used to test for equality, but = is used for assignment. x == 5 is a test. x = 5 is an assignment.
2) Don't forget : to start a code block
3) Indent blocks using either tab or three spaces, but be consistent, use one or the other.

At the end of the sequence of if ... elif ... elif ... statements, an else: statement will run a block of code only if none of the previous tests have evaluated True.


Triple-quoted strings
Triple-quoted strings allow you to write text extending across more than one line. You can use '''Long text''' or """More long text""", as long as you don't mix single and double quotes. For fun, you can add ASCII art into your code e.g. enter text into https://ascii-art-generator.org

Selection (if... elif... else...)
Selection is performed using if, which then creates a branch in the program if a test condition is met. The available operators are == equals, != not equals, > greater than, < less than, >= greater than or equal to, <= less than or equal to.
elif stands for "else if" and it only runs if the previous if or elif tests have not evaluated True.

Links
This lesson on Twitter: https://twitter.com/wmvanstone/status/1251781218368094209

The code from GitHub: https://github.com/wmvanstone/LearnPythonForObspy

The obspy tutorial: https://docs.obspy.org/tutorial/

Lesson 2: python02.html

Lesson 4: python04.html


Links: Links


Home: Index