Python Basics Summary

Source: Internet
Author: User
Tags assert iterable shallow copy variable scope

Python Basic user input

Username = input (' Please enter user name: ')

What the hell is PYC?

Python, like Java and C #, is a virtual machine-based language, and when we use Python Hello.py, is to tell the virtual machine I want to start work, the virtual machine before the explanation, the first job is to compile, the results of the compilation is stored in the memory of the Pycodeobject, when the Python program is finished, the Python interpreter will pycodeobject write back to the PYc file, when the PY Thon Program second run, the first program will be on the hard drive to find the PYc file, if found, Judge the last modification time of the. pyc file and. py file First, if the. pyc file is modified later than the. py file, the source code in the. py file has not been modified, then directly loaded, otherwise the above procedure is repeated, so we should be able to locate the Pycodeobject and PYc files, we say PYC text is a persistent way to save Pycodeobject.
# # #三元运算符
result = ' Yes ' if username = = ' kernel ' Else ' no '

Python data type
  • String

    cannot be changed
    Str.capitalize () First uppercase
    Str.casefold () uppercase all lowercase
    Str.upper () converted to uppercase letters
    Str.lower () Convert to lowercase
    str.swapcase () Case reversal
    Str.title () capitalize the first letter of each word
    Str.center (index: total length, str: character before and after padding) content centered
    Str.encode () encodes a string into buytes format
    stt.count (' kernel ') statistics kernel the number of occurrences in a string
    Str.endswith (' kernel ') Determines whether the string ends with kernel
    ' kernel\t '. Expandtabs (index) output kernel, convert \ t to how long spaces

  • List

    The list is one of the most commonly used data types in the future, and the list allows for the most convenient storage, modification and other operations of the data.
    Definition List
    names = [' Tom ', ' Amy ', ' Jack ']
    Slice
    Names[1:3] Gets the value of subscript 1-3, including 1, not including 3
    Names[:3] From the beginning to take
    NAMES[::2] The step size of the slice
    Names[:-1] Gets the last value
    Additional
    Names.append (' Dawei ')
    Insert
    Names.insert (2, ' Dawei ')
    Delete
    Names.pop () Delete last element
    Names.remove (' Amy ') deletes an element of the specified value
    Del names[1] Delete the element on the specified index
    Modify
    NAMES[1] = ' lack '
    Extended
    Number = [+/-]
    Names.extend (number)
    names=[' Tom ', ' Amy ', ' Jack ', 1, 2, 3]
    Copy
    Names_copy = Names.copy ()
    Only the first-level list of nested lists can be copied, if you want to copy nested lists using the Copy module's deepcopy ()
    Statistics
    Names.count (' Tom ')
    Sort & Flip
    Names.sort ()
    Names.reverse ()
    Get subscript
    Names.index (' Tom ')

  • Meta-group

    Tuples once created, cannot be changed, also called read-only lists
    Define a meta-ancestor
    Names = (' Tom ', ' Jack ', ' Amy ')
    Statistics
    Names.count (' Tom ')
    Get subscript
    Names.index (' Tom ')

  • Dictionary

    Dictionary a key-value data type, used like a dictionary we used to go to school, check the details of the corresponding page by strokes, letters, unordered and the key is unique
    Definition dictionary
    info = {
    ' stu1101 ' : "Tom",
    ' stu1102 ': "Amy",
    ' stu1103 ': "Jack",
    Add
    info[' stu1104 '] = ' Dawei '
    Delete
    del info[' stu1101 ']
    Info.pop (' stu1101 ')
    Info.popitem () randomly delete
    Modify
    info[' stu1101 '] = ' Lanlan '
    Find
    Info.get (' stu1101 ') If there is a return value, if there is no return-1
    info["stu1104"] if there is a return value, if there is no error
    other
    info.values ()
    Info.keys ()
    Info.setdefault (" Stu1104 "," Dawei ")
    Info.item ()

  • Collection

    A collection is an unordered, non-repeating combination of data, deduplication, relationships
    Defining collections
    s = set ([1,2,3,4])
    t = set (' Hello ')
    Intersection
    B = S |t
    S.union (t)
    and set
    b = t & S
    S.intersection (t)
    Complement set
    b = T-S
    S.difference (t)
    Subtraction
    b = t ^ s
    S.symmetric_difference (t)
    Add to
    T.add (' h ')
    T.update ([i])
    Delete
    T.remove (' h ')
    Other
    X in T to determine if X is in the set T
    X not in T to determine if X is no longer in the collection T
    S.issubset (t) determine if S is a subset of T
    S.issuperset (t) determine if T is S's own
    S.copy () Shallow copy

File
  • Open a file,

    f = open (' filename ', ' r ') need to close the file manually
    Auto close file with open (' filename ', ' r ')
    R Read-only
    W write only, empty the data first, write
    X if file exists, error, if not present, create and write data
    A append
    b Binary Mode Open
    (+) readable and writable

  • Manipulating files

    F.read () Read all data
    F.seek (0) adjusting the cursor position
    F.tell () Tell where the current pointer is (in bytes)
    F.write (") writes data
    F.flush () Flush buffer
    F.fileno () file descriptor
    F.readable () to determine whether it is readable
    F.readline () reads a line
    F.truncate () empties the data behind the cursor

  • Close File

    F.close ()

    Function
  • Defined

    def xxx ():

  • function body

    def xxx ():
    Pass

  • return value

    return value, or none if no return is specified

  • Parameters

    普通参数def information(anem,age):passinformation(‘kernel‘,21)指定参数def infoemation(name,age):    pass information(name = ‘kernel’,age = 21) 默认参数 def infoemation(name,age,addr = ‘山东’):     pass information(‘kernel’,21)动态参数 def infoemation(*args,**kargs):   pass
  • Variable scope

    A variable declared inside a function is called a local variable, and a variable declared outside the function body is called a global variable
    The life cycle of a local variable is the end of the function body, and the lifetime of the global variable is the program end

  • Global variables

    Global variable scope is the entire program, when local variables with the same name as global variables, local variables work, if you want to use global variables, you need to declare global full name variable name

  • Recursive

    Must have a definite end condition

    Each time you enter a deeper level of recursion, the problem size should be reduced compared to the last recursion

    Recursive efficiency is not high, too many recursion levels will cause stack overflow

    data = [1, 3, 6, 7, 9, 12, 14, 16, 17, 18, 20, 21, 22, 23, 30, 32, 33, 35]def binary_search(dataset,find_num):if len(dataset) >1:mid = int(len(dataset)/2)if dataset[mid] == find_num:  #find itprint("找到数字",dataset[mid])elif dataset[mid] > find_num :# 找的数在mid左面print("\033[31;1m找的数在mid[%s]左面\033[0m" % dataset[mid])return binary_search(dataset[0:mid], find_num)else:# 找的数在mid右面print("\033[32;1m找的数在mid[%s]右面\033[0m" % dataset[mid])return binary_search(dataset[mid+1:],find_num)else:if dataset[0] == find_num:  #find itprint("找到数字啦",dataset[0])else:print("没的分了,要找的数字[%s]不在列表里" % find_num)binary_search(data,66)
  • anonymous functions

    f = Lambda a,b:a+b
    result = f (2,3)

  • Built-in functions

    ABS () absolute value
    The all () parameter is a data type that can be iterated, and if it is true, returns True
    Any () Ditto, there is a true is true
    Bin () receives decimal, converted to binary
    Oct () receives decimal, converts to octal
    Hex () Receives decimal, converts to hexadecimal
    Bytes () Receives string and encoding type, converts to bytes
    STR () Receives string and encoding type, converted to string
    Callable () detects if a function can be called
    Chr () converts an integral type to a character
    Ord () converts a character to an integer type
    Compile () compiles a string into Python code
    EXEC () executes Python code
    Eval () turns a string into an expression and executes
    Help () to see assistance
    Divmod () returns a Ganso that contains the quotient and remainder
    Isintance () Determines whether an object is an instance of a class
    Issubclass () determines whether a class is a subclass of a class
    Filter () receives a function and an iterative object that iterates over the object and executes the function, returning true to add the element to the result
    Map () receives a function and an iterative object that iterates over the object and executes the function, adding the function return value to the result
    Zip () receives multiple lists, combining elements from multiple lists at the same location into one tuple

Object oriented

(Object oriented Programming,oop, OOP) classifies and encapsulates functions, which need to be implemented using "classes" and "objects", so object-oriented programming is actually the use of "classes" and "objects"

  • A class is a template that can contain multiple functions and functions in a template.
  • Object objects are instances created from templates that can execute functions in a class through an instance object
  • Encapsulation encapsulates attributes into a class so that an object can invoke properties
  • Inherited

    • A single-inheritance subclass can inherit the properties and functions of a parent class
    • Multiple inheritance

      ‘‘‘TEST继承C和GC继承B,B继承A,A存在方法f1,A继承X,X存在f2G继承F,E继承F,F存在方法f1,F继承X,X存在f2TEST类的对象调用A类的f1,所以先从左边找到顶层,如果左边顶层有,就调用左边顶层的f1,如果没有去右边找TEST类的对象调用X类的发,如果左边右边的顶层拥有共同的父类,先从左边开始找,一直找到A类,再从右边开始找,最后调用X类的f2‘‘‘class X:  def f2(self):      print(‘OK‘)class A(X):  def f1(self):      print(‘A‘)class B(A):  passclass C(B):  passclass E(X):  def f1(self):      print(‘E‘)class F(E):  passclass G(F):  passclass Test(C,G):  def test(self):      self.f1()t = Test()t.test()
  • Members

    • Field

      • The normal field belongs to the field of the object, and each object holds a copy of the
      • A static field belongs to a field of a class, and only one copy is saved
    • Method

        class Foo: @staticmethod def static_fun (): Print (' static method, called by class ') @classmethod def clas_fun (CLS): Print (' class method, called by class ') def fun: print (' normal method, call by object ')  
      • The normal method is called by an object, has at least one self parameter, and when the method is executed, the object's arguments are automatically Called by a class by passing a
      • static method, which can have no parameters
      • class method called by the class, with at least one CLS parameter, which automatically passes the class name when the method is specified
    • The @property property adds an adorner on the basis of a normal method, and when defined, requires only a self parameter, and when called, no need to add ()

      方式一:class Foo: def __init__(self,value):     self.value = value @property def price(self):     return self.value @price.setter def price(self,value):     self.value = value     print(‘设置属性‘) @price.deleter def price(self):     print(‘删除属性‘)     del self.valuef = Foo(100)print(f.price)f.price = 200print(f.price)del f.priceprint(f.value)方式二:class Foo: def __init__(self,value):     self.value = value def get_price(self):     return self.value def set_price(self,value):     self.value = value     print(‘设置属性‘) def del_price(self):     print(‘删除属性‘)     del self.value price = property(get_price,set_price,del_price)f = Foo(100)print(f.price)f.price = 200print(f.price)del f.priceprint(f.value)
  • Member modifiers

    • Public members can be accessed from anywhere
    • The naming convention for private member private members is preceded by a name of ____
  • Super keyword
    > Forcing method members of the parent class to be called
    Super (subclass, self). F1 ()

  • Special members

    • Doc represents the description of the class
    • module represents the object of the current operation in that module
    • class indicates what the object of the current operation is
    • init construction method, which automatically triggers execution when an object is created from a class
    • del destructor, which automatically triggers execution when the object is freed in memory
    • The Call object is appended with parentheses to trigger execution
    • Dict All members of a class or object
    • When str prints an object, the return value of the method is entered by default
    • getitem result = obj[' K1 '], result = obj[-1:1], automatic execution of the method
    • setitem obj[' k1 '] = 123, obj[1:4] = [11,22,33,44], automatic execution of the method
    • delitem del obj[' K1 ', del Obj[1:4], automatically executes this method
    • iter is used for iterators where lists, dictionaries, and tuples can be for loops because the type internally defines the ITER
    • Metaclass is used to indicate who created the class by whom it was instantiated
Iterators

An object that can be called by the next () function and constantly returns the next value is called an iterator, and the generator is a iterator object, but list, dict, and Str are iterable, but not iterator, which lists, Dict, STR and other iterable become iterator can use the ITER () function

Generator

Create a list of 1 million elements, if only a few previous elements, then the space occupied by the elements behind is wasted, in Python, there is an edge loop, the edge of the calculation of the following elements of the mechanism to become a generator, the generator is an object with the ability to create data

Decorative Device

Name of @+ function
Function:
Automatically executes the outer function and passes f as a parameter
Re-assign the return value of the outer function to F

def outer(func):def inner(*args,**kwargs):print(‘before‘)ret = func(*args,**kwargs)print(‘after‘)return retreturn inner@outerdef f(msg):print(msg)    f(‘kernel!‘)
Reflection

To manipulate members in a module using the form of a string
Hasattr () receives an object and a string member name if the returned ture is found and returns false if not found
GetAttr () receives an object and a string member name if the returned member is found, if there is no error
SetAttr () receives an object and a string member name, and sets the member
Delattr () receives an object and a string member name, and returns true if the deletion succeeds

Abnormal
    • Exception Base
        while True:try:print (int (input (' NUM1: ')) +int (Input (' num2: '))) except Exception as E:print ( e)  
    • Common exceptions

      Attributeerror attempts to access a tree that does not have an object, such as foo.x, but Foo has no attribute x
      IOError input/ Output exception, basically cannot open the file
      Importerror cannot introduce a module or package; is basically a path problem or name error
      Indentationerror syntax error (subclass); Code is not aligned correctly
      Indexerror The subscript index exceeds the sequence boundary, for example, when X has only three elements, but attempts to access X[5]
      Keyerror attempts to access a key that does not exist in the dictionary
      Keyboardinterrupt CTRL + C is pressed
      Nameerror Using a variable that is not yet assigned to the object
      SyntaxError python code is illegal, the code cannot be compiled (personally, it is a syntax error, is wrong)
      TypeError The Incoming object type does not conform to the requirement
      Unboundlocalerror Attempting to access a local variable that is not yet set, basically because there is another global variable with the same name,
      causes you to think that you are accessing it
      ValueError passing in a value that the caller does not expect, even if the type of the value is correct

    • Other structures of exceptions
        try:# The main code block passexcept keyerror,e:# exception, execute the block passelse:# the main block executes, execute the block passfinally:# whether it is abnormal or not, Final execution of the block pass  
    • Active Trigger exception
        try:raise Exception (' active trigger ') except Exception,e:print e  
    • assert

      Assert condition

To import a module using the form of a string

obj = Import(' manager ')
obj = import(' Lib.manager ') can only be imported to Lib by default
obj = import(' Lib.manager ', formlist=true) that allows the module name to be used for stitching

Special variables in Python
    • Documentation comments for doc py files
    • cached path to the PYc file of the import module
    • The path where file is currently running files
    • package file belongs to which packet
    • name only the name of the current file = = ' main '

Python Basics Summary

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.