First steps in python

Workshop 1

16.09.2023

Motivation


Today’s learning outcomes


At the end of this lesson you

  • will have implemented your first python program..
  • ..and ran it from the Terminal.
  • will have learned several basic programming terms and concepts that we will review at the end.
  • will be able to deepen your initial understanding through directed reading exercises.

Our first program in python

Our first program in python


What can I do with 1kWh of electricity?

\[ minutes = wattage \cdot \frac{60}{1000} \]

file `calculate_usage_time.py`
# Program for calculating the usage time (in minutes) 
# of an appliance with a given wattage, 
# if 1kWh of electricity is available

# Define variables
wattage = 1000  # ~ of appliance in (W)
cfac1 = 1000    # conversion factor for kilo
cfac2 = 60      # conversion factor for minutes

# Perform calculation
minutes = wattage * cfac2 / cfac1

# Output
print(minutes)

Dissecting our first program in python


# Program for calculating the usage time (in minutes) 
# of an appliance with a given wattage, 
# if 1kWh of electricity is available

# Define variables
wattage = 1000  # ~ of appliance in (W)
cfac1 = 1000    # conversion factor for kilo
cfac2 = 60      # conversion factor for minutes

# Perform calculation
minutes = wattage * cfac2 / cfac1

# Output
print(minutes)

Dissecting our first program in python


Comments

  • hashtag # –> the rest of the line will be ignored by python
  • opportunity for you to structure your code and explain its meaning
  • readability is key!
# Program for calculating the usage time (in minutes) 
# of an appliance with a given wattage, 
# if 1kWh of electricity is available

# Define variables
wattage = 1000  # ~ of appliance in (W)
cfac1 = 1000    # conversion factor for kilo
cfac2 = 60      # conversion factor for minutes

# Perform calculation
minutes = wattage * cfac2 / cfac1

# Output
print(minutes)

Dissecting our first program in python


Assignments

  • create an object in computer memory..
  • ..of specific class (think: data type)..
  • ..and with a name (reference)
# Program for calculating the usage time (in minutes) 
# of an appliance with a given wattage, 
# if 1kWh of electricity is available

# Define variables
wattage = 1000  # ~ of appliance in (W)
cfac1 = 1000    # conversion factor for kilo
cfac2 = 60      # conversion factor for minutes

# Perform calculation
minutes = wattage * cfac2 / cfac1

# Output
print(minutes)

Dissecting our first program in python


Assignments

  • data type
    • integer (int)
    • floating point number (float)
cfac1 = 1000
pi = 3.14

Dissecting our first program in python


Maths

# Program for calculating the usage time (in minutes) 
# of an appliance with a given wattage, 
# if 1kWh of electricity is available

# Define variables
wattage = 1000  # ~ of appliance in (W)
cfac1 = 1000    # conversion factor for kilo
cfac2 = 60      # conversion factor for minutes

# Perform calculation
minutes = wattage * cfac2 / cfac1

# Output
print(minutes)

Dissecting our first program in python


Maths

The equal sign has different meaning in python than in a math equation!

\[ x = 2 - x\\ 2x = 2\\ x = 1 \]

x = 2
x = 2 - x

What value is referenced in x?

0

Dissecting our first program in python


# Program for calculating the usage time (in minutes) 
# of an appliance with a given wattage, 
# if 1kWh of electricity is available

# Define variables
wattage = 1000  # ~ of appliance in (W)
cfac1 = 1000    # conversion factor for kilo
cfac2 = 60      # conversion factor for minutes

# Perform calculation
minutes = wattage * cfac2 / cfac1

# Output
print(minutes)

Dissecting our first program in python


Function calls

  • functions are ready-made pieces of code that can be called
  • functions can take none or multiple arguments
# Program for calculating the usage time (in minutes) 
# of an appliance with a given wattage, 
# if 1kWh of electricity is available

# Define variables
wattage = 1000  # ~ of appliance in (W)
cfac1 = 1000    # conversion factor for kilo
cfac2 = 60      # conversion factor for minutes

# Perform calculation
minutes = wattage * cfac2 / cfac1

# Output
print(minutes)

Dissecting our first program in python


# Program for calculating the usage time (in minutes) 
# of an appliance with a given wattage, 
# if 1kWh of electricity is available

# Define variables
wattage = 1000  # ~ of appliance in (W)
cfac1 = 1000    # conversion factor for kilo
cfac2 = 60      # conversion factor for minutes

# Perform calculation
minutes = wattage * cfac2 / cfac1

# Output
print(minutes)

Your first program in python


Exercise

  1. open a text editor (e.g., Notepad)
  2. conda activate scipro2023
  3. create a file convert_years2hours.py in the directory $SCIPRO/01_workshop/
  4. write a program to convert 2.5 years into hours
  5. execute your program in the terminal by running: $ python convert_years2hours.py

Be aware of bugs!

Code
# Program to convert years into hours

# Define variables
years = 2.5
year2days = 365
day2hours = 24

# Perform conversion
hours = years * year2days * day2hours

# Output
print(hours)
21900.0

Your first program in python


Exercise

Be aware of bugs! What errors do we encounter?

  • remove the # sign in front of an inline comment
  • remove the = sign in an assignment statement
  • try pint(hours) instead of print(hours)
  • try print(Hours) instead of print(hours)

Your first program in python


Exercise

Be aware of bugs! What errors do we encounter?

  • NameError
  • SyntaxError

Our second program

Our 2nd program


The solar elevation angle \(h = arcsin(cos \delta \cdot cos \tau \cdot cos \varphi + sin \delta \cdot sin \varphi)\)

Our 2nd program


The solar elevation angle \(h = arcsin(cos \delta \cdot cos \tau \cdot cos \varphi + sin \delta \cdot sin \varphi)\)

What are the high-level steps to be included in our program? What’s our recipe?

  • Input/Definition
  • Computation
  • Output

Our 2nd program


# Program for computing the solar elevation angle
# Version 1: 12 o'clock true noon

from math import cos, sin, asin

# Define variables
delta = 11.4  # declination sun 20.4.2023
tau = 0       # hour angle noon
phi = 47      # latitude

# Compute solar elevation angle
h = asin(cos(delta)*cos(tau)*cos(phi) + sin(delta)*sin(phi))
print(h)

Stop! Semantic Error

Our 2nd program


Exercise. Getting quick help and information.

  1. open your terminal
  2. conda activate scipro2023
  3. start ipython
  4. from math import cos, sin
  5. cos?

Our 2nd program


# Program for computing the solar elevation angle
# Version 1: 12 o'clock true noon

from math import cos, sin, asin, radians, degrees

# Define variables
delta = 2.86  # declination sun Sept 16, 2023 
tau = 0       # hour angle noon
phi = 47      # latitude

# Convert degree to radians
delta_rad = radians(delta)
tau_rad = radians(tau)
phi_rad = radians(phi)

# Compute solar elevation angle
h_rad = asin(cos(delta_rad)*cos(tau_rad)*cos(phi_rad) 
             + sin(delta_rad)*sin(phi_rad))
h = degrees(h_rad)
print(h)

Our 2nd program: Version 2


# Program for computing the solar elevation angle
# Version 2: the entire day

import numpy as np

# Define variables
delta = 2.86                 # declination of the sun at Sept 16, 2023 
tau = np.arange(0, 360, 15)  # vector of hour angle from 12--11 o'clock true local time
phi = 47                     # latitude

# Convert degree to radians
delta_rad = np.deg2rad(delta)
tau_rad = np.deg2rad(tau)
phi_rad = np.deg2rad(phi)

# Compute solar elevation angle
h_rad = np.arcsin(np.cos(delta_rad)*np.cos(tau_rad)*np.cos(phi_rad) 
                  + np.sin(delta_rad)*np.sin(phi_rad))
h = np.rad2deg(h_rad)
print(h)

Our 2nd program: Version 2


Exercise

  1. start ipython on your terminal
  2. import numpy as np
  3. open the documentation for the function np.arange
  4. try to understand what the function does and what it will return for np.arange(0, 360, 15)

Our 2nd program: Version 2


Exercise

  1. start ipython on your terminal
  2. import numpy as np
  3. open the documentation for the function np.arange
  4. try to understand what the function does and what it will return for np.arange(0, 360, 15)
  5. exit the documentation with the key q
  6. tau = np.arange(0, 360, 15)
  7. tau
  8. type(tau)

Our 2nd program: Version 2


Vectorization

  • vector (programming): 1-dimensional array
  • vector (maths): quantity with the two properties magnitude and direction
  • vectorization: operate on many values instead of on single values
tau = np.arange(0, 360, 15)
cos_tau = np.cos(tau)

Our 2nd program: Version 2


import statement

  • from package import object1 [, object2, ...]
  • import package
  • import package as alias
from math import cos, pi
cos(pi)


import numpy
tau = numpy.arange(0, 2*np.pi, 0.5*np.pi)
numpy.cos(tau)

Our 2nd program: Version 2


import statement

Importing too many select functions can be error-prone!

from numpy import pi, cos, arange
from math import cos
cos(arange(0, pi, 0.5*pi))

Our 2nd program: Version 2


# Program for computing the solar elevation angle
# Version 2: the entire day

import numpy as np

# Define variables
delta = 2.86                 # declination of the sun at Sept 16, 2023 
tau = np.arange(0, 360, 15)  # vector of hour angle from 12--11 o'clock true local time
phi = 47                     # latitude

# Convert degree to radians
delta_rad = np.deg2rad(delta)
tau_rad = np.deg2rad(tau)
phi_rad = np.deg2rad(phi)

# Compute solar elevation angle
h_rad = np.arcsin(np.cos(delta_rad)*np.cos(tau_rad)*np.cos(phi_rad) 
                  + np.sin(delta_rad)*np.sin(phi_rad))
h = np.rad2deg(h_rad)
print(h)

Our 2nd program: Version 3


# Program for computing the solar elevation angle
# Version 3: for the entire day, incl. figure

import numpy as np
import matplotlib.pyplot as plt

# Define variables
delta = 2.86                       # declination of the sun at Sept 16, 2023 
tau = np.arange(0, 360, 15) - 180  # vector of hour angle from 0--23 o'clock true local time
phi = 47                           # latitude

# Convert degree to radians
delta_rad = np.deg2rad(delta)
tau_rad = np.deg2rad(tau)
phi_rad = np.deg2rad(phi)

# Compute solar elevation angle
h_rad = np.arcsin(np.cos(delta_rad)*np.cos(tau_rad)*np.cos(phi_rad) 
                  + np.sin(delta_rad)*np.sin(phi_rad))
h = np.rad2deg(h_rad)

## plot results
plt.figure()
plt.plot(tau, h)
plt.grid()
plt.xlabel("hour angle (degrees)")
plt.ylabel("solar elevation angle (degrees)")
plt.savefig("tau_h.png")

Our 2nd program: Version 3


# Program for computing the solar elevation angle
# Version 3: for the entire day, incl. figure

import numpy as np
import matplotlib.pyplot as plt

# Define variables
delta = 2.86                       # declination of the sun at Sept 16, 2023 
tau = np.arange(0, 360, 15) - 180  # vector of hour angle from 0--23 o'clock true local time
phi = 47                           # latitude

# Convert degree to radians
delta_rad = np.deg2rad(delta)
tau_rad = np.deg2rad(tau)
phi_rad = np.deg2rad(phi)

# Compute solar elevation angle
h_rad = np.arcsin(np.cos(delta_rad)*np.cos(tau_rad)*np.cos(phi_rad) 
                  + np.sin(delta_rad)*np.sin(phi_rad))
h = np.rad2deg(h_rad)

## plot results
plt.figure()
plt.plot(tau, h)
plt.grid()
plt.xlabel("hour angle (degrees)")
plt.ylabel("solar elevation angle (degrees)")
plt.savefig("tau_h.png")

Recap & learning checklist

Recap & learning checklist


  • I have written my first python program using a text editor and creating a file with the ending .py.
  • I know that Python executes the commands in a python script line-by-line starting from the top.
  • I have run my first python program from the terminal using the python command.
  • I am aware that structuring and annotating my code in a clean way will help my future self and potential co-programmers understand the code better.
  • I understand that assignments create objects that are being stored in computer memory. The left-hand side of the assignment represents the name (reference) of the object, and the right-hand side represents the object.
  • I know the following data types: int, float, str, numpy.ndarray.
  • I can use math operators in python.
  • I can distinguish between three different types of errors.
  • I know the difference between packages and functions.
  • I am able to import entire packages or select functions.
  • I can access the documentation of functions and packages from the ipython command line.
  • I have created my first figure with a computer program that I coded.