First steps in python

Workshop 1

20.09.2024

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

What’s the difference between a program and a script?
(Tip: ask in Hollywood!)

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


Function calls

  • Calling a function
    • print(): calls the function
    • print(minutes): calls the function with one argument
  • Void functions vs fruitful functions
    • void functions just perform some tasks, e.g. print()
    • fruitful functions return something, e.g. type()
minutes = 60.0
type(minutes)

type("Hello")

A new data type

  • "Hello": a string (str) composed of characters
  • 'Hello': just the same
  • "I'm quoting, '1001 stars' fell out the sky": quoting within a string

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. go to https://www.online-python.com/
  2. write a program to convert 2.5 years into hours

If you have conda and python installed on your computer already, instead do the following:

  1. open a text editor (e.g., WordPad, TextEdit)
  2. conda activate scipro2024
  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.

Either go to https://www.pythonanywhere.com/try-ipython/

Or

  1. open your terminal
  2. conda activate scipro2024
  3. start ipython

And then

  1. from math import cos, sin
  2. 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. Either go to https://www.pythonanywhere.com/try-ipython/ or 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. Either go to https://www.pythonanywhere.com/try-ipython/ or 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*numpy.pi, 0.5*numpy.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