fb pixel

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