In the second half of 2012, do you want to learn a new programming language? Select python!
There are two ways to learn a new language: 1. try to use the authentic expression of the language to avoid being influenced by the original language thinking; 2. associate the new language with the original language so that you can master the basic knowledge and compile useful programs as soon as possible. Generally, this is caused by project requirements.
There are the following reasons for learning Python: 1. strong expression capabilities, not inferior to main programming languages such as C, C ++ and Java. 2. it is a script-like language, which means that programming is simplified, and tasks that may be complex in the main programming language may be completed with less code; 3. the format is rigorous, which is conducive to code style training, software code readability, and project code management; 4. multiple libraries and frameworks allow you to quickly create applications. These four items are enough. Hurry up and try again!
My idea is to associate Python with Java to learn the basics of Python. therefore, this article does not describe the python syntax in detail, but enhances understanding of python by comparing differences. Of course, a large number of programming exercises are necessary and it is best to combine them with a small project, and keep trying and making mistakes. I learned how to use python by learning and using a company's actual project.
1. Python code indent: This is the first thing to mention. A code block enclosed in parentheses is expressed by a colon plus a correct indent (the same indentation must be used for a code block at the same level). Parentheses in a condition statement can be omitted. The semicolon at the end of the statement is optional. When writing a Python code block, you must add a colon and correct indentation. This is a common mistake. For example:
While (I <100 ){
I + = 2
Printf ("% d", X)
}
Write in Python as follows:
While I <100:
I + = 2 // The correct indent is necessary, otherwise a syntax error is reported.
# Print X # error: Unexpected indent. The code at the same level must use the same indentation, but one or more spaces will not work.
2. Before using a variable, you must initialize and assign values. Otherwise, the interpreter cannot recognize the variable. A variable can store multiple types of values without emphasizing the type. Type is not emphasized during function definition. This is a feature of the scripting language that facilitates programming. For example
Def func (x ):
Return x * 2
X = 2
Y = func (X)
Print X, "", y
X = 'now changed to an string'
Print X, "", Y, 'img '# loose print format. Double quotation marks and single quotation marks can both represent strings.
# Print ZZZ: nameerror: Name 'zzz' is not defined.
3. control Flow: If, if-Elif -... -Else,... in ..., while, continue, break; there is also a pass statement that indicates empty execution, that is, equivalent to empty blocks, or NOP
4. # is used for single-row comments, and three single quotes are used for multi-row comments.
'''These are
More lines.
'''
5. Powerful built-in dynamic data structures: List, set, tuple, and dictionary. These dynamic data structures can easily be combined into more powerful data structure tools. There are many articles on the Internet about the use of these structures, which will not be detailed here.
Mylist = [] # create an empty list
Mylist = [1, 3, 'good']
Print mylist
Mylist [1] = [('this is a tuple'), ['nested list']
Print mylist
List methods include: append (x), extend (list), insert (x), sort (), reversed (), pop ([I]), insert (I, x), and so on.
Myset = [1, 2, 1, 1, 2] # create a set ==> myset = [1, 2]
Set has the member detection function:
X = 1
If X in myset:
Print myset, "has member:", X
Else:
Print X, "is not found in", myset
Mydict = {1: ('zs', 'good', 25), 2: ('ww ', 'right', 30 )}
Print mydict
Mydict ['city'] = 'hangzhou'
For K, V in mydict. iteritems ():
Print K, V
Print dict. Keys ()
Tuple is similar to the list, but its value is unchangeable. The value of the referenced tuples adopts the subscript method.
Mytuple = (1, 2, 3, 4)
Print mytuple [2]
# Error: mytuple [0] = 0
6. module. A python file is a module with the suffix ". py. After you write the function sign (x) in func. py, You can reference it in other files as follows:
[1] import func
Func. Sign (x) # Module name. Function Name
[2] From func import sign (X)
Sign (x) # direct reference
7. Scope. Here is a basic understanding. As mentioned above,
A. a python file is a module. The variable scopes of this module can be divided into global scopes, local scopes, and built-in scopes.
B. code block (for example, try block, if-Else, for, while, etc.), variables, methods, and classes defined in the function belong to the local scope, and can be queried through locals, the scope of action is until the code block or function exits. variables, methods, and classes outside the function belong to the global scope. The scope of action is from the creation time to the end of the entire file. You can use globals () query.
C. When the variables in the global scope conflict with those in the local scope, the variables in the local scope will be used first, and the variables in the global scope will be searched later. To use global variables, you must declare global var first. The variable with the same name cannot appear before declaring global var. See:
X = 2
Def fun1 ():
X = 3
Print "[1] x =", X // use the local variable X to print [1] x = 3
Print "init: x =", X // use the global variable X to print init x = 2
Fun1 ()
Print "after [1] x =", X // does not change the global variable X print after [1] x = 2
Def fun2 ():
Global x // declare to use global variable X
X = 3
Fun2 ()
Print "after fun2: x =", X // print after fun2: x = 3
Def fun3 ():
X = 0
# Error global X: syntax error: X cannot be both a global variable and a local variable. That is to say,
Print "[3] x =", X: to use a global variable, it cannot appear after a local variable with the same name.
Fun3 ()
The built-in scope is the scope of system variables, methods, classes defined by the Python language and can be directly used. For example, the Type function can print the object type.
Print type (x) // print <type 'int'>
Def type (x ):
Print "My type ():"
Return x * 2
Print type (x) // print 6
Therefore, we can draw another conclusion: if a method with the same name as the built-in method is defined, the custom method is preferred. In fact, the priority of the scope:
Local scope global scope built-in Scope
8. Exception mechanism. Try-try t, try-try t-Else, try-finally, try-try t-finally.
9. If _ name _ = '_ main _': Do something; _ name _ is the built-in attribute of the python module. Each Python module is a. py file that can be run from the command line and imported into other modules. When running from the command line, __name _ = '_ main _', do something will execute; when importing other modules, the value of _ name _ is the module name, which is not equal to '_ main _'. Do something will not be executed. That is to say, some statements exist in this module. When it runs independently, it is expected to be executed, but it is not expected to be executed when it is used as a support module to import other modules.
Therefore, this statement can be used to run and test the module separately.
10. the following example demonstrates some basic language features provided by Python: indent, built-in data structure, control flow, read/write file, redirection, import module, class definition, exception mechanism, log, and regular expression. There is no innovation in the Code itself, but the integration can demonstrate most of the basic language features of Python.
Dupkeys. py
#################################################################### validate if the input text file contains duplicated keys.# the input.txt should like below:# key1 value1# key2 value2# ...## the result is stored into a hashtable:# {key: [count, [value1, value2,..,valueN]]} ###################################################################import sysimport refrom thelog import initlogfrom exc import NotMatchedExceptionpatt = re.compile(r'^\s*(\w+)\s+(\w+)[\s\r\n]+$')total_items = 0count = { }def proc(line) : matched = patt.match(line) try : if matched : global total_items total_items += 1 key = matched.group(1) value = matched.group(2) if key in count : valuelist = (count[key])[1] valuelist.append(value) count[key] = [(count[key])[0]+1, valuelist] else : count[key] = [1, [value]] else : raise NotMatchedException('The line Not matched: %s' % line) except (NotMatchedException, Exception), args: dupkeysLog.error(args)if len(sys.argv) != 2 : print "usage: python dupkeys.py filename.txt " sys.exit(1)logfile = 'dupkeys.log'dupkeysLog = initlog(logfile)resfile = open('result.txt', 'w')sysStdout = sys.stdoutsys.stdout = resfile # redirect stdout into file result.txt filename = sys.argv[1]inputfile = open(filename)for line in inputfile : proc(line)print "total items in file %s : %d" % (filename, total_items)dupkeysLog.error("Keys duplicated: ")for k, v in count.iteritems() : print k, v if v[0] > 1 : dupkeysLog.error( ' %s %s ' % (k, v) )if inputfile: inputfile.close()if resfile : resfile.close()sys.stdout = sysStdout
Thelog. py
import loggingLOG_LEVELS = { 'DEBUG': logging.DEBUG, 'INFO': logging.INFO, 'WARN': logging.WARNING, 'ERROR': logging.ERROR, 'CRITICAL': logging.CRITICAL }def initlog(filename) : logger = logging.getLogger() hdlr = logging.FileHandler(filename) formatter = logging.Formatter("%(asctime)s %(levelname)s %(message)s") hdlr.setFormatter(formatter) logger.addHandler(hdlr) logger.setLevel(LOG_LEVELS['ERROR']) return loggerif __name__ == '__main__' : errlog = initlog("errlog.log") errlog.info('this is an ordinary info') errlog.warn('this is a warning') errlog.error('this is an error that should be handled') errlog.critical('this is an severe error')
Exc. py
class MyException(Exception) : passclass MsgException(MyException) : def __init__(self, msg) : self.msg = msg def __str__(self) : return repr(self.msg)class NotMatchedException(MsgException) : pass