Python Principles

Python Function Syntax

You can read about what functions are here.

Here are some examples of simple functions:

def f(x):
    return x+2

def g(y):
    return y*5

def h(a, b):
    result = a + b
    return result

Here's how to call the functions:

result1 = f(123)
result2 = g(10)
result3 = h(5, 7)

Here are all the parts that go into a function:

  • the def keyword
    • this tells Python we're defining a function
  • the function name
    • it must obey the same rules as for variable names
    • use all-lowercase with underscores for spaces
  • a left parenthesis (
  • one or more parameters
    • these are similar to variables
    • the parameters take the values of the function call arguments
    • multiple parameters, if any, are separated by commas
  • a right parenthesis )
  • a colon :
  • the function body
    • this is the code that runs when you call the function
    • the function body must be indented (moved four spaces in)
  • the return keyword
    • this goes inside the function body
    • it sends a value back to the caller of the function