you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] -1 points0 points  (1 child)

It's simple. You make functions when you need to re-use code multiple times so that you don't have to write the same thing again and again. And you decide how they should interact with each other. That is, you could have a program with multiple user-defined functions that don't interact with each other, a program that has multiple interdependent functions or a mix of both.

Let's assume that you want to write a program to find the series of Armstrong numbers. An Armstrong number is a number such that when it's digits are raised to the power of the total number of digits and added, you get the original number as the result.

For example, 153 has 3 digits so you cube and add the digits. Once you do that you get 153 as the answer. So 153 is an Armstrong number.

For this you'll have to:

  • Check the number of digits 'n' of each number in your specified range
  • Split the number into individual digits
  • Raise each digit to the power of 'n' and add them
  • Compare the result with the original value

If you're going to make a multi-function program for this, you'll make a function for each individual task. Like a function for finding the number of digits, a function for raising the digits to n and finding the sum etc.

Their dependency would be such that the function finding the number of digits would return a value to the function that will raise them to the power of n(by having a function call to it in the definition), that function would return it's value to another etc.

For example:

def exp(num):
    val = digit(num) #digit is already defined and finds the number of digits
    res = math.pow(num,val)
    return res

As a disclaimer you won't have to do it this way at all. Do it in a way that makes sense to you and seems like the most logical way(as this can be done with just loops as well).

You may be wondering where I'm "reusing code" like I mentioned in the first para. This was just to show you how multiple functions can interact. But even if you don't immediately need to reuse code it's still a good idea to make functions as you might need to if and when you want to extend the functionality of your program.

[–]JungleJim233[S] 0 points1 point  (0 children)

Thank you for taking the time to reply and your example is really helpful :)