Python knowledge (1)

Source: Internet
Author: User

1,Variables in Python do not have the concept of type.

For example, to create a list

Movies = ["hello", "Python", "Haha"] # create a list print (LEN (movies) # print the movies length movies. Pop ("Python ")


2,Determines whether a variable is of the list type.

M = ['A', ['B', ['C', 'D','E']]]for x in M:    if isinstance(x, list):       for y in x:           if isinstance(y, list):               for z in y:                   print(z)           else:               print(y)    else:       print(x)



3,Define and use functions 

M = ['A', ['B', ['C', 'D', 'E'] def PR (): # define the function PR for X in A: Print (X)


Pr (m) # Call the function PR

4. String is an unchangeable variable.
In python, once a string is created, it cannot be changed.
S = 'hellopython'
S = S. Strip ()# Remove the white spaces at the beginning and end of S.

In addition, tuple is also an immutable variable, and all numeric variables are also immutable.

5. variables do not really own data
Pythonvariables contain a reference to data object which contains thedata.

6. Several built-in functions

  • Range (n): returns an integer between 0 and N-1
  • List ()
  • Enumerate ()
  • INT ()
  • ID ()
  • Next () 


The namespace of the built-in functions (build-in functions, BIF) is _ builtins __
The following program prints 5 A consecutively on the screen:
For I inrange (5 ):
Print ('A', end = '')

7. Display and change the current directory and read the content of the specified file

Import osprint (OS. getcwd () # obtain the current directory OS. chdir ('.. ') # Jump to the previous directory print (OS. getcwd () file into open('test.txt ') # open the file test.txt print (file. readline (), end = '') # Read a print (file. readline (), end = '') # The read row contains the final \ nprint (file. readline (), end = '') file. seek (0) # Return to the starting position of the file ''' to read each line of text in the file and output ''' for line in file: Print (line ,'') # \ n at the end of each line will be output, but no additional line feed file will be added for print. close ()



8. Split string

STR = 'hello, world, hello, python' for X in Str. split (','): Print (x, end = ':') # output Hello: World: Hello: pythonfor X in Str. split (',', 1): Print (x, end = ':') # output Hello: World, hello, pythonfor X in Str. split (',', 2): Print (x, end = ':') # output Hello: World: Hello, python for X in Str. split (',', 3): Print (x, end = ':) # output Hello: World: Hello: Python


If the string to be split is empty, an error will occur. You can use find to detect

data = open('test.txt')for x in data:    if x.find(',') != -1 :        print(s.split(','))

You can also change the statement
If not X. Find (',') =-1:

9. Exception Handling

Try: Data = open('test.txt ') for line in data: Try: Print (line. split (',') failed t valueerror: pass # Skip data directly. close () exceptioerror: Print ('file does not exist ')

 

Valueerror: A valueerror occurs when your data does notconform to the expected format
Ioerror: An ioerror occurs when your data can not beaccessed properly

9. Locate the exception type

Try: file = open ("misssing.txt") # The file (missing.txt) does not actually have print (file. readline (), end = '') failed T: Print ('file does not exist') Finally: file. close () # An exception is reported: nameerror: Name 'file' is not defined.


This is because the file missing.txt does not exist. Therefore, open ("missing.txt") throws an exception and the file does not exist. To fix this bug, you can test whether the file exists before closing the file, as shown in figure

... Finally: If 'file' in locales (): # note that the quotation marks here must be file. Close ()

TheLocalesBIF returns a collection of names defined in thecurrent scope.

When an exception is raised and handled by yourExceptSuite, the python interpreter passesException objectInto thesuite.

try:    file = open("misssing.txt")    print(file.readline(), end='')except IOError as err:    print('file does not exist : ' + str(err))    print(err)finally:    if 'file' in locals():        file.close()

Output:

File does not exist: [errno 2] No such file or dir
[Errno 2] No such file or directory: 'misssing.txt'


Here, bif str converts err to a string.


10. Use with to process file-related operations

In the preceding example, the opened files are explicitly closed. Using the With keyword can simplify these operations.

try:with open('man.txt', 'w') as man:print('this is man', file=man)with open('other.txt', 'a') as other:print('this is other', file=other)except IOError:print('file does not exist')

By using the with and as keywords, we do not need to manually close the open file (python will automatically close the file, even if an exception occurs ). In python, this technology is called context management protocol.

The preceding example can also be written

try:with open('man.txt', 'w') as man, open('other.txt', 'a') as other:print('this is man', file=man)print('this is other', file=other)except IOError:print('file does not exist')



11. Use pickle to save and read data

Pickle is a standard Python library that can be used to store and read data in any format, similar to the serialization mechanism in Java.

Import pickle # the pickle module must be imported with open('man.txt ', 'wb') as man: # The file pickle must be opened in binary mode. dump ([1, 2, 3, ['A', 'B', 'C'], man) with open('man.txt ', 'rb') as man: A = pickle. load (man) print ()

The running result is

[1, 2, 3, ['A', 'B', 'C']




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.