Python's path to growth-the next day

Source: Internet
Author: User
Tags throw exception

CPYTHON:C interpreter. PYC (byte code)--Machine code Jpython:java interpreter Java bytecode ironpython:c# interpreter C # bytecode .... Above: After compiling is the bytecode PyPy: their own interpreter of the bytecode machine code compiled directly machine code directly run machine code fast similar to Java "Python Source Code Anatomy" code: #-*-coding:utf-8-*-8-bit: 2**8=256 --unicode (Universal Code) compression of at least 16-bit--utf-8:unicode (different types of digits) Utf-8:ascii: Numbers, letters, characters--8 bits Europe: 2 bytes Kanji: 3 bytes Single-line Comment: Single quote Multiline note Release: double quotes Python executes with a buffer pool in Python, and a pool of memory space is maintained in memory to cache common data data types: | The evil connector (+): Each connection will open up a new memory space (the original memory space program will not be deleted, the interpreter has a recycling mechanism, Found that no one calls this memory space will be reclaimed) Eg:a=b+c+d will open up 3 memory spaces | String formatting: Python is a master file for Python, everything is an object, and objects are created based on class, objects of the same type are created by the same class, and the functions of the objects are the same, and their function sets are stored in the class that created the object   s = "dd" s = str (' dd ') L1 = [1,2,3]L1 = List ("Three-way")   is to create the object first--re-call method   (1) int:   __abs__      abs   __add__      +    __divmod__     generate quotient and remainder   for pagination    __rdivmod__   plus R for the divisor and divisor substitution    __EQ __   __ge__   __gt__ python in the source code includes: C write the source code and Python write the source code so look at the Python source, see the method below did not write codes, write is pass  (2) Str: type (object name)   Object class Dir (object name)     object class and Member of Class  __contains__   contains equivalent to in>>>  ("Zhangyan"). __contains__ ("Yan") true>>>  "Yan"  in  "Zhangyan" true capitalize       First letter lowercase to uppercase >>>  ("admin"). Capitalize () ' admin '  casefold         All letters uppercase to lowercase  center (num, padding string)   Character Center  num is length  >>>  ("admin"). Center (A, '-') '------- Admin--------'  count (to count characters, start with the first few characters, end with the first few characters)   count the number of occurrences of characters >>>  ("ASDFgfdertyeru "). Count (" F ", 0,9) 2 encode (' GBK ')   encode to Gbk endswith (the trailing character, starting with the first character, to the end of the first few characters) to determine whether to end with a string    expandtabs ()   Converts the TAB key (\ t) to 8 spaces  find (characters) find characters   cannot find a return -1index (character) find character   cannot find an error   Format   string concatenation   same + formatted string >>> name= "{0} like {1}" >>> result= Name.format ("Zhangjie", "Zhangyan") >>> result ' Zhangjie like zhangyan '   ' delimiter '. Join ( To stitch the characters)   used to do stitching  partition (split flag string)   split string  replice (' A ', ' C ') a all converted to c rjust   right-aligned split     Specify character split string  with   connection context tuple (tuple): Tuple last element to add,countindex  dictionary (dict) dic1 = {' K1 ': ' v1 ', ' K2 ': ' V2 '}dic1 = dict (k1= ' v1 ', k2= ' v2 ')  dic1.get (' K1 ')   with Dic1 (' K1 ')   different if key does not exist the latter will error, the former will return null

Format character

The format character reserves the location for the real value and controls the format of the display. A format character can contain a type code that controls the type of display, as follows:

%s string (shown with STR ())

%r string (shown with repr ())

%c single character

%b binary integers

%d decimal integers

%i Decimal Integer

%o Eight-binary integers

%x hexadecimal integer

%e index (base written as E)

%E index (base written as E)

%f floating Point

%F floating-point number, same as above

%g index (e) or floating point number (depending on display length)

%G Index (E) or floating point number (depending on display length)

Percent% character "%"

The format can be further controlled in the following ways:

%[(name)][flags][width]. [Precision]typecode

(name) is named

Flags can have +,-, ' or 0. + Indicates right alignment. -Indicates left alignment. ' is a space that fills a space on the left side of a positive number to align with a negative number. 0 means using 0 padding.

Width indicates display widths

Precision indicates the precision after the decimal point

Summary of use of global variables:
    1. intrinsic function, global variable can be accessed without modifying global variables
    2. An intrinsic function that modifies a global variable with the same name, Python considers it to be a local variable
    3. The Unbound-localerror is raised when an intrinsic function modifies a global variable with the same name before calling the variable names (such as print sum)
The sum set in the program is a global variable, and there is no definition of sum in the function, and the rules for accessing local variables and global variables are based on Python: When searching for a variable, Python first searches from the local scope, and if the variable is not found in the local scope, Python then looks for the variable in the global variable, if it can't find the throw exception (Nameerror or Unbound-localerror, depending on the Python version.) )

If the intrinsic function has a variable or global variable that references an external function, and the variable is modified. Then Python will consider it a local variable, and because there is no definition and assignment of sum in the function, an error is given. When you encounter a global variable accessed in a program and you want to modify the value of a global variable, you can use: Globalkeyword, in functionDeclare this variable to be a global variable eg:
if __name__ = = ' __main__ ':
Bal=0 #我的钱 (self-defined)
Settle_accounts ()
Def settle_accounts ():
Global Bal
Global money
If Bal > Money:
Bal-=money
Print "Congratulations on your successful purchase! Your consumption is:%d your balance is:%d "% (money,balance)
  strings, tuples, lists, dictionaries between conversions # #, dictionary dict = {' name ':  ' Zara ',  ' Age ': 7,  ' class ':  ' First '}  #字典转为字符串, returns:<type  ' str ' > {' age ': 7,  ' name ':  ' Zara ',  ' class ':   ' first '}print type (str (dict)),  str (dict)   #字典可以转为元组, return: (' age ',  ' name ',  ' class ') Print tuple (dict) #字典可以转为元组, return: (7,  ' Zara ',  ' first ') Print tuple (Dict.values ())   #字典转为列表, return: [' age ',  ' name ',  ' class ']print list (dict) #字典转为列表print  dict.values  #2, tuple tup= (1,  2, 3, 4, 5)   #元组转为字符串, return: (1, 2, 3, 4, 5) print tup.__str__ ()   #元组转为列表, return: [1, 2, 3, 4, 5]print list (Tup) #元组不可以转为字典   #3, List nums=[1, 3,  5, 7, 8, 13, 20];  #列表转为字符串, return: [1, 3, 5, 7, 8, 13,  20]print str (nums)   #列表转为元组, return: (1,&NBSP;3,&NBSP;5,&NBSP;7,&NBSP;8,&NBSP;13,&NBSP;20) print  Tuple (nums)   #列表不可以转为Dictionary   #4, string   #字符串转为元组, return: (1, 2, 3) Print tuple (eval ("())") #字符串转为列表, return: [1, 2,  3]print list ("()") #字符串转为字典, returns:<type  ' Dict ' >print type (eval ("{' Name ': ' LJQ ',  ' age ': 24} ')

open/file Operations

F=open ('/tmp/hello ', ' W ')

#open (path + file name, read-write mode)

#读写模式: R read-only, r+ read/write, W New (overwrites the original file), a append, b binary. Common mode

such as: ' RB ', ' WB ', ' r+b ' and so on

The types of read-write modes are:

RU or Ua opens in read-only mode with universal line-feed support (PEP 278)
W opens in write mode,
A opens in Append mode (starting with EOF and creating a new file if necessary)
R+ Open in read-write mode
w+ Open in read/write mode (see W)
A + opens in read/write mode (see a)
RB opens in binary read mode
WB opens in binary write mode (see W)
AB opens in binary append mode (see a)
Rb+ opens in binary read/write mode (see r+)
Wb+ opens in binary read/write mode (see w+)
Ab+ opens in binary read/write mode (see A +)


Attention:

1, use ' W ', if the file exists, first to empty, and then (re) create,

2, using the ' a ' mode, all the data to be written to the file is appended to the end of the file, even if you use Seek () to point to the file somewhere else, if the file does not exist, it will be created automatically.



F.read ([size]) size unspecified returns the entire file if the file size >2 memory is problematic. F.read () returns "" (empty string)

File.readline () returns a row

File.readline ([size]) returns a list that contains a size row, and returns all rows if size is unspecified

for lines in F:print line #通过迭代器访问

F.write (" Hello\n ") #如果要写入字符串以外的数据, first convert him to a string.

F.tell () returns an integer that represents the position of the current file pointer (that is, the number of bits to the file header).

F.seek (offset, [start position])

To move the file pointer

Offset: unit: bit, can be negative

Start position: 0-header, default; 1-current position; 2-end of file

F.close () Close file

Code:


#!/usr/bin/env python
# Filename:using_file.py

Poem= ' \programming is funwhen the work is doneif you wanna make your work also fun:use python! ' '
F=file (' Poem.txt ', ' W ') # Open for ' W ' riting
F.write (poem) # Write text to file
F.close () # Close the file
F=file (' Poem.txt ')

# If no mode is specified, ' R ' ead mode was assumed by default
While True:
Line=f.readline ()
If Len (line) ==0: # Zero length indicates EOF
Break
Print line,
# Notice comma to avoid automatic newline added by Python
F.close ()
# Close the file

Python's path to growth-the next day

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.