?? Introduced?? Input/output?? Comments?? Operator?? Variable and assigned value?? Python type?? Indentation?? Cycle and condition?? File?? Error?? Function?? Class?? Module 2.3 Note Common annotations like most scripts and Unix-shell languages, Python also uses the # notation to mark comments, starting with # until the end of a line is commented.
>>> # One Comment
... print ' Hello world! ' # another comment
Hello world! Document string
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 regular annotations, a document string can be accessed at run time, or it can be used to automatically generate documents. Code Declaration note
Release (
the -*- symbols)
#-*-Coding:latin-1-*-
Python looks for coding: name or in the coding=name comment.
If you don ' t include such a comment, the default encoding used would be ASCII.
Unix executable Scripts (#!)
If You is goning to use Pythonon a Unix, linux,or unix-like system, you acan also turen files of Python code int o executable programs, much as you would for programs coded in a Sheel language such as CSH or Ksh. Such files are usually called executable scripts. In simple terms, Unix-style executable scripts is just normal text files containing Python statements, but with the Speci Al Properties:
Their first line is special.
Script usually start with a line this begins with the characters #! (often called "hash Bang"), followed by the path (the operating system uses it-to-find an
Interpreter for running the program code in the rest of the file) to the Python interpreter on your machine.
They usually has executable privileges.
Script files is usually marked as executable to tell the opration system that they could be run as top-level PR Ograms. On Unix Systems, a comamnd such as chmod +x file.py usually does thi trick.2.4 operator standard operator: + - * / // % ** Add, subtract, multiply, Both the except and the remainder are standard operators. Python has two division operators, a single slash used as a traditional division, and a double slash used as a floating-point division (rounding the result). Traditional division means that if the two operands are integers, it will be performed as a floor (whichever is smaller than the largest integer), whereas floating-point division is a true division, and floating-point division always performs true division, regardless of the type of operand. There is also a exponentiation operator, double star (* *). Comparison operators:< <= > >= == != <> logical operators:and or not index operator: [] slice operator: [:] Core style: reasonable use of parentheses to enhance the readability of the code, it is a good idea to use parentheses in many cases, and without parentheses, can cause the program to get incorrect results, or make the code less readable, causing the reader to be confused. Parentheses do not have to exist in the Python language, but it is always worthwhile to use parentheses for readability. Anyone who maintains your code will thank you, and you will thank yourself when you read your code again. Variable name rules in 2.5 variables and assignments python are the same as for C languages. 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 self-increment 1 in C language and the decrement 1 operator, which is because the + and-is also a monocular operator, Python interprets--n as-(-N) to get N, and the same ++n result is n.2.6 number python supports five basic number types, where There are three types of integers.
?? int (signed integer)?????? bool (Boolean) (True (1), False (0))?? Complex (Complex) Boolean is a special integer. Although a Boolean value is represented by a constant of true and false, if a Boolean value is placed in a numeric context (for example, true is added to a number), true is treated as an integer value of 1, and False is treated as an integer value of 0.
2.7 strings in string python are defined as the character set between quotation marks. 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. The plus sign (+) is used for string join operations, and the asterisk (*) is used for string repetition. 2.8 lists and tuples You can think of lists and tuples 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. The subset can be obtained by slicing operations ([] and [:]), which is the same as the use of strings. 2.9 Dictionary Dictionary is a mapping data type in Python that works like an associative array or hash table in Perl, 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 () & nbsp [' Host ', ' Port '] >>> adict[' host '] ' Earth ' >>> for key in adict: ... print key, adict[key] ... host earth2.10 code block and indent alignment code blocks use indentation alignment to express code logic instead of curly braces, because without 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. Maybe you'll find that the absence of curly braces in your life is not as bad as you think. The syntax for the 2.11&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. Python, of course, also supports the Else statement, with the following syntax:
if Expression:if_suiteelse:else_suite
Python also supports elif (meaning "else-if") statements with the following syntax:
if Expression1:if_suiteelif expression2:elif_suiteelse:else_suite
The syntax of the 2.12 while loop standard while condition Loop statement is similar to the IF. Again, use indentation to separate each child code block.
While
Expression:while_suite
The 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. 2.13 For Loop and range () the For loop in 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. 2.14 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 i
0149
List parsing can even do more complex things, such as picking up the values that fit the requirements into the list:
>>> Sqdevens = [x * * 2 for X in range (8) if not x% 2]>>>>>> for i in Sqdevens:
Print I
041636
2.15 files and built-in functions open (), file () after you have become accustomed to the syntax of a language, access to files is a very important link. After some work is done, it is important to save it to persistent storage. How to open the file handle = open (file_name, Access_mode = ' R ') the file_name variable contains the string name of the file we want to open, Access_mode ' r ' means read, ' W ' represents the Write, ' a ' represents the addition. Other possible sounds include ' + ' for Read and write, ' B ' for binary access. If Access_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 property of a file object must also access the core note through the period property identifier: What is a property? properties are data-related items that can be simple data values or executable objects, such as functions and methods. Which objects have properties? A lot. Classes, modules, files and complex numbers, and so on, have properties. How do I Access object properties? Use the period property to identify the method. This means adding a period between the object name and the property name: object.attribute.2.16 errors and exceptions compile-time 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. The code group after except is your code that handles the error. Try:filename = raw_input (' Enter file name: ') fobj = open (filename, ' R ') for Eachline 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. 2.17 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 a 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 ' Retu RN (x + x) This function, the work of "add me to my value". It takes an object, adds its value to itself, and then returns the and. For numeric type parameters, the result is obvious, but I want to point out here that the plus operator works almost with all data types. In other words, almost all standard data types support the + operator, whether it is a numeric addition or a sequence merge. How to call a function
>>> Addme2me (4.25) 8.5>>>>>> addme2me () 20>>>>>> addme2me (' Python ') ' Pythonpython ' >>>>>> addme2me ([-1, ' abc ']) [-1, ' abc ',-1, ' abc ']
Python calls functions in the same language as in other high-level languages, with function names plus function operators, and a pair of parentheses. Brackets are all optional parameters. Even if a parameter is not there, the parentheses cannot be omitted. Notice how the + operator works in non-numeric types. Parameters of the default parameter function can have a default value, and 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 ' ... &nb sp; >>> foo () in debug mode done >>> foo (False) done2.18 class &NB The sp; class is the core of object-oriented programming, which acts as a container for relevant data and logic. They provide a blueprint for creating "real" objects (i.e., instances). Because Python does not force you to program in an object-oriented way (unlike Java), you may not be able to learn classes at the moment. How to define a class
class ClassName (Base_class[es]): "Optional documentation string" Static_member_declarationsmethod_ Declarations
define classes using the Class keyword. can provide an optional parent class or base class; If there is no suitable base class, use object as the base class. The class line is followed by an optional document string, a static member definition, and a method definition. __init__ () method 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__ () method, you can override the default __init__ () method (the default method does nothing) to decorate the object you just created. 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 () 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. 2.19 Modules modules are a form of organization that organizes Python code that is related to each other into separate files. A module can contain executable code, functions and classes, or a combination of these things. How to import modules import module_name How to access a module function or access a module variable once the import is complete, The properties of a module (functions and variables) can be accessed through the familiar. Period property identifier. 2.20 practical functions for new Python programmers useful built-in functions
function Description dir ([obj]) Display object properties, if no parameters are provided, Displays the name of the global variable help ([obj]) to display the object's text in a neat and beautiful form File string, and if no arguments are provided, the interactive Help will be entered. int (obj) to convert an object to an integer len (o BJ) Returns the length of the object open (FN, mode) to open a file named fn in mode (' r ' = Read, ' W ' = Write) range ([[[Start,]stop[,step] ) Returns a list of integers. The starting value is start and the ending value is stop-1; The default value of start is 0, and the step default value is 1. Raw_input (str) Wait for the user to enter a string that can provide an optional parameter str as a cue message. STR (obj) Convert an object to a string type (obj) &NB Sp Returns the type of the object (the return value itself is a type Object!) )
Starting Python-python core programming