• Home
  • Python
  • About
  • Functions

    Functions are used to define a block of code that can be called several times. print, input and len are global functions provided by Python. Likewise, we can define our own functions.

    Functions can have 0 or more parameters:

    # Definition
    def greet(name):
      print("Hello " + name + "!")
    
    
    # Use it
    greet("Peter") # Hello Peter!

    Use the return keyword to define the value that will be available in the outer scope when the function finishes running.

    # a and b are function arguments
    def add_numbers(a, b):
      return a + b
    
    result = add_numbers(1,2)
    print(result) # 3

    Common uses of functions are:

    1. Avoid repetition by defining the same logic once and calling it when needed. See DRY
    2. Code organization: give a meaningful name to parts of the code that are maybe too long.
    Dictionaries
    Github Back to the top