35
Functions
Functions are a significant part of Python and most other languages. They are units of code that carry out a specific set of operations. And while functions can be called many times throughout a program, there are plenty of cases where a function is called just once but conveniently groups a set of operations that you need to call within a program.
Functions are usually called with one or more arguments and usually return some value when they exit. To declare a function, start with the def
keyword and end the declaration with parentheses and a colon. The actual code is indented four spaces, just as we saw for looping code. Let’s write a really simple function first that calculates the square of a number:
Get Python Programming with Design Patterns now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.