Knowledge Base

7. User Defined Functions

See 1.6 for general information on functions

7.1. Creating a Function

  1. Use keyword def followed by function name and parameters. End with a colon.
1def Is_This_a_Five(param1):
  1. Write the body of the function with each line indented by four spaces.
1def Is_This_a_Five(param1):
2 isFive = False
3 if param1 == 5:
4 isFive = True
  1. Use keyword return to indicate the value the function should return.
1def Is_This_a_Five(param1):
2 isFive = False
3 if param1 == 5:
4 isFive = True
5 return isFive

7.2. Default values

To set a default value for a parameter, set the parameter equal to the default value in the definition of the function.

The function apply_factor(2) returns 6 and apply_factor(2,factor=2) returns 4.

1def apply_factor(input_value,factor=3):
2 return input_value * factor

7.3. Positional vs keyword arguments

Positional arguments are assigned to function parameters based on the order of the arguments and the order of the parameters in the function’s definition.

  • When calling the function apply_power(3,4) (given below), 3 will be assigned to parameter input_value and 4 will be assigned to parameter power because of their relative positions.

Keyword arguments are assigned to function parameters by explicitly naming the parameter when calling the function.

  • When calling the function apply_power(power=3,input_value=4) 3 will be assigned to parameter factor and 4 will be assigned to parameter input_value because we used keyword arguments.
1def apply_factor(input_value,power=3):
2 return input_value ** power
Send Feedback
close
  • Bug
  • Improvement
  • Feature
Send Feedback
,