10.1. Function Basics

10.1.1. Function definition

  • Reuse code

  • Improves code readability

  • Clean-up code

  • Allows for easier refactoring

def hello():
    print('My name... José Jiménez')

hello()     # My name... José Jiménez
hello()     # My name... José Jiménez
hello()     # My name... José Jiménez

10.1.2. Returning values

  • return keyword indicates outcome of the function

  • Code after return will not execute

def hello():
    return 'ehlo world'

output = hello()

print(output)
# 'ehlo world'
def hello():
    return 'ehlo world'
    print('This will not be executed')

output = hello()

print(output)
# 'ehlo world'

10.1.2.1. Returning simple types

def function():
    return 42
def function():
    return 13.37
def function():
    return 'Mark Watney'
def function():
    return (42, 13.37, 'Mark Watney')
def function():
    return 42, 13.37, 'Mark Watney'
def function():
    return [42, 13.37, 'Mark Watney']
def function():
    return {42, 13.37, 'Mark Watney'}
def function():
    return {'first_name': 'Mark', 'last_name': 'Watney'}
def function():
    return True
def function():
    return None
def function():
    print('ehlo world')
    # Python will ``return None`` if no explicit return is specified
def function():
    pass
    # Python will ``return None`` if no explicit return is specified
def function():
    # Python will ``return None`` if no explicit return is specified

10.1.2.2. Returning nested types

def function():
    return [
        ('Mark', 'Watney'),
        {'Jan Twardowski', 'Melissa Lewis'},
        {'astro': 'Иванович', 'agency': {'name': 'Roscosmos'}},
        {'astro': 'Jiménez', 'missions': ('Mercury', 'Gemini', 'Apollo')},
    ]

10.1.3. Function arguments

10.1.3.1. Required arguments

def subtract(a, b):
    return a - b

10.1.3.2. Arguments with default value

  • Arguments without default values are required

  • Function will take default value if not overwritten by user

  • Arguments with default values must be at the right side

  • Arguments with default values can be omitted while executing

def subtract(a=1, b=2):
    return a - b
def subtract(a, b=2):
    return a - b
def subtract(a=1, b):
    return a - b

# SyntaxError: non-default argument follows default argument

10.1.3.3. Positional arguments

def subtract(a, b):
    return a - b

subtract(2, 1)      # 1
subtract(1, 2)      # -1

10.1.3.4. Keyword arguments

  • Arguments without default values are required

  • Order of keyword arguments has no significance

def subtract(a, b):
    return a - b

subtract(a=2, b=1)  # 1
subtract(b=1, a=2)  # 1
subtract(2, b=1)    # 1
subtract(a=2, 1)    # SyntaxError: positional argument follows keyword argument
def hello(name='José Jiménez'):
     print(f'My name... {name}')


hello('Mark Watney')          # My name... Mark Watney
hello(name='Mark Watney')     # My name... Mark Watney
hello()                       # My name... José Jiménez
def connect(username, password, host='127.0.0.1',
            port=80, ssl=True, keep_alive=1, persistent=False):
    print('Connecting...')


connect('admin', 'admin', 'localhost', 80, False, 1, True)

connect(host='localhost', username='admin', password='admin', ssl=True, keep_alive=1, persistent=True)

connect(
    host='localhost',
    username='admin',
    password='admin',
    port=443,
    ssl=True,
    persistent=True,
)
def read_csv(filepath_or_buffer, sep=', ', delimiter=None, header='infer',
             names=None, index_col=None, usecols=None, squeeze=False, prefix=None,
             mangle_dupe_cols=True, dtype=None, engine=None, converters=None,
             true_values=None, false_values=None, skipinitialspace=False,
             skiprows=None, nrows=None, na_values=None, keep_default_na=True,
             na_filter=True, verbose=False, skip_blank_lines=True, parse_dates=False,
             infer_datetime_format=False, keep_date_col=False, date_parser=None,
             dayfirst=False, iterator=False, chunksize=None, compression='infer',
             thousands=None, decimal=b'.', lineterminator=None, quotechar='"',
             quoting=0, escapechar=None, comment=None, encoding=None, dialect=None,
             tupleize_cols=None, error_bad_lines=True, warn_bad_lines=True,
             skipfooter=0, doublequote=True, delim_whitespace=False, low_memory=True,
             memory_map=False, float_precision=None):
    """
    Definition of pandas.read_csv() function
    https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html
    """


my_file1 = read_csv('iris.csv')

my_file2 = read_csv('iris.csv', encoding='utf-8')

my_file3 = read_csv(
    filepath_or_buffer='iris.csv',
    encoding='utf-8',
    verbose=True,
    usecols=['Sepal Length', 'Species']
)

10.1.4. Naming convention

10.1.4.1. Function name convention

  • It's not Java, do not use camelCase

    def addNumbers(a, b):
        return a + b
    
  • It's Python, use snake_case # Python - snake ;)

    def add_numbers(a, b):
        return a + b
    

10.1.4.2. Use better names, rather than comments

def cal_var(results):
    """Calculate variance"""
    return sum((Xi-m) ** 2 for Xi in results) / len(results)
def calculate_variance(results):
    return sum((Xi-m) ** 2 for Xi in results) / len(results)

10.1.4.3. Name collisions

  • _ at the end of name when name collision

    def print_(text):
        print(f'<strong>{text}</strong>')
    

10.1.4.4. System functions names

  • __ at the beginning and end of name

    def __import__(module_name):
        ...
    

10.1.5. Variable scope

10.1.5.1. Global scope

  • All variables in main program

  • Variables are available inside all functions

print(globals())
# {...}

10.1.5.2. Local scope

  • Variables defined inside function

  • Variables are not available from outside

print(locals())
# {...}
def add_numbers(a, b=2):
    c = 3
    print(locals())

add_numbers(1)
# {'a': 1, 'b': 2, 'c': 3}

10.1.6. Assignments

10.1.6.1. Cleaning text input

English
  1. For given input data (see below)

  2. Write function cleaning up data

  3. Function takes one argument of type str

  4. Function returns cleaned text

Polish
  1. Dla danych wejściowych (patrz poniżej)

  2. Napisz funkcję czyszczącą dane

  3. Funkcja przyjmuje jeden argument typu str

  4. Funkcja zwraca oczyszczony tekst

Input
INPUT = List[str] = [
    'ul.Mieszka II',
    'UL. Zygmunta III WaZY',
    '  bolesława chrobrego ',
    'ul Jana III SobIESkiego',
    '\tul. Jana trzeciego Sobieskiego',
    'ulicaJana III Sobieskiego',
    'UL. JA\tNA 3 SOBIES  KIEGO',
    'ULICA JANA III SOBIESKIEGO  ',
    'ULICA. JANA III SOBIeskieGO',
    ' Jana 3 Sobieskiego  ',
    'Jana III Sobi\teskiego ',
]
Output
'Mieszka II'
'Zygmunta III Wazy'
'Bolesława Chrobrego'
'Jana III Sobieskiego'
'Jana III Sobieskiego'
'Jana III Sobieskiego'
'Jana III Sobieskiego'
'Jana III Sobieskiego'
'Jana III Sobieskiego'
'Jana III Sobieskiego'
'Jana III Sobieskiego'
The whys and wherefores
  • Defining and calling functions

  • Passing function arguments

  • Cleaning data from user input

Todo

Translate input data to English

10.1.6.2. Aviation numbers

English
  1. For input data (see below)

  2. Define function converting int or float to text form in Pilot's Speak

Polish
  1. Dla danych wejściowych (patrz poniżej)

  2. Zdefiniuj funkcję konwertującą int lub float na formę tekstową w mowie pilotów

Input
0, "zero"
1, "one"
2, "two"
3, "tree"
4, "fower"
5, "fife"
6, "six"
7, "seven"
8, "ait"
9, "niner"
1969
31337
13.37
31.337
-1969
-31.337
-49.35
Output
'one niner six niner'
'tree one tree tree seven'
'one tree and tree seven'
'tree one and tree tree seven'
'minus one niner six niner'
'minus tree one and tree tree seven'
'minus fower niner and tree fife'
The whys and wherefores
  • Defining and calling functions

  • Passing function arguments

  • Cleaning data from user input

  • dict lookups

10.1.6.3. Number to human readable

English
  1. For input data (see below)

  2. Define function converting int or float to text form

  3. Text form must be in proper grammar form

  4. Max 6 digits before decimal separator (point .)

  5. Max 5 digits after decimal separator (point .)

Polish
  1. Dla danych wejściowych (patrz poniżej)

  2. Zdefiniuj funkcję konwertującą int lub float na formę tekstową

  3. Forma tekstowa musi być poprawna gramatycznie

  4. Max 6 cyfr przed separatorem dziesiętnym (point .)

  5. Max 5 cyfr po separatorze dziesiętnym (point .)

Input
1969
31337
13.37
31.337
-1969
-31.337
-49.35
Output
'one thousand nine hundred sixty nine'
'thirty one thousand three hundred thirty seven'
'thirteen and thirty seven hundredths'
'thirty one three hundreds thirty seven thousands'
'minus one thousand nine hundred sixty nine'
'minus thirty one three hundreds thirty seven thousands'
'minus forty nine and thirty five hundreds'
The whys and wherefores
  • Defining and calling functions

  • Passing function arguments

  • Cleaning data from user input

  • dict lookups

10.1.6.4. Roman numbers

English
  1. Define function converting roman numerals to integer

  2. Define function converting integer to roman numerals

Polish
  1. Zdefiniuj funkcję przeliczającą liczbę rzymską na całkowitą

  2. Zdefiniuj funkcję przeliczającą liczbę całkowitą na rzymską

The whys and wherefores
  • Defining and calling functions

  • Checking for corner cases

  • Passing function arguments

  • Cleaning data from user input

  • dict lookups