Introduction to functions


🙋 Need help? Ask an expert now!

How do we apply this?

Lets play with some examples of writing functions. These will tend to be easy examples as we will be getting into more difficult functions in the next unit.

  • Write a function that takes an integer and returns the integer squared
# Define the function (Dont forget the colon) def square(value): #Return the value squared return value**2 # Call the function and print out the result print(square(10))

Another example with multiple arguments - Write a function that adds two numbers together

# Define the function (Don't forget the colon) def add(a,b): #Return the values added return a +b # Call the function print(add(10,12))

Don't forget, you can have strings and objects as arguments to your functions as well! Not just numbers! This is a good time to go play with functions in your own shell.

A couple of challenges to get you started (we will cover these in the next section)

  1. Write a function that gives back the length of a list
  2. Write a function that tells you whether or not the word 'cat' is in a string
  3. Write a function that returns whether or not the argument is string or an integer

You can practice here!!

Edit Me on GitHub!