diveintopython.org
Python for experienced programmers

 

1.2. Declaring functions

Python has functions like most other languages, but it does not have separate interface and implementation declarations like C++ or Java. When you need a function, just declare it and code it.

Example 1.3. Declaring the buildConnectionString function

def buildConnectionString(params):

Several things to note here. First, the keyword def starts the function declaration. Unlike Visual Basic, Python doesn't distinguish between functions that return values and functions that don't. There are no subroutines. Everything is a function, and all functions start with def.

Second, the function doesn't define a return datatype. In fact, it doesn't even specify whether it returns a value or not. The function doesn't care one way or the other. If it ever executes a return statement, it will return a value, otherwise it won't. Of course, the calling script cares very much; if you try to assign a variable the value of a function that doesn't return a value, Python will raise an exception.

Third, the argument, params, doesn't specify a datatype. In Python, variables are never explicitly typed. Python figures out what type a variable is and keeps track of it internally.

Important
Automatic datatyping is a double-edged sword. It's convenient, and it can be extremely powerful. But it places an additional burden on you to understand when and how Python coerces data into different types.