Learning Python: Functions

Functions

simple function

def say_hello_world():
    """Prints hello world"""
    print("Hello World")

calling function

say_hello_world()

simple function with parameter

def say_hello(someone):
    """Says Hello to someone"""
    print(f"Hello {someone}")

calling function

say_hello("Friends")

simple function with multiple parameters

def say_hello_and_more(someone, and_more):
    """Says Hello to some and append more text"""
    print(f"Hello {someone}, {and_more}")

calling function

say_hello_and_more("Friends", "GreatDay!")

simple function with arbitrary parameters

def say_hello_to_many(*people):
    """Says hello to many people
    :people: names in tuple
    """
    for name in people:
        print(f"Hello {name}")

calling function

say_hello_to_many("Khalesi", "Cersei", "Yara")

with default arguments

def say_hello_to_world_or_someone(someone=None):
    """Prints hello world if no name is provided"""
    if someone is None:
        print("Hello World")
    else:
        print(f"Hello {someone}")

calling function

say_hello_to_world_or_someone()

say_hello_to_world_or_someone("Mogambo")

returning a single value

def get_hello_message(language="EN"):
    return "Hello"

print(get_hello_message())

returning mulitple values (aka tuple)

def infamous_siblings():
    return "Cersei", "Jamie"

# approach 1
x = infamous_siblings()
print(x[0])
print(x[1])

# approach 2 
sibbling_1, sibbling_2 = infamous_siblings()
print(sibbling_1)
print(sibbling_2)

Lambdas

  • A lambda function is a small anonymous function
  • A lambda function can take any number of arguments, but can only have one expression

Syntax

lamba arguments: expression

Example

x = lambda a: a + 10
print(x(5))

x = lambda a, b: a + b
print(x(5, 4))

x = lambda a, b, c: a + b + c
print(x(1, 2, 3))