#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ ENGG1811 Lecture Week 6 An example to illustrate keyword arguments """ # %% # The function arrange has three parameters: num1, num2, order # The inputs num1 and num2 are expected to be numbers # The input order is expected to the string 'ascending' or 'descending' # Its purpose is to print the numbers supplied to the function in # ascending or descending order depending on the string input order def arrange(num1, num2, order): # big <- bigger number # small <- smaller number if num1 >= num2: big, small = num1, num2 else: big, small = num2, num1 # Print in ascending or descending # order depending on the input if order == 'ascending': print(order,':',small, big) elif order == 'descending': print(order,':',big, small) else: print('Invalid option') # %% First let us understand what the function does arrange(9, 7, 'ascending') arrange(2, 5, 'ascending') arrange(9, 7, 'descending') arrange(2, 5, 'descending') # %% Using keyword arguments # All the following calling methods are valid arrange(10, 7, 'ascending') arrange(10, 7, order = 'ascending') arrange(10, num2 = 7, order = 'ascending') # %% Order of keywords argument is not important, arrange(10, order = 'ascending', num2 = 7) arrange(num1 = 10, num2 = 7 , order = 'ascending') arrange(num2 = 7 , num1 = 10, order = 'ascending') arrange(order = 'ascending', num2 = 7, num1 = 10) # %% # The following will give an error: arrange(10, num2 = 7, 'ascending') # Error: positional argument follows keyword argument # %% Other errors: # arrange(2,5) # TypeError: arrange() missing 1 required positional argument: 'order' # arrange(10, order = 'ascending', numx = 7) # TypeError: arrange() got an unexpected keyword argument 'numx'