if name==main
An example of properly written python code. Let’s assume the name of the script is script.py
in this example.
#!/bin/env python3
- On Unix based systems, this is needed to be able to run the script with
./script.py
. ''' docstring '''
- adds a documentation to the script as a whole and individual functions. The documentation can be accessed with
help()
.
The import
statements come next. Then the function definitions with def
.
if __name__==__main__
- the result of this statement is true if script is invoked with
python script.py
. The script can otherwise be invoked with theimport
command from within python.
Other than readability, the advantage with this approach is being able to run functions with script.compute()
, script.report()
, and script.plot()
.
#!/bin/env python3
'''
This is an educational python module.
Reports the values of y=sin(x) and plots if executed as a script.
Silently calculates the values y=sin(x) if imported as a module.
'''
from math import pi
import numpy as np
import matplotlib.pyplot as plt
def compute():
'''returns the values of x and y'''
x=np.linspace(-2*pi,2*pi,50)
y=np.sin(x)*np.exp(-x)
return x,y
def report(x,y):
'''prints a report of the values of x and y'''
for k in zip(x,y):
print(f'{k[0]:.4f},{k[1]:.4f}')
def plot(x,y):
'''This function plots the values of y=sin(x)'''
plt.plot(x,y)
plt.xlabel('x')
plt.ylabel('y=sin x')
plt.show()
if __name__=="__main__":
print('executed directly')
print(__doc__)
x,y=compute()
report(x,y)
plot(x,y)
else:
print('imported as a module')
x,y=compute()