🐍🐍 Python part two 🐍🐍¶

✨ Previous Lesson ✨¶

  1. running python code: Jupyter Notebooks, markdown basics
  2. variables: variable names, variable assignment, print(), execution order
  3. data types: integer, float, string, list, len(), string operations/indexing/slicing, type conversion: int(), str(), float()
  4. functions, help and errors: min(), max(), round(), help(), runtime errors (exceptions), syntax errors
  5. lists sequence type, immutable vs mutable, list method append, del

✨ Today's Lesson ✨¶

  1. For loops
  2. Conditionals
  3. Writing functions
  4. Variable scope
  5. Libraries

For Loops¶

For Loops¶

Conditionals¶

mass = 4.2

if mass > 3:
    print(mass, ' is large')

if mass < 2:
    print(mass, ' is small')

if 2 <= mass <= 3:  
    print(mass, ' is just right')

Functions¶

def print_greeting():
    print ("Hello!")

Functions¶

def print_personalised_greeting(name):
    print ("Hello "+name)

Variable Scope¶

pressure = 103.9

def adjust(temperature):
    new_temperature = temperature*1.43/pressure

Python scientific libraries¶

✨ Lesson outline ✨¶

  1. For loops dummy variable, loop syntax, index from 0
  2. Conditionals if, elif, else, ordering
  3. Writing functions function syntax, return statement, parameters and arguments
  4. Variable scope local and global variables
  5. Libraries modules, packages, libraries, import statements, aliases

Bonus end note: Programming good practice

⚠️ Programming good practice ⚠️¶

Document your code with docstrings

 def calc_bulk_density(mass,volume):
     "Return dry bulk density = powder mass / powder volume."
     return mass / volume

What are the other two types of code documentation you can use?

⚠️ Programming good practice ⚠️¶

Focus on readability

  • consistency is key
  • whitespace:
    spam(ham[1], {eggs: 2})
    spam( ham[ 1 ], { eggs: 2} )
  • clear, meaningful variable names (don't just use x, p etc and expect the reader to know what they mean!)

⚠️ Programming good practice ⚠️¶

Think about reproducibility

Reproducibility is more complex and difficult than you might think..

One straight-forward thing you can do is print the version number for each package you import using print(packagename.__version__)

In [ ]: