A short introduction to scientific Python programming

Hans Petter Langtangen [1, 2]
Leif Rune Hellevik [3]

[1] Center for Biomedical Computing, Simula Research Laboratory
[2] Department of Informatics, University of Oslo
[3] Biomechanics Group, Department of Structural Engineering NTNU

Mar 11, 2020


Contents. This note introduces very basic programming elements, such as
  • variables for numbers, lists, and arrays
  • while loops and for loops
  • functifions
  • if tests
  • plotting
through examples involving a mathematical formula. A glimpse of vectorization of code is also given.

Table of contents

Variables, loops, lists, and arrays
      Getting access to Python
      Mathematical example
      A program for evaluating a formula
      Formatted output with text and numbers
      While loops
      Lists
      For loops
      Arrays
      Mathematical functions
      Plotting
Functions and branching
      Functions
      A more general mathematical formula
      If tests
      Array view versus array copying
      Linear systems
Files
      File reading
      File writing
Classes
      A very simple class
      A class for representing a mathematical function
Exercises
      Exercise 1: Program a formula
      Exercise 2: Combine text and numbers in output
      Exercise 3: Program a while loop
      Exercise 4: Create a list with a while loop
      Exercise 5: Program a for loop
      Exercise 6: Write a Python function
      Exercise 7: Return three values from a Python function
      Exercise 8: Plot a function
      Exercise 9: Plot two functions
      Exercise 10: Measure the efficiency of vectorization