Intermediate · Functions · 112 of 264
Perfect number
A number is perfect if it equals the sum of its divisors smaller than itself, like 6 = 1 + 2 + 3. Write a function and use it.
Input: a positive whole number. Output: perfect or not perfect
Examples
Input
6
Output
perfect
Input
28
Output
perfect
Input
12
Output
not perfect
2 more tests check other inputs when you press Check.
Stuck? The idea behind functions
A function, made with def, gives a name to a piece of code, so it can be used again: its parameters are the values it is given, return hands an answer back.
A function that returns lets the caller decide what to do with the answer: print it, compare it, use it in a sum.
def is_even(n):
return n % 2 == 0
print(is_even(4))
print(is_even(7))Watch for: print inside a function is not return: the caller gets None. And the code after return in the same block never runs.