temperature_celsius = 25
temperature_kelvin = temperature_celsius + 273.15
print(temperature_kelvin)
298.15
AESB2122 - Signals and Systems with Python
def
: keyword used to define a function. After def
, Python understands that a function is being definedreturn
: keyword used to exit a function and send back a value. Anything after return
is the value that gets sent back. Also, the function is considered finished when it hits a return
statement.Let’s say we want to convert temperatures to Kelvin
How to make this a function?
def
statement and return
statementCreate a function that identifies whether a given input in degree Celsius is a possible surface temperature in the Netherlands and if so, convert to Kelvin. Otherwise return the input value.
Create a new Python file named sine_wave.py
. In it:
Create a new file named script.py
. In it:
In using a function from a different file, what we did right now is import a module!
A module is simply a file containing any Python code (functions, classes, variables).
You can simply import such modules and use them in other Python scripts. This is called modular programming and it helps in organizing code, reusability, and maintaining the codebase.
A module can have other modules imported within it, allowing for a hierarchical organization of code.
So, this is essentially what you do when you, for instance, do import numpy as np
. You are importing the NumPy library which gives access to all the functions and classes defined in that library.
Libraries are essentially collections of modules, usually thought of as a package.
A. Create a Python script sine.py
that:
1. Defines a function `create_sine_wave` that generates a sine wave given a frequency and duration.
2. Plot the output of the function and save it as `sine_wave.png`.
B. Run the script from the terminal and check the output.
C. Create another script script.py
that imports the create_sine_wave
function from sine.py
and uses it to plot 3 sine waves with different frequencies in the same plot.
D. Run script.py
from the terminal and check the output.