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

  • Keyword and positional arguments

    When calling functions we provide values for the arguments so that the function executes using those values. It’s possible to provide those values with both positional and keyword arguments:
    def rectangle(h, w, val=0):
    	return [[val] * w] * h
    
    print(rectangle(2, 3, 1))
    # [[1, 1, 1], [1, 1, 1]]
    def rectangle(h, w, val=0):
    	return [[val] * w] * h
    
    print(rectangle(2, w=3, val=1))
    # [[1, 1, 1], [1, 1, 1]]
    We can provide values for arguments by specifying the names of those arguments like we did in the second example (val=1 or w=3).
    This is especially useful for functions that have many arguments and most of them have default values. In that case, we can provide the keyword arguments for only the parameters we need and skip the rest.
    Note that keyword arguments don’t need to be provided in the same order as the function argument. They can have an arbitrary order as long as their names match the arguments of the function. It’s also important to note that positional arguments cannot follow keyword arguments. When calling a function we first specify the positional arguments and only then the keyword arguments. Can you think of why that’s the case 🤔?

    Challenge

    Given the function that prints the properties of a patient, call it 3 times with the following order of arguments:
    1. name, age, height
    1. age, name, height
    1. height, age, name
    The outputs of each call need to be the same, but you can use both positional and keyword arguments to call the function.
     
    To check your solution you need to sign in
    Sign in to continue