CMSC 201

Lab 5: Functions

What are functions?

A function is a block of code that can be used over and over again without having to retype the code which shortens the amount of typing you have to do overall. A function should fulfill one specific task (calculate area, check if a number is prime, sort a list, etc.)

How do I make them?

The first line of the function contains it's name and any of it's parameters, followed by a colon.

A function with no parameters:

def myFirstFunction():
     print("I did the thing!")


A function with 2 parameters:
def mySecondFunction(num1, num2):
     sum = num1 + num2
     difference = num1-num2


A function that returns something
def findSum(numA, numB):
     sum = numA + numB
     return sum


A function that returns lots of things
def returnThings():
     //code goes here
     return val1, val2, val3