How to Write a Function in Python
Steps to creating a proper function with arguments follows!
- Define the function using “def”
Example : def
2. Give the function a name that will describe the function.
Example : def z_score
3. Using parenthesis, add the arguments of the function.
Example : def z_score(X, mu, sigma)
4. Add a colon after the parenthesis.
Example : def z_score(X, mu, sigma):
5. In the next line, you create a variable to pass in what you actually want the function to do.
Example: I named the variable (z) and ‘told’ it to subtract mu from X and then divide that answer by sigma.
def z_score(X, mu, sigma):
z = (X - mu) / sigma
6. Then, use the built in return function in python to return the line above.
Example : Just put return and the variable (z).
def z_score(X, mu, sigma):
z = (X - mu) / sigma
return z
7. To call the function, you would create a new variable, set it equal to the function and pass the arguments into the function.
Example :
def z_score(X, mu, sigma):
z = (X - mu) / sigma
return z
ans = z_score(26, 20, 3)
If we want to find the z_score of something using the function we have defined, I would pass the arguments into the parenthesis in the function and it should output the answer.
How this works:
When using this function to get an answer to something, the function takes the arguments and the variable that tells the function what to do with the arguments, passes in the new, numeric arguments and spits out the answer.