9. Functions ‐ Part 1 - MantsSk/CA_PTUA14 GitHub Wiki

Introduction

What is a function? Functions are a convenient way to divide your code into useful blocks, allowing us to order our code, make it more readable, reuse it and save some time. Also functions are a key way to define interfaces so programmers can share their code. In Python, you define a function with the def keyword, then write the function identifier (name) followed by parentheses and a colon. The next thing you have to do is make sure you indent with a tab or 4 spaces, and then specify what you want the function to do for you.

def function_name():
    # What to make the function do

A simple example - functions that prints 'Hello world':

def print_smth():
    print('Hello world!')

Or prints random int number from 0 to 10:

def get_random_number():
    print(random.randint(0, 10))

Just like built-in functions, user-defined functions are called using the function name followed by parenthesis :

get_random_number() 
print_smth()
# and so on....

Naming

Choosing names for your variables, functions and/or classes, and so forth can be challenging. You should put a fair amount of thought into your naming choices when writing code as it will make your code more readable. The best way to name your objects in Python is to use descriptive names to make it clear what the object represents. Main rules as follows:

  • Use only lowercase in method names.
def compute():
  pass
  • An underscore should separate words in a method name.
def calculate_smth():
  pass
  • Non-public method name should begin with a single underscore.
def _get_smth():
  pass
  • Use two consecutive underscores at the beginning of a method name, if it needs to be mangled.
def __get_secret():
  pass

A very good source of naming rules and examples are here: Python Function NamingMust be read!

Return statement

Return statements are used to end a function while returning an expression that can be used later on. However, they are not mandatory and can be left out when unneeded. Syntax:

return [expression]

Some Examples:

def find_sum(num1, num2):
    '''Returns the sum of num1 and num2.'''
    sum_nums = num1 + num2  # Finds the sum of num1 and num2
    return sum_nums  # Returns the sum of the numbers
def even_odd(num):

    '''
    Returns "even" if num is even, and "odd" if num is odd.    
    Parameters:
        num (int): Any integer    Returns:
        type (string): "even" if num is even; "odd" if num is odd
    '''

    if num % 2 == 0:  # Checks if num/2 has a remainder of 0
        return "even"  # If it has a remainder of 0, return "even"
    else:
        return "odd"  # If it doesn't, return "odd"

👨‍🏫 ❗ ATTENTIONIf [expression] is left empty, a None type object will be returned while exiting the function

def check_if_exist(a=None):
  if a:
    return a
  return
    

Parameters in Functions:

Parameters, or arguments, are values that you can pass to a function that will determine how a function will get executed. There are different ways on how we can pass the parameters.

Positional Parameters: The most common type of passing parameters is by calling a function and passing the parameters in the same position as in the definition of the function. Let’s take an example of a division function:

def integer_division(num_one, num_two):
    return num_one // num_two

integer_division(10, 2)

----OUTPUT----
>>>> 5

Keyword Parameters: We can also pass the parameters in a key=value format when calling a function. This means we don’t require to keep the sequence in mind. Consider the same function as above:

def integer_division(num_one=10, num_two=2):
    return num_one // num_two

integer_division(10, 2)

----OUTPUT----
>>>> 5

Exercises:

  • Create at least 5 different functions by your own and test it.
  • Create a function that adds a string ending to each member in a list.
  • Create a mini python program which would take two numbers as an input and would return their sum, subtraction, division, multiplication.
  • Create a function that returns only strings with unique characters.