Skip to main content

11.3) Functions (cont'd)


  • x and c are only defined within the function. They are local variables. Add a few lines at the end of your program to print the value of x and c. You should get an error. The variables are deleted as soon as you leave the function
  • Return is a keyword that allows you to return a value when you call your function. Here you return the value of the variable c. In this example you could shorten your code and write directly:
return x*x*x
  • You call (i.e. execute) a function by writing its name, followed by round brackets : cube(). If you have arguments to your function, simply provide a value or variable name: cube(a) or cube(3)
  • If your function returns a value, you can assign it to a variable (e.g. as in 'y', above), or print it directly

Important: you need to define your function before you call it, just like you need to assign a value to a variable before you use it. Your can put your functions at the start of programs, below the import statements, to avoid issues.