Saturday, July 2, 2022

Python - Functions

# Functions

def my_function():
  print("Hello from a function")

my_function()

# So apparently we can redefine functions
# Notice the function name below is the same one defined above
def my_function(fname):
    print(fname + " Smith")
    

my_function("John")
my_function("Jane")

# Two args
def my_function(fname, lname):
    print (fname + " " + lname)

my_function("John", "Doe")
my_function("Jane", "Smith")

# This will break because not right number of args
#my_function("Pat")
#my_function("Richard", "Paul", "Astley")

print ("---")

def my_function(*kids):
    for kid in kids:
        print(kid)
# Prints John, Jane, Richard    
my_function("John", "Jane", "Richard")

print ("---")

# You can specify arguments instead of relying on order
def my_function(child3, child2, child1):
  print("The youngest child is " + child3)

# Displays Linus
my_function(child1 = "Emil", child2 = "Tobias", child3 = "Linus")


print ("===")

# Default parameter values
def my_function(country = "Norway"):
  print("I am from " + country)

my_function("Sweden")
my_function("India")
# Displays "I am from Norway"
my_function()
my_function("Brazil")

# Return a value
def my_function(x):
    return 5 * x

# Displays 15, 25, 45
print(my_function(3))
print(my_function(5))
print(my_function(9))

print ("---")

# Empty functions
def myfunction():
    pass