# arguments with keywords and variable number of arguments # # Matt Bishop, MHI 289I, Fall 2020 # # # first, keywords def pr(first, second): print("first =", first, "-- second =", second) # say what this is print("Here's how named parameters work") print("The declaration is 'def pr(first, second)'") # now we print a couple of these print("pr(3, 5):", end=' '); pr(3, 5) print("pr(5, 3):", end=' '); pr(5, 3) # now name the parameters print("pr(second=9, first=6):", end=' '); pr(second=9, first=6) # # now show default values # def pr2(first=5, second=10): print("first =", first, "-- second =", second) # say what this is print("\nHere's how default parameter values work") print("The declaration is 'def pr2(first=5, second=10)'") # show how it works print("pr2(3, 5):", end=' '); pr2(3, 5) print("pr2(3):", end=' '); pr2(3) print("pr2(second=10):", end=' '); pr2(second=20) # # and now a variable number of arguments # def pr3(*args): print(args) # say what this is print("\nHere's how a variable number of arguments works") print("The declaration is 'def pr3(*args)' and it prints the args as a tuple") # show how it works print("pr3():", end=' '); pr3() print("pr3(1):", end=' '); pr3(1) print("pr3(1, 2):", end=' '); pr3(1, 2) print("pr3(1, 2, 3):", end=' '); pr3(1, 2, 3) # # same, but we print them one at a time # def pr4(*args): # start with the first argument n = 0 # walk the argument list for i in args: # first argument is numbered 1, then successive # arguments are numbered 2, 3, ... n += 1 print("\targ #%d:" % n, i) print("\nThe declaration is 'def pr4(*args)' and it prints the args one at a time") # show how it works print("pr4():", end=' '); pr4() print("pr4('a'):"); pr4('a') print("pr4('b', 'c'):"); pr4('b', 'c') print("pr4('d', 'e', 'f'):"); pr4('d', 'e', 'f')