Improve your Python code (7) __python

Source: Internet
Author: User
1. Avoid a finally trap

Look back at the last section of the chart we drew:

Let's take a look at this code

Def finallytest ():
    print (' I am starting------') while
    True:
        try:
            print (' I am running ')
            raise Indexerror (' R ')
        except Nameerror as E:
            print (' Nameerror happend {e} '. Format (e=e))
            break
        finally:
            print (' finally executed ')   The break # finally statement has a break statement

if __name__ = = ' __main__ ':
    Finallytest () ""
"output:
I am starting------
I am running
finally executed
" "

Def returntest (a):
    try:
        if a <= 0:
            raise valueerror (' data cannot is negtive ')
        else: return
            A
    except ValueError as E:
        print ("ValueError:", E)
    finally:
        print ("The end!")
        Return-1

If __name__ = = ' __main__ ':
    print (returntest (0))
    print (Returntest (2)) ""
output:
Valueerror:data cannot be negtive
The end!
-1 the
end!
-1 "" "

2. None of this stuff

# To determine if list is empty
list = []

if list is none:                # Wrong way
    print (' list is none ')
else:
    print ("list is" Not none '


if list:                        # The correct way to
    print (' list is not none ')
else:
    print ("list is none")

""
output: Not none of the list is None ""
"

3. The connection string is preferred to join rather than +

Reason:

STR1, str2, STR3, STR4, STR5 = ' my ', ' heart ', ' 'll ', ' go ', ' on '
combine_str = '. Join ([str1, str2, STR3, STR4, STR5])
print (COMBINE_STR) ""
output:
myheartwillgoon
"" "

4. Use format instead of%






Weather = [' A ', ' B ', ' C ']
formatter = ' letter are: {0} '. Format
for item in map (formatter, weather):
    print (item) ""
output: letter
is:a Letter
is:b Letter
Is:c


5. Distinguish between mutable objects and immutable objects

Class Student (object): Def __init__ (self, name, course=[]): # Here's a warning: Default argument value is mutable self.  Name = Name Self.course = Course # def __init__ (self, Name, Course=none): # This is a change to the previous code # Self.name =


    Name # If course is None: # self.course = [] # else: # Self.course = Course def addcourse (self,coursename): Self.course.append (Coursename) def printcoursename (self): print ("Stu Dent {Self.name} ' s course are: ". Format (self=self)) for item in Self.course:print (item) liming = Stu
Dent (' Liming ') liming.addcourse ("Math") liming.printcoursename () David = Student (' David ') David.addcourse ("Art") David.printcoursename () Print (ID (liming), "|", ID (David) print (ID (liming.name), "|", ID (david.name)) Print (ID ( liming.course), "|", ID (david.course)) "" "Output1:student liming ' s course are:math student David ' s course are:math Ar T 2168438350288 | 2168438350456 2168438237256 | 2168438328040 2168438334024 | 2168438334024 output2:student liming ' s course are:math student David ' s course are:art 1946024173976 | 1946024174144 1946024061000 | 1946024151784 1946024178760 | 1946024157768 "" "

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.