How To Create and Use Python Functions

Python Functions
(Image credit: Pexels)
4

Functions are incredibly powerful. We use them every day of our lives. When our parents said “clean your room!” We knew what had to be done. Functions are blocks of code that are executed when we call their name. But they can do much more than that. Functions can have arguments (parameters) passed to them, so we could pass a function the latest temperature from a sensor and use the function to trigger a fan to turn on. We could use a function to read the contents of a dictionary and work on the data stored within it.

In this how to. we will introduce the concept of functions and a few of its most powerful features. We will also build a project to read the current status of our PC and provide the data to the Python Shell.

Latest Videos FromTom's Hardware
TOPICS
Les Pounder
Associate Editor

Les Pounder is an associate editor at Tom's Hardware. He is a creative technologist and for seven years has created projects to educate and inspire minds both young and old. He has worked with the Raspberry Pi Foundation to write and deliver their teacher training program "Picademy".

  • Li Ken-un
    Not 100% the same, but much terser while not overly dense: 🙂

    from operator import call
    from psutil import cpu_count, cpu_freq, cpu_percent, virtual_memory

    funcs = {
    'cpuspeed': lambda: f"The CPU speed is {cpu_freq():,} MHz.",
    'cores': lambda: f"This CPU has {cpu_count(False):,} cores and {cpu_count():,} threads.",
    'cpu': lambda: f"Current CPU usage is {cpu_percent():,}%.",
    'ram': lambda: f"There is {round(virtual_memory() / 1024 ** 2):,} MB of available RAM."
    }
    combined_funcs = lambda: '\n'.join(call(func) for func in funcs.values())
    try:
    while True:
    func_to_call = funcs.get(input("Please type 'cpu', 'ram', 'cores', 'cpuspeed' or press ENTER to show all stats: "), combined_funcs)
    print(call(func_to_call))
    except KeyboardInterrupt:
    print("Exiting…")
    Reply
  • bit_user
    Another Python article; more missed opportunities. This time:
    storing & passing functions as variables & parameters
    lamdas (as @Li Ken-un demonstrated)
    packed argument lists
    higher-order functions: filter(), map()
    member functions & static member functions (though, I don't know if you've yet introduced objects)
    curring (i.e. function argument binding)
    Here's a simple example demonstrating several of those techniques:
    add = lambda x, y: x + y
    print( "add( 7, 9 ) =", add( 7, 9 ), "\n" )

    def curry_first( f, first ):
    return lambda *args: f( first, *args )

    add_1 = curry_first( add, 1 )
    for i in map( add_1, ):
    print( i )
    Output:
    add( 7, 9 ) = 16

    2
    3
    4
    Explanation:
    lambda is used to define an unnamed function. In this case, a lambda with 2 arguments is defined which simply adds them.
    The variable add is defined to hold this lambda, which effectively turns it into a function.
    To demonstrate this, it's used to add 7 and 9.
    Next, the curry_first() function is used to bind a value of 1, for the first argument of add. The resulting function takes only a single argument and adds 1 to it.
    Now, we use the map() builtin function to apply add_1() to each element in the list .
    This is done in a for loop, so the resulting value can be printed. I could've used a list comprehension to print the result in one shot, but I figure the example is already terse enough.
    Reply
  • Li Ken-un
    bit_user said:
    def curry_first( f, first ):
    return lambda *args: f( first, *args )
    curry_first is just partial from functools. 😉

    from operator import add
    from functools import partial

    add_1 = partial(add, 1)

    print(f"add( 7, 9 ) = {add( 7, 9 )}\n" )
    for i in map(add_1, ):
    print(i)from operator import add
    from functools import partial
    from toolz import compose

    add_1 = partial(add, 1)

    print(f"add( 7, 9 ) = {add( 7, 9 )}\n" )

    add_1_and_print = compose(print, add_1)

    for i in :
    add_1_and_print(i)

    There are some additional imports that go very well with the stuff in functools, including itertools and operators. I recommend toolz which provides even more constructs like compose and pipe without having to define them yourself in every project/script.
    Reply
  • bit_user
    Li Ken-un said:
    curry_first is just partial from functools. 😉
    I figured there must be a module for doing it, but I thought it was more instructive to see a trivial example of how to actually implement it.

    For real world use, I'd definitely recommend people use functools or whatever seems the most polished implementation.
    Reply