Python basic Syntax (iv)

Source: Internet
Author: User

Python basic Syntax (iv)

--------------------------------------------the basic syntax of Python (iii)--------------------------------------------

Ten, Python standard library

The Python standard library is installed with Pthon and contains a number of extremely useful modules.

1. SYS module SYS module contains system-corresponding functions

    • SYS.ARGV---contains command-line arguments, the first parameter is the file name of the PY
    • Sys.platform---return platform type
    • Sys.exit ([status])---Exit program, optional status (range: 0-127): 0 indicates normal exit, other means abnormal, can throw exception event for capture
    • Sys.path---Program the corresponding file must be placed in the Sys.path contained directory, using Sys.path.append to add their own module path
    • Sys.modules---This is a dictionary, maps module names to modules which has already been loaded
    • Sys.stdin,sys.stdout,sys.stderr---Contains stream objects that correspond to standard I/O streams
s = Sys.stdin.readline ()

Sys.stdout.write (s)

2. OS Module This module contains common operating system functions

    • The Os.name string indicates the platform you are using. For example, for Windows, it's ' NT ', and for Linux/unix users, it's ' POSIX '
    • The OS.GETCWD () function gets the current working directory, which is the directory path of the current Python script work
    • The Os.getenv () and os.putenv () functions are used to read and set environment variables respectively
    • Os.listdir () returns all file and directory names under the specified directory
    • The Os.remove () function is used to delete a file
    • The Os.system () function is used to run shell commands
    • The OS.LINESEP string gives the line terminator used by the current platform. For example, Windows uses ' \ r \ n ', Linux uses ' \ n ' and Mac uses ' \ R '
    • OS.SEP operating system-specific path delimiters
    • The Os.path.split () function returns the directory name and file name of a path
    • The Os.path.isfile () and Os.path.isdir () functions respectively verify that the given path is a file or a directory
    • The Os.path.existe () function is used to verify that the given path really exists

Xi. Other

1. A number of special methods

name Description
__init__ (self,...) This method is called before the new object is returned to use.
__del__ (self) Called exactly before the object is to be deleted.
__str__ (self) printcalled when we use a statement or use it on str() an object.
__lt__ (Self,other) Called when the less-than operator (<) is used. Similarly, there are special methods for all operators (+,>, and so on).
__getitem__ (Self,key) x[key]called when the index operator is used.
__len__ (self) Called when the built-in function is used on a Sequence object len() .

The methods in the previous table are defined in the following class:

Class Array:
__list = []

def __init__ (self):
Print "Constructor"

def __del__ (self):
Print "destructor"

def __str__ (self):
Return "This self-defined array class"

def __getitem__ (self, key):
return Self.__list[key]

def __len__ (self):
Return Len (self.__list)

def Add (self, value):
Self.__list.append (value)

def Remove (self, Index):
Del Self.__list[index]

def displayitems (self):
Print "Show all items----"
For item in Self.__list:
Print Item

arr = Array () #constructor
Print arr #this self-defined Array class
Print Len (arr) #0
Arr. ADD (1)
Arr. ADD (2)
Arr. ADD (3)
Print Len (arr) #3
Print Arr[0] #1
Arr. Displayitems ()
#show All items----
#1
#2
#3
Arr. Remove (1)
Arr. Displayitems ()
#show All items----
#1
#3
#destructor

2. Comprehensive list

With list synthesis, you can export a new list from an existing list.

List1 = [1, 2, 3, 4, 5]
List2 = [i*2 for i in List1 if I > 3]

Print List1 #[1, 2, 3, 4, 5]
Print List2 #[8, 10]

3. function receive tuple/list/dictionary

When a function receives a tuple or dictionary-like parameter, there is a special way to use the * and * * prefixes. This method is particularly useful when a function needs to obtain a variable number of arguments.

Because there is a * prefix before the args variable, all the extra function arguments are stored as a tuple in args. If you are using a * * prefix, the extra arguments are considered a dictionary

Key/value pairs.

def powersum (Power, *args):
Total = 0
For i in args:
Total + = POW (i, Power)
Return Total

Print Powersum (2, 1, 2, 3)

def displaydic (**args):
For Key,value in Args.items ():
Print "key:%s;value:%s"% (key, value)


Displaydic (a= "One", b= "one", c= "three")
#key: A;value:one
#key: C;value:three
#key: B;value:two

4. Lambda

Lambda statements are used to create new function objects and return them at run time. Lambda requires a parameter, followed only by a single expression as the body of the function, and the value of the expression is

The new function returns. Note that even the print statement cannot be used in lambda form, only expressions are used.

Func = Lambda S:s * 3
Print func ("Peter") #peter Peter Peter

Func2 = lambda A, b:a * b
Print Func2 (2, 3) #6

5. Exec/eval

The EXEC statement is used to execute a python statement stored in a string or file, and the eval statement is used to calculate a valid python expression stored in a string.

cmd = "print ' Hello World '"
exec cmd #hello world

expression = "10 * 2 + 5"
Print eval (expression) #25

6. Assert

An Assert statement is used to assert that a condition is true and to throw an error when it is not true AssertionError .

Flag = True

Assert flag = = True

Try
Assert flag = = False
Except Assertionerror, err:
Print "Failed"
Else
Print "Pass"

7. repr function

The REPR function is used to obtain the canonical string representation of an object. The inverse quotation marks (also known as converters) can accomplish the same function.

Note that most of the time there is an eval (repr (object)) = = object.

You can control what the object returns when it is called by the REPR function by defining the __repr__ method of the class.

arr = [1, 2, 3]
print ' arr ' #[1, 2, 3]
Print repr (arr) #[1, 2, 3]

12. Practice

Implement an address book, the main functions: Add, delete, update, query, display all contacts.

1 Import Cpickle
2 Import OS
3 Import sys
4
5 Class Contact:
6 def __init__ (self, name, phone, mail):
7 Self.name = Name
8 Self.phone = Phone
9 self.mail = Mail
10
One def Update (self, name, phone, mail):
Self.name = Name
Self.phone = Phone
self.mail = Mail
15
def display (self):
+ print "name:%s, phone:%s, mail:%s"% (Self.name, Self.phone, Self.mail)
18
19
# BEGIN
21st
# file to store contact data
data = OS.GETCWD () + os.sep + "Contacts.data"
24
While True:
Print "-----------------------------------------------------------------------"
Operation = raw_input ("Input your operation (add/delete/modify/search/all/exit):")
28
if operation = = "Exit":
Sys.exit ()
31
If Os.path.exists (data):
If os.path.getsize (data) = = 0:
contacts = {}
+ Else:
+ F = file (data)
PNS contacts = Cpickle.load (f)
F.close ()
$ Else:
contacts = {}
41
if operation = = "Add":
Flag = False
While True:
* Name = raw_input ("Input name (exit to back choose operation):")
If name = = "Exit":
Flag = True
Break
If name in Contacts:
Print "The name already exists, please input another or input ' exit ' to back choose operation"
Wuyi Continue
If else:
Phone = raw_input ("Input phone:")
Wu mail = raw_input ("Input mail:")
c = Contact (name, phone, mail)
Contacts[name] = C
f = file (data, "w")
Cpickle.dump (Contacts, F)
F.close ()
Print "Add successfully."
Break
elif operation = = "Delete":
Raw_input name = ("Input the name that is want to delete:")
If name in Contacts:
Del Contacts[name]
$ f = file (data, "w")
Cpickle.dump (Contacts, F)
F.close ()
Print "Delete successfully."
+ Else:
Print "There is no person named%s"% name
elif operation = = "Modify":
While True:
* * * name = raw_input ("Input the name which to update ' or exit to back choose Operation:")
If name = = "Exit":
Break
The "If not" name in Contacts:
Print "There is no person named%s"% name
Continue
else:
Bayi phone = raw_input ("Input phone:")
Raw_input mail = ("Input mail:")
Contacts[name]. Update (name, phone, mail)
f = file (data, "w")
Cpickle.dump (Contacts, F)
F.close ()
Print "Modify successfully."
Break
elif operation = = "Search":
* Name = raw_input ("Input the name which you want to search:")
If name in Contacts:
Contacts[name].display ()
Who else:
94 print "There is no person named%s"% name
elif operation = = "All":
"For name", contact in Contacts.items ():
Contact.display ()
98 Else:
Print "Unknown operation"

-----------------------------------------------------End-----------------------------------------------------

Python basic Syntax (iv)

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.