DEV Community

Cover image for Python Functions.
Acar Emmanuel
Acar Emmanuel

Posted on

Python Functions.

What is a function?

Simply put, a function in general terms is a sequence of statements that performs a computation. When you define a function , you give it a name followed by these sequence of statements.
Later on, you call the function by the defined name to perform what it was assigned to do.
If you have worked with python before you have probably worked with a function already! Chances are high that you did not know it even , take an example when you are trying to find the type of a value,

type(32)
 # Output is <class 'int'>
Enter fullscreen mode Exit fullscreen mode

Tada! Easy right? Right there was among the functions you used along the way. It is one of many inbuilt functions that come along with python.
The name of the function right there is type and the expression in the parenthesis is called the argument of the function. An argument is a value that we pass into the function as an input and in this case the result of the type function is the type of the argument - an integer.
Briefly the main take away is that a function takes an argument and returns a return value.

Let's take a dive into in-built functions;

Python comes bundled with a lot of in- built functions. We will only look at a few of them.

  • The max and min function. These return the largest and smallest value respectively.
        numbers  = [4,6,1,0,56,78]
        print(max(numbers)) # returns 78
        print(min(numbers)) # returns 0


Enter fullscreen mode Exit fullscreen mode
  • Type conversion function. These take values of one type and convert them to the type specified by that particular function but of course only when it can. Otherwise, an error is returned. Let's visualize it;
      >>> int('32')   #returns 32
      >>> int('Hello')  
       """ Returns value error. ValueError: 
          invalid literal for int() with base 10: 'Hello' """
      >>>int(3.455966696)  # returns 3

      >>>float(32)  #returns 32.0

      >>> float('3.14159') #returns 3.14159

      >>> str(40) # returns '40'
      >>> str(23.9)  # returns '23.9'

Enter fullscreen mode Exit fullscreen mode
  • Random numbers. These are used to avoid a deterministic approach to things for example when designing a game you probably would not want your users to guess the next move so why not make them random. Not only that, how about the issue of security and privacy? Imagine a One Time Pin(OTP) or internet banking password that can be easily guessed because it follows a certain known pattern , why not do it the random way using python's inbuilt random function. For example when you want to generate 10 random numbers,check below.
   import random
   for x in range(10):
       x  = random.random()
       print(x)
   # returns 10 random numbers.
Enter fullscreen mode Exit fullscreen mode

The random function returns a float betwen 0.00 and 1.00(including 0.00 but not 1.00).
Each time you run the above function a different set of 10 random numbers are generated as values of x.
Other functions that handle random numbers are randint and choice

    >>> random.randint(5,9) # returns any number from 5 to 9
     t = [3,6,4]
     >>> random.choice(t) #returns any value
Enter fullscreen mode Exit fullscreen mode
  • Math function. There are set of in built functions in python that simplifies mathematical computations. We import the math library to be able to use these functions e.g. sqrt,log,sin,tan.
   import math
   >>> degrees = 45
   >>> radians = degrees/360.0 * 2 * math.pi
   >>>math.sin(radians)
Enter fullscreen mode Exit fullscreen mode

User-defined functions.

You most likely have been waiting for this one. On top of Python's in-built functions. We can as well create our own functions.
To do this we use the def keyword followed by the function name and parameters if any.

   #defining a function in python
   def function_name(parameters): #may or may not have 
                                   #parameters
         # function statements here
Enter fullscreen mode Exit fullscreen mode

Take an example of a function that prints the name of movies and takes no parameters.

   def movie_titles():
       print("Coming 2 America")
       print("Out of Death")
       print("War room")

   movie_title()  # function call

    #Output is the movie titles above
Enter fullscreen mode Exit fullscreen mode

See also an example of a function that takes parameters. This one counts the number of items in a list.

   list  = [2,5,6,3]
   def count_list(list):
        count = 0
        for number in list:
              count = count + 1
        return count

   print(f"The number of items in the list is {count_list(list)})

Enter fullscreen mode Exit fullscreen mode

Arguments and parameters.

Parameters are the variables that are defined during function declaration. They are found inside the the parenthesis.
On the other hand, arguments are the actual values that are assigned to the parameters.

def add(a,b):
   added  = a + b
   return added
x = add(3,5) # returns 8. 5 and 3 are the arguments of the function.
Enter fullscreen mode Exit fullscreen mode

Fruitful and void functions.

"Fruitful" functions are those that have a return value. For example the above function which adds two numbers. When you assign it to x we get a return value of 8.
On the other hand, void functions are those that gives an output but do not have a return value.This is demonstrated by the previous example that was printing movie titles. When we assign the movie_list() function to let's say movies we get None simply because there is no return value.

That's the end of today's article I hope you learnt something.

Top comments (2)

Collapse
 
anonymoux47 profile image
AnonymouX47 • Edited

Not bad for a beginner but you should note a few things:

  • type, int, float, str are classes, NOT functions... they're fundamentally different types in python.
  • Every function has a return value... None is a return value.
Collapse
 
manuel_a profile image
Acar Emmanuel

Thanks so much for your feedback. It helps me to be better.