Eliud Githuku




Day 4 of #30-days-of-code

Functions in Python

Eliud Githuku's photo
Eliud Githuku
·Dec 8, 2022·

2 min read

A function is a bunch of code that performs a particular task when called. From the definition, it is already as important to note that a function is useless if it is not called as it only performs the task assigned if it gets called. There are two types of functions in Python, and programming in general, that is, built-in functions such as the print() function in Python, and user-defined functions. Functions have the following syntax:

                                    def greetings():
                                       print('Hello World')

The def keyword is used to define the function. To call a function use the function name, which in our case is greetings. We can also pass arguments into the function when defining it, that is:

```def welcome_statement(name, age, gender): print('Hello', name, ) print('You are', age,'years old') print('Your gender is', gender) welcome_statement('Eliud', '23', 'Male')

### Return Keyword
The return keyword gives a response to what is being run, that is:

def sum_of_numbers(num1, num2, num3): return num1 + num2 + num3 print(f'The sum of the numbers is', sum_of_numbers(num1=50, num2=20, num3=30)) sum_of_numbers(num1=50, num2=20, num3=30)

The return keyword also signifies the end of a code block, that is, it does not run any code put under it in the same code block. Let's see this in an example:

def fname(name): return print('John') print('My name is', name) fname('eliud') ``` The output of the above code is 'John', which means that the "print('My name is', name)", has been ignored, which is also the line below the return keyword

Share this