This chapter describes the absolute basics in Python: assignments and expressions, how to type a number or a string, how to indicate comments in code, and so forth. It starts out with a discussion of how Python blocks structures its code, which is different from any other major language.
Indentation and block structuring :
Python differs from most other programming languages because it uses white-space and indentation to determine block structure (that is, to determine what constitutes the body of a loop, the else clause of a conditional, and so on). Most language use braces of some sort to do this. Below is C code that calculate the factorial of 9, leaving the result in the variable r :
Differentiating comments :
For the most part, anything following a # symbol in a Python file is a comment and is disregarded by the language. The obvious exception is a # in a string, which is just a character of that string :
Variables and assignments :
The most commonly used command in Python is assignment, which looks pretty close to what you might've used in other languages. Python code to create a variable called x and assign value 5 to that variable is :
In Python, neither a variable type declaration nor an end-of-line delimiter is necessary, unlike in many other computer languages. The line is ended by the end of the line. Variables are created automatically when they're first assigned.
Python variables can be set to any object, unlike C or many other languages' variables, which can store only the type of value they're declared as. The following is perfectly legal Python code :
x starts out referring to the string object "Hello" and then refers to the integer object 5. Of course, this feature can be abused because arbitrarily assigning the same variable name to refer successively to different data types can make code confusing to understand.
A new assignment overrides any previous assignments. The del statement delete the variable. Trying to print the variable's contents after deleting it gives an error the same as if the variable had never been created in the first place :
Here we have our first look at a traceback, which is printed when an error, called an exception, has been detected. The last line tells us what exception was detected, which in this case is a NameError exception on x. After its deletion, x is no longer a valid variable name. In this example, the trace returns only line 1, in
Variable names are case sensitive and can include any alphanumeric character as well as underscores but most start with a letter or underscore.
Python supports arithmetic and similar expressions; these will be familiar to most readers. The following code calculates the average of 3 and 5, leaving the result in the variable z :
You’ve already seen that Python, like most other programming languages, indicates strings through the use of double quotes. This line leaves the string "Hello, World" in the variable x :
Backslashes can be used to escape characters, to give them special meanings. \n means the newline character, \t means the tab character, \\ means a single normal backslash character, and \" is a plain double-quote character. It doesn’t end the string :
double quotes to be included without backslashes :
Because you’re probably familiar with standard numeric operations from other languages, here doesn’t contain a separate chapter describing Python’s numeric
abilities. This section describes the unique features of Python numbers, and the Python documentation lists the available functions.
Python offers four kinds of numbers: integers, floats, complex numbers, and Booleans. An integer constant is written as an integer—0, –11, +33, 123456—and has unlimited range, restricted only by the resources of your machine. A float can be written with a decimal point or using scientific notation: 3.14, –2E-8, 2.718281828. The precision of these values is governed by the underlying machine but is typically equal to double (64-bit) types in C. Complex numbers are probably of limited interest and are discussed separately later in the section. Booleans are either True or False and behave identically to 1 and 0 except for their string representations.
Arithmetic is much like it is in C. Operations involving two integers produce an integer, except for division (/), where a float results. If the // division symbol is used, the result is an integer, with truncation. Operations involving a float always produce a float. Here are a few examples :
These are explicit conversions between types (1). int() will truncate float values. Numbers in Python have two advantages over C or Java. First, integers can be arbitrarily large; and second, the division of two integers results in a float.
- Built-in numeric functions
Python provides the following number-related functions as part of its core :
- Advanced numeric functions
More advanced numeric functions such as the trig and hyperbolic trig functions, as well as a few useful constants, aren’t built-ins in Python but are provided in a standard module called math. Modules will be explained in detail later; for now, it’s sufficient to know that the math functions in this section must be made available by starting your Python program or interactive session with the statement :
- Numeric computation
The core Python installation isn’t well suited to intensive numeric computation because of speed constraints. But the powerful Python extension NumPy provides highly efficient implementations of many advanced numeric operations. The emphasis is on array operations, including multidimensional matrices and more advanced functions such as the Fast Fourier Transform.
- Complex numbers
Complex numbers are created automatically whenever an expression of the form nj is encountered, with n having the same form as a Python integer or float. j is, of course, standard engineering notation for the imaginary number equal to the square root of –1. Note that Python expresses the resulting complex number in parentheses, as a way of indicating that what is printed to the screen represents the value of a single object :
Calculating j * j gives the expected answer of –1, but the result remains a Python complex number object. Complex numbers are never converted automatically to equivalent real or integer objects. But you can easily access their real and imaginary parts with real and imag :
(Note that real and imaginary parts of a complex number are always returned as floatingpoint numbers.)
- Advanced complex-number functions
The functions in the math module don’t apply to complex numbers; the rationale is that most users want the square root of –1 to generate an error, not an answer! Instead, similar functions, which can operate on complex numbers, are provided in the cmath module :
In order to make clear in the code that these are special-purpose complex-number functions and to avoid name conflicts with the more normal equivalents, it’s best to import the cmath module by saying :
and then to explicitly refer to the cmath package when using the function :
The None value :
In addition to standard types such as strings and numbers, Python has a special basic data type that defines a single special data object called None. As the name suggests, None is used to represent an empty value. It appears in various guises throughout Python. For example, a procedure in Python is just a function that doesn’t explicitly return a value, which means that, by default, it returns None.
None is often useful in day-to-day Python programming as a placeholder, to indicate a point in a data structure where meaningful data will eventually be found, even though that data hasn’t yet been calculated. You can easily test for the presence of None, because there is only one instance of None in the entire Python system (all references to None point to the same object), and None is equivalent only to itself.
Getting input from the user :
You can also use the input() function to get input from the user. Use the prompt string you want displayed to the user as input’s parameter :
This is a fairly simple way to get user input. The one catch is that the input comes in as a string, so if you want to use it as a number, you have to use the int() or float()function to convert it.
Built-in operators :
Python provides various built-in operators, from the standard (such as +, *, and so on) to the more esoteric, such as operators for performing bit shifting, bitwise logical functions, and so forth. Most of these operators are no more unique to Python than to any other language, and hence I won’t explain them in the main text. You can find a complete list of the Python built-in operators in the documentation.
Basic Python style :
Python has relatively few limitations on coding style with the obvious exception of the requirement to use indentation to organize code into blocks. Even in that case, the amount of indentation and type of indentation (tabs versus spaces) isn’t mandated. However, there are preferred stylistic conventions for Python, which are contained inPython Enhancement Proposal (PEP) 8, which is summarized in the appendix. A selection of Pythonic conventions is provided in table 4.1, but to fully absorb Pythonic style you’ll need to periodically reread PEP 8 :
* [Python 學習筆記] 函式、類別與模組 : 模組 (import、import as、from import)