Basic Python Tutorials and error-prone (text processing)

Source: Internet
Author: User

One: Basic tutorials

(1) file I/O is very similar to C language;io is input/output in the computer, that is, input and output. Because the program and runtime data resides in memory and is executed by the CPU, an ultra-fast compute core, where the data is exchanged, usually a disk, a network, and so on, requires an IO interface.

Spath= "D:/download/baa.txt" F=open (spath, "W") # Opens file for writing. Creates this file doesn ' t exist.f.write ("first line 1.\n") f.writelines ("First line 2.") F.close () F=open (spath, "R") # Opens file for readingfor line in F:print linef.close ()

(2) Exception handling try:except:In the process of running the program, if an error occurs, you can agree to return an error code beforehand, so that you can know if there is a mistake, and the cause of the error. It is common to return error codes in calls provided by the operating system. such as the function of opening a fileopen(), returns a file descriptor (that is, an integer) on success, and returns when an error occurs.-1.

S=raw_input ("Input your Age:") if s = = "": Raise Exception ("Input must no be empty.") Try:i=int (s) except Valueerror:print "Could not convert data to an integer." Except:print "Unknown exception!" Else: # It is useful for code this must be executed if the TRY clause does not raise a exceptionprint "you are%d"% i, " Years old "finally: # Actionprint" goodbye! "

(3) class and inheriting class B (A) is the template that creates the instance, and the instance is a concrete object, each instance has data that is independent of each other , and the method is the function that binds to the instance, unlike the normal function, Method can directly access the data of the instance, by invoking the method on the instance, we manipulate the data inside the object directly, but do not need to know the implementation details inside the method.

(4) Package mechanism
Each of the. py files is called a module,module that can be imported between each other. See the example below:
# a.py
Def Add_func (A, B):
Return a+b
# b.py
From a import Add_func # Also can be:import a
Print "Import Add_func from Module a"
Print "Result of 1 plus 2 is:"
Print Add_func # If using "Import a", then here should is "A.add_func"

Two: practical examples

# encoding:utf-8#!/usr/bin/pythonimport Reclass parent:parentattr = 100;# overload def __init__ (self):p rint "Call parent class constructor NStruct ". Decode (" Utf-8 "). Encode (" GBK "); #成员函数def Parentmethod (self):p rint" Invoke parent class member function: Parent method ";d EF setAttr (self , attr):P arent.parentattr = Attr;def getAttr (SEF):p rint "Parent class Property: Parentattr:", Parent.parentattr;def __del__ (self):p rint "Parent descontruct"; class child (Parent): # defines the subclass Def __init__ (self):p rint "Call subclass constructor Method Child construct" Def childmethod (self  ):p rint ' Call the subclass method of child methods ' Def __del__ (self):p rint "Children destructor"; c = Child () # Instantiate Subclass C.childmethod () # Call the Subclass Method C.parentmethod () # Call the parent class method C.setattr (200) # Call the parent class again method c.getattr () lines = "Zyp,0001,nan\r\nxqz,0002,nan\r\ Nwzx,0003,nv "; line =" Cats is smarter than dogs "; matchobj = Re.match (R ' (. *), ', lines, re. M|re. I) If Matchobj:print "ddd", Matchobj.group (); Else:print "No match!!"; Lists = Lines.split (', \\r\\n ');p rint "lists:", Lists;for Li in Lists:print li; #print li, "\ n";p rint "*********just for TESt****** "; try:filer = open (' Splits.txt ', ' R ');d one = 0;while not done:f_str = Filer.readline (); if (f_str! ="): Eles = F_str . Split (', '); #print "Eles:", eles;for ele in Eles:print ele;else:done = 1;except ioerror:print "error:can\ ' t find this file" ; Filer.close ();p rint "*********just for test******"; try:filer = open (' Splits.txt ', ' R '); f_lines = Filer.readlines (); For f_lines:eles = Line.split (', '); for ele in Eles:print ele;except ioerror:print "error:can\ ' t find this file"; fi Ler.close ();
Description: This example illustrates the class inheritance of Python, as well as exception handling, and the read task of the file
three: Easy to make mistakes

(1) Common error 1: Use expression as default in function arguments
Python allows you to set a default value for a parameter of a function so that the parameter becomes an optional parameter. While this is a great feature of the language, it's a bit of a hassle when the default is a Mutable object (mutable). For example, look at the following Python function definition:
def foo (bar=[]): # Bar is an optional parameter, if not specified, the default value is []
Bar.append ("Mky"); # But there's a problem with this line, and I'll see ...
return bar;
Print foo ()
Print foo ()


The answer is the default value of a function parameter, which is assigned only once when the function is defined. Thus, the default value of the parameter bar is initialized to its default value (that is, an empty list) only if the function foo () is defined for the first time. When you call Foo () (without giving the parameter bar), you will continue to use the same list as the bar's earliest initialization.

(2) local variables (due to assignment and variable not being declared) in the Use list (lists). Look at this example:
>>> lst = [1, 2, 3]
>>> def foo1 ():
...     Lst.append (5)   # There's no problem ... br> ...
>>> foo1 ()
>>> lst
[1, 2, 3, 5]
>>> lst = [1, 2, 3]
>>> def foo2 ():
...     LST + = [5]      # ... That's a problem!
...
>>> Foo2 ()
Traceback (most recent call last):
  File <stdin>, line 1, in <module>  File "<stdin>", Line 2, in foo
unboundlocalerror:local variable ' LST ' referenced before assignment
Yes ? Why Foo2 have problems, and foo1 no problem? The
answer foo1 does not assign a value to LST, but Foo2 attempts to assign a value to LST. Note that lst+=[5] is shorthand for lst=lst+[5], so you can see that we're trying to assign a value to LST (so Python assumes the scope is local). However, the value to be assigned to LST is based on the LST itself (where the scope is still local), and the LST is not defined, which makes a mistake.

(3) Naming conflicts with Python standard library modules
A good place for Python is that it provides a rich library module. But the result is that if you don't subconsciously avoid it, it's easy for you to run into situations where your own module name conflicts with the name of a standard library that comes with Python (for example, you might have a module called email.py in your code that conflicts with a module with the same name in the standard library).
This can lead to some very rough questions, such as when you want to load a library, the library needs to load a module in the Python standard library, as a result, because you have a module with the same name as the module in the standard library, the package incorrectly loads your module, not the module in the Python standard library. Then there will be trouble.
So be careful when giving the module a name, and avoid the same names as the modules in the Python standard library. It's much easier to re-name your module than to ask for a "Python enhancement Proposal (PEP)" To change the name of a standard library package, and get approved.

(4) version issue, difference between 2.X and 3.X, here are two good learning python sites

10 common error Http://www.csdn.net/article/2014-05-12/2819716-Top-10-Mistakes-that-Python-Programmers-Make for Python programmers

http://www.yiibai.com/python/python_gui_programming.html---python GUI tools
Http://www.liaoxuefeng.com/wiki/001374738125095c955c1e6d8bb493182103fac9270762a000/ 00141861202544241651579c69d4399a9aa135afef28c44000python Tutorials

Basic Python Tutorials and error-prone (text processing)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.