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

  • Functions inside functions

    Python is a very flexible language and it allows the creation of functions practically anywhere in the code. One can define a new function inside an if block, a for loop, or inside another function:
    def process(name1, name2, name3):
    	def greet(name):
    		if len(name) < 5:
    			print(f'Hi, {name}')
    		else:
    			print('The name is too long')
    	greet(name1)
    	greet(name2)
    	greet(name3)
    
    process('Anna', 'Bob', 'Daniel')
    # Hi, Anna
    # Hi, Bob
    # The name is too long
    Here we have defined a new function greet() which acts as a utility to not repeat the if, else statements for all the 3 names in the process() function.
    Note that the inner functions have access to all the variables defined above them. So, in our example, the function greet() has access to name1, name2, and name3.

    Challenge

    Modify the function so that it returns a list of all the divisors of numbers passed to it. Add an inner function that returns a list of divisors for a single number.
    def divisors(*numbers):
    	...
    
    print(divisors(4, 5))         # [1, 2, 4, 1, 5]
    print(divisors(3))            # [1, 3]
    print(divisors(6, 8))         # [1, 2, 3, 6, 1, 2, 4, 8]
     
    To check your solution you need to sign in
    Sign in to continue