Functions


Python.

We have reached the point where you understand that programs cannot be truly useful when following a sequential flow. Conditionals and Loops provide us with a great way to break up a program and its control flow, but by far the most valuable control flow mechanism for programming are functions.

Functions are a way to organize code, specifically a block of code, so it can be used throughout a program. They should be written in a way that they perform a single, related action. If done correctly, they will make a program more modular by allowing you to reuse code.

Python provides three different types of functions:

This module is all about learning Python functions. Topics to be covered: User-Defined Functions, Calling Functions, Arguments, and Return Values.


Challenges

Lastly, Python allows you to define your own functions. This is what we care about the most, as it allows you to write code that does a specific task and use it throughout your program. In this module we will focus on teaching you how to define your own functions (the syntax), how to pass arguments, and return values.

Python Function Syntax:

Python function definition follows these rules:

  • Function blocks begin with the keyword def followed by the function name, parentheses (), and a colon :
  • The code block then starts and must be indented
  • Finally, the statement return exits a function

Put that all together and you will get something that looks like this:

def FUNCTION_NAME():
	# Function Code Block Starts
  # Statement(s) to be executed
  return

Taking what we learned in the very first module, we can write a hello world greeting function. It would look like this:

def greeting():
	print("Hello World!")
  return

Now that this is created anytime we call the function greeting, "Hello World!" will be printed. This brings up a good point though, how do we call a function?

Defining a function only gives it a name, specifies the parameters that are to be used in the function, and structures the blocks of code to be included in the function. But, you need to be able to use that. The way to call a function is very similar to the way we called some of the built-in functions, like print() and int(). They are called by simply using the functions name. Using the greeting() function above, I will demonstrate how we would call it:

# Function Definition
def greeting():
	print("Hello World")
  return
  
# Main Program, we want to call it here
greeting()

Challenge:

Use python to write a functon that prints the number 1-10

  1. Create a new file with the file extension .py
  2. Write python, using a function, that prints the numbers 1-10
  3. Test your code with python yourFile.py
  4. Verify your solution with verify yourFile.py

Function arguments are the values or variables passed into a function when it is called. You can define what is to be passed when calling your function and the function's behavior will often depend on the arguments passed. This adds a new rule to our function definition:

  • Any parameters or arguments should be placed within the function definition's parentheses

While defining a function, you specify a list of variables within the parentheses (these are referred to as parameters). These parameters act as a placeholder for the data that will be passed to the function when it is called. When the function is called, value to each of these parameters must be provided and can be used just like any other variable, but are referred to by the parameter name. The values provided are known as arguments.

Example:

def greeting(name):
	print("Hello {}".format(name))
  return
  
greeting("Batman")
greeting("Brandon")
greeting("Chris")

Running this code will produce the following output:

Hello Batman
Hello Brandon
Hello Chris

Python supports mainy different types of Function Arguments, but the one we will cover in-depth is Positional/Required arguments. This is nothing new, as what we just wrote is considered a positional or required argument. They are called this, because the function cannot execute unless every parameter listed gets an argument in the correct positional order. Let's look at another example:

def printInfo(name, age):
	print("Name: ", name)
  print("Age: ", age)
  
printInfo("Brandon", 14)
printInfo("Chris")

Executing this code will print the following:

Name: Brandon
Age: 14
Traceback (most recent call last):
	File "test.py", line 6, in <module>
  	printInfo();
TypeError: printInfo() takes exactly 2 arguments (1 given)

From this we can see the first function call worked as expected because every parameter was passed in the correct order. The second one did not, as we did not pass anything for age and that is a required parameter.

Challenge:

Use python to write a basic calculator function

  1. Create a new file with the file extension .py
  2. Write python to accept two integers from the user
  3. Write python, using a function, that requires three parameters: number1, number2, and operation.
    1. Your calculator should support these operations: add, subtract, multiply, divide
    2. Print the result or an error message if the user attempts division by zero
  4. Call this function once for each supported operation
# Example Running of the program
python yourScript.py
Number 1: 13
Number 2: 12
25
1
156
1.08
  1. Test your code with python yourFile.py
  2. Verify your solution with verify yourFile.py

Now, sometimes we want functions to do something to our variables and return a result. This requires defining a function return value.

The return keyword as the last statement in function definition indicates the end of function block and that program flow "returns" to the calling function. Along with returning flow control, the function can also return values to the calling function. These values can be stores in variables for further processing. This introduces a change to the function definition rules:

  • Finally, the statement return [values] exits a function, optionally passing back a value to the calling function.

Let's also update our syntax:

def FUNCTION_NAME(PARAMETERS):
	# Function Code Block Starts
  # Statement(s) to be executed
  return VALUE

One thing to note, the return statement with no arguments (how we have been doing it up until this point) is the same as a return None statement.

Example:

def add(x,y,z)
	return x+y+z
  
a = 1
b = 2
c = 7
result = add(a,b,c)
print("a={}, b={}, c={}, a+b+c={},".format(a, b, c, result)

Executing this will produce the following output:

a=1, b=2, c=7, a+b+c=10

Challenge:

Use python to write a basic calculator function

  1. Create a new file with the file extension .py
  2. Write python to accept two integers from the user
  3. Write python, using a function, that requires three parameters: number1, number2, and operation.
    1. Your calculator should support these operations: add, subtract, multiply, divide
    2. Return the result or an error message if the user attempts division by zero
    3. Print the result outside the function
  4. Call this function once for each supported operation
# Example Running of the program
python yourScript.py
Number 1: 13
Number 2: 12
25
1
156
1.08
  1. Test your code with python yourFile.py
  2. Verify your solution with verify yourFile.py


30-Day Scoreboard:

This scoreboard reflects solves for challenges in this module after the module launched in this dojo.

Rank Hacker Badges Score