Python Syntax


One of the first things many newcomers to Python notice is how readable the code is. This makes Python a good choice for group projects, where many people will have to share and maintain programs. The ease of reading and maintaining Python code is one reason it is popular with so many programmers.

One very notable feature of Python that tends to startle experienced developers is the mandatory indentation. Instead of using keywords like do/done or punctuation like {}, you group statements (e.g., the block following an if statement) by indenting your code. Python is sensitive to white space, so to end a block you just return to the previous level of indentation. The section “Control Structures” shows exactly how this works.

Unlike C and Perl, Python does not require semicolons at the end of lines (although they can be used to separate multiple statements on a single line). Comments in Python start with a #, as in shell and Perl. You do not need to declare variables before using them, and memory management is done automatically

Using Python Modules

Python ships with a rich set of core libraries, called modules. Modules contain useful functions that you can call from your code. Some modules, like sys (for system functions like input and output) are very commonly used, but there are also more specialized modules, like socket and ftplib (for networking). To use a module, you have to import it with a line at the top of your script, after which you can use any of the functions or objects it contains. For example, you could import the math module, which includes the variable pi. Here’s how you would print the value of pi while in the interactive interpreter:

 >>> import math >>> print math.pi 3 .14159265359

This chapter describes the most commonly used Python modules. You can find out more about the core modules at http://docs.python.org/modindex.html. And, just for fun, you might want to try entering import this in the Python interpreter.




UNIX. The Complete Reference
UNIX: The Complete Reference, Second Edition (Complete Reference Series)
ISBN: 0072263369
EAN: 2147483647
Year: 2006
Pages: 316

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net