Python Functions

The following tutorial is an introduction to built-in Python functions such as average, standard deviation, maximum, minimum, and conditional counting.

Python Source Code

import random
y = [random.random()*100.0 for i in range(10)]
print("Print y")
print(y)

print("Sorted List")
for i in range(len(y)):
    print("%.2f" % y[i])

def avg(x):
    return sum(x) / len(x)

print("Avg: " + str(avg(y)))
print("Max: " + str(max(y)))
print("Min: " + str(min(y)))
z = sum(1 if i<50.0 else 0 for i in y)
print("Number Below 50: " + str(z))

# another method with NumPy
import numpy as np
print(np.mean(y))
print(np.average(y))
print(np.std(y))
print(np.median(y))

Data statistics can also be completed with a spreadsheet program like Microsoft Excel and MATLAB where the data sets are arrays or matrices instead of tables in a spreadsheet. Click on the appropriate link for additional information and source code.

Non-Ideal Gas Function Example

Source Code

def P_RK_IG(V, T, do_ideal_gas=False):
   R = 0.0821  # L-atm/K
   Pc = 37.2   # atm
   Tc = 132.5  # K

   a = 0.427 * pow(R,2) * pow(Tc,2.5) / Pc
   b = 0.0866 * R * Tc / Pc

   # Compute in atm
   P_ig = R * T / V
   P_rk = R * T / (V-b) - a/(V*(V+b)*pow(T,0.5))

   # Convert to Pascals
   if do_ideal_gas:
      return P_ig * 101325
   else:
      return P_rk * 101325

for T in range(490,511,10):
   V = 4.0
   while V < 8:
      print("----- Temperature: " + str(T) + " K")
      print("P_ig: " + str(P_RK_IG(V,T,True)) + " Pa")
      print("P_rk: " + str(P_RK_IG(V,T)) + " Pa")
      V = V + 2.0

Generative AI Learning

Write-it-yourself class: build every function with your own hands; the AI quizzes and probes. Use these prompts after completing the examples.

"Quiz me with 4 questions, one at a time, on Python functions: what def, arguments, and return each do, the difference between printing a value inside a function and returning it, what happens to a variable defined inside a function after it returns (scope), and why a function that computes the Redlich-Kwong pressure is more useful than the same lines pasted three times. Ask me to predict the output of one short snippet where a function prints but returns None. Grade my answers and list my misconceptions."
"I wrote this function myself: {paste your function}. Do not rewrite it. Interrogate me about it, one question at a time: what are the units of each argument, what happens if I call it with a list instead of a number, what does it return for a physically impossible input, and how would I test it against one hand calculation? Then grade my testing plan."

Discussion Questions

  1. A function prints its answer but returns nothing. The next calculation needs that answer. What breaks, and what is the one-line fix?
  2. Two calls to your gas-pressure function with the same arguments must give the same answer. What design choices (global variables, input() inside the function) would silently break that property?
  3. You need mean, max, and min of 10 random numbers. When is a custom function worth writing when numpy already provides these - and what does writing one anyway teach you about trusting the library version?

Course Information

Excel and VBA

Python

MATLAB

MathCAD

Related Courses

Admin