Better Programming

Advice for programmers.

Follow publication

Member-only story

12 Examples To Understand Python User-Defined Functions

Niall McNulty
Better Programming
Published in
8 min readMar 28, 2021

An open laptop surrounded by photos of cars
Photo by Boitumelo Phetla on Unsplash

Hello, and welcome to my guide to Python user-defined functions. This article will cover the basics of Python user-defined functions, the syntax you must master, and examples to help you consolidate your newly acquired knowledge.

Introduction

In simple terms, a function takes an input, performs a computation, and produces an output. Python has user-defined functions, anonymous functions, and built-in functions, such as the print() function. I’m sure you will all recognise the print() function as your introductory line of code to the wonderful world of programming.

print("Hello World")
>>> Hello World

Today, however, we are going to focus on user-defined functions. In programming, you will eventually reach a point where you are regurgitating the same code over and over. This is time-consuming and unnecessarily repetitive. In programming, there is an acronym for this: DRY (don't repeat yourself)! To avoid this you can define your own functions. This will help make your code organised, manageable, and re-usable. The idea is that instead of writing the same code again and again for different inputs, you can call (use) your functions when necessary.

blackboard filled with the words “I will not repeat myself again”
flickr.com

The syntax is the set of rules that defines code (in this case, your function).

The first line (header)

  • the keyword def
  • the function name (keep it relevant — link to naming conventions)
  • parentheses (), which may or may not include parameters and arguments
  • and a colon :

Function/statement block (body)

  • The following lines of the function block include what the function is supposed to do. All these lines have to be indented (press Tab).
  • The first statement of a function can be an optional statement…

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Niall McNulty
Niall McNulty

Written by Niall McNulty

I’m a junior data scientist who enjoys long-distance running, football, travelling, reading, food, programming… the list could go on. Never stop learning!

Responses (1)

Write a response

Nice, just what i needed :)

2