Lesson 1 of 3
Package a calculation into a reusable, named function: define it with def, call it, return a result, and document it.
About 25 minutes
def and call itreturnYou have already used many functions: print(), len(), round(), max(). Each is a named piece of code that does one job. You call it, give it some information, and it does the work without you needing to know how it is written inside.
You can write your own functions too. Imagine a program that converts temperatures to kelvin in ten different places. Without a function, the formula is copied ten times; if you find a mistake, you must fix it ten times and hope you didn't miss one. With a function, the formula lives in one place, has a clear name, and every part of the program uses the same tested code.
celsius_to_kelvin(25) says what it does; 25 + 273.15 only says how.A function definition starts with the keyword def, then the function's name, brackets, and a colon. The indented block below is the function's body: the code that runs when the function is used. Defining a function doesn't run it; it just teaches Python a new command. You run the body by calling the function: its name followed by brackets.
def print_header(): print("=" * 30) print("SPASCLE materials report") print("=" * 30)print_header()print("Sample: Cu-01")Define before you call
Most functions need information to work with. Names listed inside the brackets of the definition are parameters. When you call the function, the values you pass in are called arguments, and each parameter takes the value of its argument for that call.
def describe(element, density): print(f"{element} has a density of {density} g/cm³")describe("Copper", 8.96)describe("Aluminium", 2.70)The functions above print their result, which is fine for displaying something, but the result can't be used in further calculations. Most useful functions instead return a value with the return statement. The function call then stands for that value, so you can store it in a variable, print it, or use it in an expression.
A function that converts a temperature from °C to K, used to report several transition temperatures.
def celsius_to_kelvin(temperature_c): return temperature_c + 273.15melting_k = celsius_to_kelvin(1085)print(f"Copper melts at {melting_k} K")print(f"Room temperature is {celsius_to_kelvin(20)} K")print(f"Difference: {melting_k - celsius_to_kelvin(20)} K")return also ends the function immediately: any lines after it in the body don't run. You will look at return in much more detail in the Return Values lesson.
A function can call other functions, including ones you wrote. This lets you build bigger calculations out of small, well-tested pieces.
def celsius_to_kelvin(temperature_c): return temperature_c + 273.15def thermal_energy(temperature_c): boltzmann = 1.380649e-23 # J/K return boltzmann * celsius_to_kelvin(temperature_c)print(f"{thermal_energy(25):.3e} J")A docstring is a string written as the first line of a function's body, normally in triple quotes. It explains what the function does, what its parameters mean (including units), and what it returns. Python stores it with the function, and help() displays it. Good docstrings are especially valuable in scientific code, where units and assumptions matter.
def density(mass_g, volume_cm3): """Return the density in g/cm³ of a sample with the given mass (g) and volume (cm³).""" return mass_g / volume_cm3print(density(26.98, 10.0))print(density.__doc__)convert_units, calculate_density, density.snake_case style as variable names.Choose an answer and press Check answer. You can retry as often as you like.