• Homework
  • Thirds
  • Upper Thirds
  • Fourth
  • Divisions
    • ICT
    • Computer Science
  • Fifth
  • Lower Sixth
  • Upper Sixth
    • Upper Sixth Theory
  • Blog
  • Careers
  • Unity
  • Networking
computinglesson.com

Defining and using functions in Python

Challenges

Creating a function

Functions are used to group useful pieces of code together so that you can give them a name and easily use them whenever you want.

Use the keyword  def  to define a function
Give the function a name
Add any parameters between the brackets
for example ...
def square():
This function doesn't have any parameters so we just use round brackets with nothing inbetween - they're still needed though.
Picture

Using or 'calling' a function

Picture
Using a function just requires calling its name.

Make sure that you use brackets when you call a function, even if there's nothing in them.

Using a parameter with a function

Functions become really useful when we add parameters to them, like dials on the front of a machine, they allow us to control the key variables inside. 

A function with parameters is flexible and can do many things.
Picture

Calling a function with a parameter

Picture

Random numbers and challenges

The program on the left shows how you can call the same function with a different parameter to make the function do different things.

You should always call a function with exactly the number of parameters set out in the def statement (the definition)
Powered by Create your own unique website with customizable templates.