DEV Community

loading...
Cover image for Writing functions in Python

Writing functions in Python

Chris Bongers
I write daily web development tips that help you become a more efficient developer. 👨‍💻⚡️
Originally published at daily-dev-tips.com ・2 min read

Functions are an essential part of programming, as they can execute a block of code at once.
Often it's an excellent way to re-use blocks of code.

Let's give it a go and see how they work in Python.

Creating a function in Python

A function is made by prefixing the def keyword.

def foo():
    print("Bar")
Enter fullscreen mode Exit fullscreen mode

However, running our code now will not do anything since we didn't call our function yet.

Executing the function

To run/execute the function, we must call it somewhere in our code. In general, this happens when a specific criterion is matched, but let's just run it as is.

def foo():
    print("Bar")

foo()
Enter fullscreen mode Exit fullscreen mode

When we run our code now, it returns Bar

Passing and returning data

Having a function that prints out something is not convenient so let's see how we can give it data and return something.

Let's say we want to make a function that multiplies a number by itself and returns the output.

Meaning, if we put in the number 5, it should run 5x5 and return 25.

def multiply(number):
    return number * number

print(multiply(5))
Enter fullscreen mode Exit fullscreen mode

Running this code will indeed return 25.

We can easily have the function accept multiple arguments like so:

def multiply(number, multiplier):
    return number * multiplier

print(multiply(5, 10))
Enter fullscreen mode Exit fullscreen mode

This will return 50.

And one cool thing we can do is send the arguments based on their key value like this.

multiply(number=5, multiplier=2)
Enter fullscreen mode Exit fullscreen mode

You might not know how many arguments you're expecting in some cases, and you can prepend the argument with an asterisk (*).

def feed_animals(*animals):
    print(animals)
    print(animals[1])

feed_animals('Cow', 'Chicken', 'Goat')
Enter fullscreen mode Exit fullscreen mode

Which will return:

('Cow', 'Chicken', 'Goat')
Goat
Enter fullscreen mode Exit fullscreen mode

There are some more additions to functions, but this covers the basics for Python functions.

Thank you for reading, and let's connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter

Discussion (8)

Collapse
hanpari profile image
Pavel Morava

If you use the print statement inside something you call a function instead of the keyword return, you are creating a function with the constant return value which is None.

I wish people stopped using this demonstrations altogether because the other beginners think it is normal and encouraged practice.

Sigh, I know Python is not purely functional language, but side effects should be omitted as often as possible, and not used as educational technique.

People should use print when nobody is looking and delete all proof afterwards. 😋

Collapse
dailydevtips1 profile image
Chris Bongers Author

Fair enough, but at this point I'm learning it, and it's a valid way for me to see what it does, it's how I learn so why can't other people learn like that?

Especially if you haven't crossed the debugging part yet 😅
But valid point that a production app shouldn't have logs, same for console.logs in JS

Collapse
hanpari profile image
Pavel Morava

If you are learning Python, you should try Jupyter notebooks instead.

Or just create ipynb file if you are using VSCode or PyCharm.

Each cell will print the output for you.

Thread Thread
dailydevtips1 profile image
Chris Bongers Author

Oh cool, thanks for this information will look into that!

Collapse
waylonwalker profile image
Waylon Walker

Keep up the work Chris.

An extension of functions are lambda functions. They are one liners that make it easy to embed them inline with other functions.

mult = lambda x,y: x * y

mult(2,2)
Enter fullscreen mode Exit fullscreen mode

Generally its not best practice to name a lambda like this though, and linters will yell and tell you to just make a regular function. Their power is embedding in other objects easily.

node(lambda x: x * 2, 'input_dataset', 'input_mult_2')
Enter fullscreen mode Exit fullscreen mode

Here is a simple example of something I do often to create kedro nodes. I make simple functions right inline of creating the DAG node.

Collapse
dailydevtips1 profile image
Chris Bongers Author

Yeah had Lambda on my sheet, so they are basically your shorthand arrow function compared to JavaScript?
Or why are they introduced?

I must say I find the full write-out more readable at the moment, but might come in handy for sure!

Collapse
artydev profile image
artydev

Great to see you are diving in Python :-)
I began to use it a long time ago when Perl dominate the scene.
Good journey :-)

Collapse
dailydevtips1 profile image
Chris Bongers Author

Yeah it's quite fun to see the differences, and so far liking how many built-in stuff Python has