fb pixel

Introduction to Python

  • Profound Academy

    • Status
      • 1
        Input and Output
      • 2
        Variables and Integer Arithmetic
      • 3
        Conditional Operators
      • 4
        Advanced Conditions - Nesting
      • 5
        Types and Variables
      • 6
        Strings
      • 7
        Lists
      • 8
        For Loops
      • 9
        While Loops
      • 10
        continue, break, while...else
      • 11
        String and List methods
      • 12
        Nested Loops
      • 13
        List Comprehension
      • 14
        Tuples and Sets
      • 15
        dict
      • 16
        Functions
      • 17
        Functions 2
      • 18
        Lambda and higher-order functions
      • 19
        Files

  • Variable number of arguments

    We’ve already seen some functions that accept a variable number of arguments like print() or zip(). Yet, we haven’t created one ourselves. How to write a function that can handle a variable number of arguments?
    When printing elements, we can call the print() function with as many arguments as we want and it will print all of them:
    print('Hi')                   # Hi
    print('Hi', 'how', 'are', 1)  # Hi how are 1
    print(1, 2, 3, 8)             # 1 2 3 8
    If we take a look at the function signature of print() in the official python docs, the first argument actually captures the whole list of arguments (non-keyword) passed to it. The same holds for the zip function:
    print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
    zip(*iterables, strict=False)
    Source: https://docs.python.org/3/library/functions.html
    We can define our own functions that accept a variable number of arguments with an asterisk *:
    def income(*purchases):
    	total = 0
    	for purchase in purchases:
    		total += purchase
    	return total
    
    print(income(1, 2, 3, 4, 10))  # 20
    Here we can treat purchases as a list of numbers. We can access its length with len(), we can loop over the elements with a for loop, etc.

    Challenge

    Implement a function num_args() that would return the number of arguments passed to it.
    Example calls to a function:
    def num_args(*args):
    	...
    
    print(num_args(1, 2, 3))  # 3
    print(num_args())         # 0
    print(num_args('Anna'))   # 1
     
    Pro tip 😎: It’s also possible to turn a simple list into *args:
    a = [1, 2, 3, 'hello']
    print(*a)
    
    # This is equivalent to
    print(1, 2, 3, 'hello')
    Now you know how to easily print lists.
     
    To check your solution you need to sign in
    Sign in to continue