Learning Python

12. Using Functions

12.1. The basics about functions

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


def main():
    my_function()
def my_function(fname):
    print(fname + " Refsnes")


def main():
    my_function("Emil")
    my_function("Tobias")
    my_function("Linus")
def my_function(x):
    return 5 * x


def main():
    print(my_function(3))
    print(my_function(5))
    print(my_function(9))
def my_function(country = "Norway"):
    print("I am from " + country)


def main():
    my_function("Sweden")
    my_function("India")
    my_function()
    my_function("Brazil")

12.2. Introduction to Lambda

A lambda function is an anonymous function

Syntax:

lambda arguments : expression
#!/usr/bin/env python3

def main():
    x = lambda a : a + 2
    print(x(2))


if __name__ == "__main__":
    main()

Output:

4
#!/usr/bin/env python3

def main():
    x = lambda a, b : a + b
    print(x(2, 3))


if __name__ == "__main__":
    main()

Output:

5

12.3. Using Lambda functions

#!/usr/bin/env python3

def myDouble(x):
    return lambda a : a * x

def main():
    double = myDouble(2)
    print(double(3))
    print(double(4))


if __name__ == "__main__":
    main()

Output:

6
8