Excerpt from Python core programming (second edition) comments As with most scripts and Unix-shell languages, Python also uses the # notation to mark comments, starting with # until the end of the line is commented. >>> # One comment ... print ' Hello world! ' # another Commenthello world There is a special note called a document string. You can add a string to the beginning of a module, class, or function to function as an online document, a feature that Java programmers are very familiar with. def foo (): "This is a doc string." Return true Unlike normal annotations, a document string can be accessed at run time, or it can be used to automatically generate documents. operators like most other languages, the standard arithmetic operators in Python work the way you're familiar +-*///% **python Of course there are standard comparison operators, which compare operations based on the true or false return of the value of an expression Boolean < <= > >= = = = <>python also provides logical operators and or not variables and assignments python the variable name rules in the same way as most other high-level languages are affected by C (or the language itself is C Written in the language). A variable name is simply an identifier that begins with a letter-the so-called letter beginning-meaning uppercase or lowercase letters, plus an underscore (_). The other characters can be numbers, letters, or underscores. The python variable name is case-sensitive, meaning that the variable "box" is two different variables than the one. python is a dynamic type language, meaning that you do not need to declare the type of the variable beforehand. The type and value of the variable are initialized at the moment of assignment. Variable assignment is performed by an equal sign. python does not support the self-increment 1 and decrement 1 operators in the C language, because the + and-is also a single-mesh operator, and Python interprets--n as-(-N) to get N, and the same ++n result is n. number python supports five basic number types, three of which are integer types。 int (signed integer) long (Long Integer) bool (Boolean) float (floating-point value) complex (plural) string python string is defined as a character set between quotes. Python supports the use of paired single or double quotes, with three quotation marks (three consecutive single or double quotes) that can be used to contain special characters. Use the index operator ([]) and the Slice operator ([:]) to get substrings. A string has its own index rule: The index of the first character is 0, and the last character's index is-1. >>> pystr = ' Python ' >>> iscool = ' is cool! ' >>> pystr[0] ' P ' >>> pystr[2:5] ' tho ' >>> iscool[:2] ' is ' >>> iscool[3:] ' cool! ' >>> iscool[-1] '! ' >>> pystr + iscool ' Pythonis cool! ' >>> pystr + ' + iscool ' Python is cool! ' >>> pystr * 2 ' pythonpython ' >>> '-' *--------------------' >>> pystr = ' python ... is cool ' ' >>> pystr ' Python\nis cool ' >>> print Pystrpythonis cool>>> list and tuples Lists and tuples can be treated as normal "arrays", which can hold any number of arbitrary types of Python objects. As well as arrays, elements are accessed through a numeric index starting at 0, but lists and tuples can store different types of objects. There are several important differences between a list and a tuple. The list element is wrapped in brackets ([]), and the number of elements and the value of the element can be changed. Tuple elements are wrapped in parentheses (()) and cannot be changed (although their content can). Tuples can be viewed as read-only lists. A subset can be obtained by slicing operations ([] and [:]), which is the same as the way strings are used. >>> alist = [1, 2, 3, 4]>>> alist[1, 2, 3, 4]>>> alist[0]1>>> alist[2:][3, 4]>>> aList[:3][1, 2, 3]> >> alist[1] = 5>>> alist[1, 5, 3, 4] tuples can also perform slicing operations, resulting in tuples (cannot be modified):>>> atuple = (' Robots ', ' atuple ', ', ' Try ') >>> (' Robots ', ' robots ', ' try ') >>> Atuple[:3] >>& Gt ATUPLE[1] = 5Traceback (innermost last): File ' <stdin> ', line 1, in? Typeerror:object doesn ' t support item assignment Dictionary Dictionary is a mapping data type in Python, consisting of a key-value (Key-value) pair. Almost all types of Python objects can be used as keys, but they are usually most commonly used in numbers or strings. The value can be any type of Python object, and the dictionary element is wrapped in curly braces ({}). >>> adict = {' Host ': ' Earth '} # Create dict>>> adict[' port ' = # Add to dict>>> adict{' host ' : ' Earth ', ' Port ': 80}>>> adict.keys () [' Host ', ' Port ']>>> adict[' host '] ' Earth ' >>> for key in Adict:. Print key, Adict[key]...host earthport 80 code block and indent alignment code block to express code logic by indenting alignment instead of using braces Because there are no extra characters, the program is more readable.And indentation can clearly express exactly what block of code a statement belongs to. Of course, code blocks can also consist of only one statement. The syntax of the &NBSP;IF statement Standard IF condition statement is as follows: if expression: if_suite The code group If_suite is executed if the value of the expression is not 0 or is a Boolean value of true; Otherwise, proceed to the next statement. A code group is a Python term that consists of one or more statements that represent a block of child code. Unlike other languages, Python does not need to be enclosed in parentheses. If x < .0: print ' "X" must be atleast 0! python of course also supports the Else statement, the syntax is as follows: if expression: &N Bsp if_suiteelse: else_suite python also supports elif (meaning "else-if") statements with the following syntax: if expression1: & nbsp If_suiteelif expression2: elif_suiteelse: Else_suite while cycle The syntax of a standard while conditional loop statement is similar to the IF. While expression: while_suite statement While_suite is executed in a continuous loop until the value of the expression becomes 0 or False; Then Python executes the next line of code. Similar to the IF statement, the conditional expression in Python's while statement does not need to be enclosed in parentheses. >>> counter = 0>>> while counter < 3: ... print ' Loop #%d '% (counter) ... Counter + = 1loop #0loop #1loop #2 for cycle and RAThe For Loop in Nge () built-in functions python is not the same as the traditional for loop (counter loop), which is more like a foreach iteration in a shell script. A for in Python accepts an iterative object, such as a sequence or iterator, as its argument, iterating over one of the elements at a time. print ' I like-to-use the Internet for: ' For item in [' E-mail ', ' net-surfing ', ' homework ', ' chat ']: print item, The # print statement adds a line break to each row by default. As long as you add a comma (,) at the end of the print statement, you can change this behavior. Print # an additional print statement without any parameters, which is used to output a newline character. >>> for Eachnum in [0, 1, 2]: .... Print Eachnum ... 012 >>> for Eachnum in range (3): ... Print Eachnum ... 012 >>> foo = ' abc ' >>> for C in foo: ... print c...abc range () function often and l The En () function is used together with the string index. Here we want to display each element and its index value:>>> foo = ' abc ' >>> for I in range (len (foo)): ... print foo[i], ' (%d) '% i...a (0) B (1) C (2) List parsing This is a pleasing term that means you can use a for loop in a row to put all the values into a list:>>> squared = [x * * 2 for X in range (4)]>>> For i in squared: ... print i0149 list parsing can even do more complex things, such as picking out the values that fit the requirements put in the list:>>> sqDevens = [x * * 2 for X in range (8) if not x 2]>>>>>> for i in Sqdevens: ... print i041636 files and built-in functions open () file access is a very important link after you have become accustomed to the syntax of a language. After some work is done, it is important to save it to persistent storage. Handle = open (file_name, mode = ' R ') file_name variable contains the string name of the file we want to open, mode ' R ' means read, ' W ' means write, ' a ' means Add. Other possible sounds include ' + ' for Read and write, ' B ' for binary access. If mode is not provided, the default value is ' R '. If Open () succeeds, a file object handle is returned. All subsequent file operations must be done through this file handle. When a file object is returned, we can access some of its methods, such as ReadLines () and close (). The method properties of a file object must also be accessed through the period property identifier. Below are some code that prompts the user to enter a file name, then opens a document and displays its contents to the screen: filename = raw_input (' Enter file name: ') fobj = open (Filenam E, ' R ') for Eachline in fobj: print eachline, # because each line of text in the file has its own newline character, if we do not suppress the newline symbol generated by the print statement, the text will be displayed with an extra The empty rows generated. Fobj.close () Errors and exceptions compile will check for syntax errors, but Python also allows errors to be detected while the program is running. When an error is detected, the Python interpreter throws an exception and displays the details of the exception. The programmer can quickly locate the problem and debug it based on this information, and find a way to handle the error. To add error detection and exception handling to your code, just encapsulate them in the try-except statement. The code group after try is the code that you intend to manage. Code group after except, it is the code that you handle the error. try: filename = raw_input (' Enter file name: ') fobj = open (filename, ' R ') for Eachl Ine in fobj: print eachline, Fobj.close () except IOError, e: print ' File open error : ', e programmers can also deliberately throw an exception by using the Raise statement. functions similar to other languages, functions in Python are called with parentheses (()). Functions must be defined before they are called. If there is no return statement in the function, the None object is returned automatically. Python is called by reference. This means that changes to the parameters within the function affect the original object. However, in fact, only mutable objects are affected by this, and for immutable objects, it behaves like a value call. How to define function def function_name ([arguments]): "Optional documentation string" function_suite The syntax for defining a function consists of the DEF keyword and the function name immediately following it, plus several parameters required by the function. The function arguments (compared to the arguments in the example above) are optional, which is why you put them in brackets. (Don't write the brackets in your code!) This statement is terminated by a colon (as in the end of the IF and while statements), followed by a code group that represents the body of the function, a short example: Def addme2me (x): ' Apply + operation to Argument ' return (x + x) How to call Functions >>> Addme2me (4.25) 8.5>>>>>> Addme2me (10) 20>>>>>> addme2me (' Python ') ' Pythonpython ' >>>>>> addme2me ([-1, ' abc ']) [-1, ' abc ', -1, ' abc '] the calling function in the python language is the same as in other high-level languages, with the function name plus the function operator, and a pair of parentheses. The parentheses are all optional parameters. The parentheses cannot be omitted, even if a parameter is not there. Default parameters function parameters can have a default value, if provided with a default value, in the function definition, the parameter is provided in the form of an assignment statement. In fact, this is just the syntax that provides the default argument, which means that if the parameter is not supplied when the function is called, it takes the value as the default value. >>> def foo (debug=true): ... ' Determine if in debug mode with default argument ' ... if Debug: ... print ' in debug mode ' ... print ' Done ' ...>>> foo () in debug mod edone>>> foo (False) The done class class is the core of object-oriented programming, which acts as a container for related data and logic. They provide a blueprint for creating "real" objects (i.e., instances). Because Python does not compel you to program in an object-oriented way (unlike Java). How to define Classes Class ClassName (Base_class[es]): "Optional documentation string" static_member_declarations method_declarations Define classes using the Class keyword. can provide an optional parent class or base class; If there is no suitable base class, thenUse object as the base class. The class line is followed by an optional document string, a static member definition, and a method definition. Class Fooclass (object): "" "" My very first Class:fooclass "" " Version = 0.1 # class (data) Attribu Tedef __init__ (self, nm= ' John Doe '): # all names start and end with two underscores are special methods "" "Constructor" "" Self.name = NM # class instance (data) attribute print ' Created A class instance for ', Nmdef showname (self): & nbsp "" "Display instance attribute and class name" "" print ' Your name is ', self.name print ' My Name is ', Self.__class__.__name__def showver (self): "" Display class (Static) attribute "" " Print Self.version # References Fooclass.versiondef addme2me (self, x): # Does don't use ' self ' ' "" Apply + Opera tion to Argument "" " return x + x When a class instance is created, the __init__ () method executes automatically after the class instance is created, similar to the build function. __INIT__ () can be used as a build function, but unlike a build function in other languages, it does not create an instance-it is just the first method that executes after your object is created. Its purpose is to perform some of the necessary initialization work for that object. By creating your own __init__ () partymethod, you can override the default __init__ () method (the default method does nothing), which allows you to decorate the object you just created. In this example, we initialize a class instance property (or member) named name. This variable exists only in the class instance and is not part of the actual class itself. __INIT__ () requires a default parameter, as described in the previous section. Without a doubt, you also notice that each method has a parameter, self. What is self? It is a reference to the class instance itself. Other languages typically use an identifier called this. How to create a class instance >>> foo1 = Fooclass () Created A class instance for John doe The string displayed on the screen It is the result of the automatic invocation of the __init__ () method. When an instance is created, __init__ () is automatically called. Whether this __int__ () is custom or default. Creating a class instance is like calling a function that does have the same syntax. They are all callable objects. class instances use the same function operator to invoke a function or method. Now that we have successfully created the first class instance, here are some methods to call:>>> Foo1.showname () Your name is John doemy name is __main__. Fooclass>>>>>> foo1.showver () 0.1>>> print Foo1.addme2me (5) 10>>> Print Foo1.addme2me (' xyz ') xyzxyz Each method's call returns the result we expect. The more interesting data is the class name. In the ShowName () method, we display the value of the self.__class__.__name__ variable. For an instance, this variable represents the name of the class that instantiates it. (self.__class__ refers to the actual class). In our case, we didn't pass the name argument when we created the class instance, so the default parameter, ' John Doe ', was automatically used. In our next example, we will specify a parameter. >>> Foo2 = Fooclass (' Jane Smith ') Created a class instance for Jane Smith>>> Foo2.showname () Your name is Jane smithmy name is fooclass module module is a form of organization that This related Python code is organized into separate files. A module can contain executable code, functions and classes, or a combination of these things. When you create a Python source file, the name of the module is the file name without the. py suffix. Once a module is created, you can import the module from another module using an import statement. How to import modules imports module_name How to access a module function or access a module variable once the import is complete, a module of properties (functions and variables) can be passed through the familiar. The period property identifies the method access. Module.function () module.variable Now we offer Hello world! again example, but this time use the output function in the SYS module. >>> Import sys>>> sys.stdout.write (' Hello world!\n ') Hello world!>>> sys.platform ' Win32 ' >>> sys.version ' 2.4.2 (#67, Sep 2005, 10:51:12) [MSC v.1310 + bit (Intel)] ' & nbsp;
Getting started with Python