Defining a Function in Python
When I first taught myself Perl I couldn’t wait to get coding, so I started on a project before I’d read the chapter on subroutines. I ended up writing an entire Web forum in a single vast conditional statement. I don’t know whether to be proud that I made it work or ashamed of the monstrosity I must have created. If you want to write clean code, or at least code that isn’t a total nightmare, you’ll want to tuck most of it away in small focussed and reusable functions. Like any decent language, PHP and Python both support functions.
PHP Code Example:
sayHello() function prints a given
$name value and returns
print "Hello, $name!";
// Hello, Matt!
Here, we create the function and then try it out by calling it with the string “Matt”.
For this example we haven’t used type hinting for the
$name argument or specified a return type. Since Python does not enforce either feature we will discuss urgument and return type constraints in another article.
Note: Although Python does not constrain the types of arguments, as of Python 3.5 it does support optional type annotations. We will cover these in a future article.
Python Code Example:
Here is an equivalent fragment in Python.
# Hello, Matt!
The divergences between a Python and a PHP function are pretty clear in the examples. We must use
def rather than
function, indentation rather than braces, a colon after the parentheses. Despite these obvious syntactical differences, functions in Python should represent no conceptual challenge for the PHP developer. The Python equivalent to PHP’s
Although it’s not enforced in any way, if you’re a PHP coder trying to pass unmolested in the land of the Python it is a good idea to follow the PEP 8 styleguide which has this to say about function names:
Function names should be lowercase, with words separated by underscores as necessary to improve readability.
Variable names follow the same convention as function names.
mixedCase is allowed only in contexts where that’s already the prevailing style (e.g. threading.py), to retain backwards compatibility.
To return a value you must use a
return statement. In PHP if you fail to return a value (which can be a perfectly valid choice) your function will resolve to
null. In Python, a function which does not explicitly return a value will resolve to
Note: Functionally equivalent to
Noneis actually an object which is used to indicate the absence of a value. A very Hidden Hat concept!
Stay up to date with the Python for PHP Programmers project