The Python interpreter starts reading from the top of the .py or .pyw file. When the interpreter encounters a def statement it executes the statement, thereby creating the function and binding the name following the def to it. Any code that is not inside a def statement (or inside a class statement, as we will see in the next chapter) is executed directly.
Python cannot call functions or use objects that have not been defined. So Python programs that occupy a single file tend to have a Pascal-like structure with lots of function definitions from the top down, and at the end a call to one of them to start the processing off.
Unlike C++ and Java, Python programs do not have a fixed entry point, and the name "main" is not special. The Python interpreter simply executes the code it encounters from the first line down. For example, here is a complete Python program:
The interpreter executes def hello(), that is, it creates the hello() function, then creates the world() function, and then creates the main() function. Finally the interpreter reaches a function call, to main() in this case, so the interpreter executes the function call, at which point what we normally think of as program execution commences.
Python programmers usually put only one statement at the top level, a call to the first function they want to execute. They usually call this function main(), and call their other functions from it, resulting in a structure similar to that used by C++ and Java.
Since def statements are executed at runtime, it is possible to use different definitions depending on the situation. This is especially useful when we want to use functionality in one version of Python that is not available in an earlier one, without forcing our users to upgrade.
For example, Python 2.4 introduced the sorted() function. What if we had some code that needed sorted(), but some of our users were using Python 2.3 and some were using 2.4 or later? We could simply rely on the sorted() method for 2.4 or later, and provide our own equivalent function for older Pythons:
import sys if sys.version_info[:2] < (2, 4): def sorted(items):
items = list(items) items.sort() return items
We begin by importing the sys module, which provides the version_info tuple. Then we use this tuple to get the major and minor version numbers. Only if the version is lower than 2.4 do we define our own sorted() function. Notice also that we can compare tuples: Python can compare data structures, including nested ones, providing all the types they contain can be compared.
Was this article helpful?
Discover How You Can Quickly And Easily Dominate Google and YouTube... With Simple Cash Generating Videos. Did you know that YouTube is the second largest search website on the entire Internet? YouTube gets more daily searches than Bing and Yahoo. In fact, there is only one search engine that gets more action.