001 Part I [Python basics]

Source: Internet
Author: User

I. Python basics

    • Data type

Primitive type: int float byte compound type: A type combined by another primitive type list dict cuple
    • Operators and Expressions:

Arithmetic operators:         plus  /  minus  /  multiply  /  except  /  Modulus  /  power  /  floor removal         +    -     *    /     %      **     //python2    except: 10 / float (20) Bitwise operators [binary Operations]:bin (60)   Convert binary number int (' 1100 ', 2)     convert binary to decimal &    bitwise AND           is 1  only for 1    |    bitwise OR         exists 1  that is 1^    bitwise XOR or           the same as 0, different for 1~     bitwise counter           positive complement, the inverse code is itself                   negative complement is: sign bit unchanged, the rest of you seek counter, the bottom plus 1  Both 11111&NBSP;&NBSP;&NBSP;&NBSP;&Nbsp;            Anti-code is: The sign bit is 1, the rest of you seek counter, but the bottom does not add 1                   Suppose there is a number ~ 9, the calculation steps are as follows,9=1001                  Its complement is 01001,                  Counter 10110, this number is stored in memory, now need to replace the original code, minus 1, and then take the inverse                   11010, the sign bit is 1 negative, both -10<<   left >>   right Shift
    • Bitwise inverse:

---positive complement and anti-code are its own, but the front to add a positive sign bit   "0"---negative sign bit is "1" negative complement is: sign bit unchanged, the rest of you seek counter, the bottom plus 1 negative anti-code is: sign bit unchanged, The rest of you. Negation---binary number is stored in the form of complement in memory---60 bitwise inverse calculation:     The first step:     calculate the  [complement of 60)   and  [anti-code]:                  Original code    complement    anti-code          decimal  60          Binary  111100  0111100 0111100     Step two :     counter-action is to reverse the complement]:                          complement                                                    1000011                                  Anti-code                                    complement  - 1                                  1000010                  Original Code                                   1111101                 1  Rep is negative                                  111101  Convert Decimal to 61                                 -61
    • comparison operator [return Boolean type]

= = equals = = is not equal to > greater than < less than
    • logical operators

And with true is Trueor or as long as true is the short-circuit function of the truenot non-negation logic operation: The front false is no longer calculated: 1+2 >4 and (+) = = 4 Front is true does not Will recalculate back: 1+2 <4 or (+ 3) = =
def add (x, y): print ("%d +%d"% (x, y)) return X+yadd (1, 2) > 4 and Add (2, 3) = = 5 ...: 1 + 2out[2]: False
def add (x, y): print ("%d +%d"% (x, y)) return X+yadd (1, 2) < 4 and add (2,3) < 6 ...: 1 + 3True
def add (x, y): print ("%d +%d"% (x, y)) return X+yadd (1, 2) < 4 and add (2,3) < 4 ...: 1 + 3False
    • Other operators

= assignment operator in member operator not in member operator is identity operator, compares the IDs of two elements; The list cannot be compared with IS, the IS-not identity operator is used by the environment often to judge whether it is none;
    • Expressions and Precedence

1. One yuan is higher than two Yuan 2. The value is higher than logic 3. The arithmetic operation is higher than the bitwise Operation 4. Multiplication is above plus minus 5. In doubt, add parentheses.
    • Program Structure

1.   sequential structure 2.   branching structure 3.   loop structure There is no switch structure in relation to  switchpython, because the ' switch ' structure can be fully represented by the ' if '  elif else ' statement to implement the switch implementation method: Rough version: #coding:utf8   #add  minus divide using  python  from __future__ import division  x=1  y=2   Operator= '/'   result={   ' + ':x+y,   '-":x-y,  " * ":x*y,  "/": x/ Y  }  print (Result.get (operator))           Improved version :#!/usr/bin/env python# -*- encoding:utf-8 -*-class calculate:     def __init__ (self, x, op, y):         self.x  = x        self.op = op         self.y = y   def count (self):         result={         "+":self.x+self.y,          "-":self.x-self.y,         "*":self.x*self.y,          "/": Self.x/self.y}        print ( Result.get (Self.op)) mark = calculate ("+", 2) Mark.count ()

Python ternary operations

A = 4b = a If a > 0 else 0
    • Range function

Range (x) [0,x) range (m, n) [M, N) range (m, n, s) [M,n], step s
    • Break clause

* Can only appear in the loop structure * for jumping out of the current loop structure
    • Continue clause

* Can only appear in the loop structure * used to skip the remaining actions of this iteration

ELSE clause

The ELSE clause of the loop structure is unique to Python, which indicates that a loop does not break out of the loop, prematurely ends the loop, but exits normally, before the statement in else is executed;

Two. Built-in container:

    • List

* list is the most commonly used linear data structure * list is an ordered combination of a series of elements * list is a mutable list of operations: Definition list: li = []li = list () li &NBSP;=&NBSP;[1,&NBSP;2,&NBSP;3] View Help document: Add: Append, extend, insert Delete:clear, pop,  Remove: Reverse, sort: Count, index Other: Copy add: Li = []append: Only one One increase li.append (3) Extend: Extended Li.extend ([5,6,7]) Li[3, 5, 6, 7]insert: position before inserting Li.insert (0, 0)   Insert 0 before the first delete: clear: Clear list Li.clear () Remove: Deletes the specified element from the left, if the deleted element does not exist will be an error valueerrorli.remove (3)    Delete element 3pop: Delete the specified location element: If not present will error Indexerrorli.pop ()      Delete last element Li.pop (3)     Delete key is 3 element modified: Reverse: Reverse list order: Sort: From small to large:     only for simple numeric sort sort (reverse=true)   from big to small sort: check: Count: Show number of matching elements li.count (3) Other: Index (3): Returns the position of the specified element in the list, if it does not exist Valueerror:index (Value, [start, [stop])  copy:  deep Copy, Will generate a new list         assignment is a shallow copy, shallow copy of the data changes will affect the original list; Subscript operation: li[1]li[1] =  10 Slice:li[3:5]:   Front is closed interval &NBSP;&NBSP, followed by an open interval li[3:]li[:]   effect is the same as copy, and the efficiency will be faster than copy;li[:4] li[4:-2]      Cut to the penultimate one, followed by an open interval li[-4:-1]li[2:6:2]:  start, stop&nbsp, and a step li[6:2:-1]  start,stop  Reverse display, step 1li[6:2:-2]  start,stop, reverse display, step length is 2li[::-1]li[::2]
    • tuples [tuple]

Tuple and list most places similar to tuple are immutable structure tuple can only get value definition one tuple: t = () T = tuple () Count: Count Elements Index: Returns the position of the specified element in the tuple subscript operation [get value]:t[1 by subscript ]
    • PACKING & Unpacking

PACKING: Change the value of multiple variables into a tuple or list, by default it becomes a tuple unpacking: You can also assign a tuple or list to multiple variables
X, *y = (1, 2, 3, 4) print (x) 1print (y) [2, 3, 4]
*x, y = (1, 2, 3, 4) print (x) [1, 2, 3]print (y) 4
*_ This expression is assigned to a variable that cannot be used: x, *_, y = (1, 2, 3, 4) print (x) 1print (y) 4
x, (y, Z) = (1, (2, 3)) print (x) 1print (y) 2print (z) 3
    • Collection

The meaning of the set and the meaning of the mathematically set are the same set of elements that are not linear structures *  The collection element is the only set element that is a hash of the set of operations: Initialize: S = set () S = set ([1, 2, &NBSP;3]) Increased: S.add (3)                      //Add an element s.update ([3, 4, 5, 6])        //Collection add more than one element in the list delete:remove:      remove, delete the element that does not exist throws an exception;discard:     Delete, delete non-existent element does not throw exception;clear:       empty pop:          Randomly deletes a collection of elements in a collection operation:union                     Collection                a | bintersection              Intersection               a &  bdifference               differential set, non-exchangeable     a -      a ^ b set judgment of the difference of the  bsymmetric_difference     set [ Returns a Boolean]:issubset     subset issuperset   superset Isdisjoint
    • Dictionary

* Dictionary is an unordered collection * Dictionary is a KV structure * value can be any object * key is unique * key must be an operation of a hash object dictionary: D = dict () d = {' A ': 5, ' B ': 4}d[' a ']d.keys () dict_keys ([' B ', ' a ']) Traverse key:for key in D.keys (): Print (D[key]) traversal value:for value in D.values (): print (value) traverses key and Value:for key, Value in D.iterms (): print ('%s =%s '% (key, value)) D.iterkeys () returns a generator; Pop,popitem To delete the element D.pop (' key ') need to specify key, delete the nonexistent value return Keyerrord.pop (' key ', 6) Delete the nonexistent value will return 6 increase the dictionary element: d[' c '] = 7


This article from "Technical Side dishes" blog, declined reprint!

001 The first part [Python Basics]

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.