This article is dedicated to the small whites who are still on the basis of Python 0! It's not a problem to make sure you get started

Source: Internet
Author: User
Tags arithmetic arithmetic operators bitwise bitwise operators case statement shallow copy string format

More cases please follow my blog: home.cnblogs.com/u/python1234

Welcome to join thousands of people Exchange resource sharing group: 125240963

    • It means there's nothing.

    • If the function does not return a value, you can return none

    • Used to occupy a position

Third, built-in data structure

    • List

    • Set

    • Dict

    • Tuple

List (lists)

# 1, create empty list L1 =

[]

# 2. Create a list with values L2 = [100

]

# 3. Create a list with multiple values L3 = [2, 3, 1, 4, 6, 4, 6

]

# 4. Use list () L4 = List ()

    • # Create a list B with List A # The meaning of the following code is that for all elements in a, put in the new list B = [I * Ten for I in

      A

      # can also filter the contents of the original list of the disease into a new listing # such as the original list A, you need to have all the even number of a new list B a = [x for x in range (1, 35)] # Generate a list from 1 to 34 # to generate a new list of all even numbers in a (b b) = [M for m in a if m% 2 = =

      0]

      # list generation can be nested # by two List A, a = [I for I in range (1, 4)] # Generate List A b = [I for I in range] if I% 100 = =

      0]

      # list generation is nested, at this time equal to two for loop nesting c = [M + N for M in a for n

      b

      # The above code is equivalent to the following code for the M in

      A:

      For N in

      B:

      Print (M + N, end = ""

      )

      # Nested lists the city can also be used with conditional expressions C = [M + N for M in a for n in b if M + N < 250]

  • Common functions for lists

    • Copy: Copy, this function is a shallow copy

      b = A.copy ()

    • Count: Find the number of values or elements specified in the list

      A_len = A.count (8)

    • Extend: List of extensions, two lists, put a straight stitch on the back one

      A = [1, 2, 3, 4, 5

      ]

      B

      = [6, 7, 8, 9, 10

      ]

      A.extend (b)

    • Remove: Removes the element of the specified value from the list (if the deleted value is not in the list, an error is given)

    • Clear: Clear

    • Reverse: Flip List contents, flip in place

      A = [1, 2, 3, 4, 5

      ]

      A.reverse ()

    • Del Delete

    • Pop, take an element from the bitwise, i.e. take the last element out

      Last_ele = A.pop ()

    • Insert: Make position insertion

      # Insert (index, data), insertion position is index front A.insert (3, 666)

    • Append insert a content, append at the end

      A = [I for I in range (1, 5

      )]

      A.append (

      100)

    • Min

    • List: converting data from other formats into a list

      # Convert content from range to list print (list (12, 19))

    • Max: Find the maximum value in the list

      b = [' Man ', ' film ', ' Python '

      ]

      Print (max (b))

    • Len: Find list length

      A = [x for x in range (1, 100

      )]

      Print (Len (a))

Tuple (tuple)

# Create an empty tuple t =

()

# Create a tuple with only one value T = (1

,)

T

= 1

,

# Create multiple values for tuple t = (1, 2, 3, 4, 5

)

T

= 1, 2, 3, 4, 5 # Use other structures to create L = [1, 2, 3, 4, 5

]

T

= Tuple (L)

Properties of tuples

    • is a sequence table, ordered

    • Tuple data values can be accessed and cannot be modified

    • The tuple data can be any type

    • List all features, in addition to modifiable, tuples have

Functions of tuples

    • Len: Gets the length of the tuple

    • Max, min: Maximum minimum value

    • Count: Calculate the number of occurrences of the development data

    • Index: Find the indexed position of the element in the tuple

Set (SET)

# Definition of the collection s =

Set ()

# at this point, be sure to have a value in the curly braces, otherwise define a dict s = {1, 2, 3, 4, 5, 6, 7

}

# If you just define with braces, you define a dict type D = {}

Characteristics of the collection

    • Data is unordered within the collection, i.e. indexes and shards cannot be used

    • Collection internal data elements are unique and can be used to exclude duplicate data

    • Data within the collection, str, int, float, tuple, frozen set, etc., where only hashed data can be placed inside

Collection sequence Operations

    • Member detection (In,not in)

    • Traverse

# for loop s = {4, 5, "I"

}

For I in

S

Print (I, end = "")

)

# with tuples set traversal s = {(1, 2, 3), ("Just", "for", "Fun"), (4, 5, 6

)}

For K,m,n in

S

Print (k, "--", M, "--"

, N)

For K in

S

Print (k)

The connotation of the collection

# Common Set Connotation # The following collection automatically filters out duplicate elements after initialization s = {23, 223, 545, 3, 1, 2, 3, 4, 3, 2, 3, 1, 2, 4, 3

}

# Normal Set Connotation SS = {I for I in

S

# conditional Set Connotation SSS = {I for I in S if i% 2 = =

0}

# multi-loop Set connotation S1 = {1, 2, 3, 4

}

S2

= {"Just", "for", "fun"

}

S

= {m * n for m in S2-N in

S1}

S

= {m * n for m in S2-N in s1 if n = = 2}

Aggregate functions

    • Len, Max, Min

    • Set: Generate a Collection

    • Add: Adding elements to the collection

    • Clear

    • Copy

    • Remove: Remove the established value, directly change the original value, if the value to be deleted does not exist, an error

    • Discard: Removes the specified value from the collection, as with remove, but does not give an error if the stake is to be deleted

    • Pop randomly removes an element

    • Function

    • Intersection: Intersection

    • Difference: Difference Set

    • Union: and set

    • Issubset: Checks if a collection is another subset

    • Issuperset: Checks if a collection is another superset

    • # Create S = Frozenset ()

Dict (dictionary)

    • No sequential combination of data, data appearing as key-value pairs

      # Creation of Dictionary # Create empty dictionary 1 d =

      {}

      # Create an empty dictionary 2 d =

      Dict ()

      # Create a dictionary with values, each set of data separated by a colon, each pair of key-value pairs separated by commas d = {"One": 1, "one": 2, "three": 3

      }

      # Create a content dictionary with dict 1 d = dict ({"One": 1, "": 2, "three": 3

      })

      # Create a content dictionary with dict 2 # using the keyword parameter d = dict (one = 1, 2, three = 3

      )

      # d = dict (["One", 1), ("One", 2), ("Three", 3)])

The characteristics of a dictionary

    • A dictionary is a sequence type, but an unordered sequence, so there are no shards and indexes

    • Each of the data in the dictionary consists of a key-value pair, which is the KV pair

      • Key: Must be a hash value, such as Int,string,float,tuple, but list,set,dict not

      • Value: Any value

Common dictionary Operations

# Access Data D = {"One": 1, "one": 2, "three": 3

}

# Note Access format # inside the brackets is the key value print (d["one"

])

d[

"One"] = "eins" # Delete an action # using the Del operation del d[

]

# member detection, in, no in # member detection detected is key content d = {"One": 1, "one": 2, "three": 3

}

If 2 in

D:

Print ("Value"

)

If "both" in

D:

Print ("Key"

)

if ("both", 2) in

D:

Print ("KV"

)

# Press Key to use for loop D = {"One": 1, "one": 2, "three": 3

}

# Use a For loop to access the for-K in directly by the key value

D:

Print

(k, D[k])

# The above code can be rewritten as follows for the K in

D.keys ():

Print

(k, D[k])

# access only the value of the dictionary for the V in

D.values ():

Print

(v)

# Note the following special usages for the k,v in

D.items ():

Print (k, '--', V)

Dictionary-generated

D = {"One": 1, "one": 2, "three": 3

}

# General Dictionary-generated DD = {k:v for k,v in

D.items ()}

# conditional Dictionary Generation DD = {k:v for k,v in D.items () if v% 2 = = 0}

Dictionary-related functions

    • Len, Max, Min, dict

    • STR (dictionary): Returns the string format of a dictionary

    • Clear: Empty the dictionary

    • Items: Returns the tuple format of the dictionary's key-value pairs

    • Keys: Returns a structure that consists of a dictionary key

    • Values: In the same vein, an iterative structure

    • Get: Returns the corresponding value according to the key set

      D = {"One": 1, "one": 2, "three": 3

      }

      Print (D.get ("on333"

      ))

      # get default value is None, can set print (D.get ("one", 100))

    • Fromkeys: Uses the specified sequence as the key, using a value as the value of all keys of the dictionary

      L = ["Eins", "Zwei", "Drei"

      ]

      # note Fromkeys two parameters of type # Note Fromkeys's call body D = Dict.fromkeys (L, "oops")

Iv. expressions

Operator

    • Arithmetic operators

    • Comparison or relational operators

    • Assignment operators

    • logical operators

    • Bit arithmetic

    • Member operations

    • Identity operator

Arithmetic operators

    • Plus +

    • Reduction

    • By

    • Remove

    • Residual%

    • Pick-up (floor except)//

    • Power Operation * *

    • : Warning:python no self-increment decrement operator

Comparison operators

    • ==

    • !=

    • >=

    • <=

    • The result of the comparison is a Boolean value (True/false)

Assignment operators

    • + = (-=,x=,/=,//=,%=, **=)

logical operators

    • and Logic and

    • or logical OR

    • Not logical non-

    • The result is False if 0, otherwise true

    • Short circuit

    • No XOR or arithmetic in Python

Member Operation symbols

    • Used to detect whether a variable is a member of another variable

    • Inch

    • Not in

Identity operations

    • is: Used to detect whether two variables are the same variable

    • is not: Two variables are not of the same variable

Precedence of Operators

    • Parentheses have the highest precedence

      * * Index (highest priority)

      ~ +-Rollover by bit

      ,

      Unary Plus and minus (the last two methods are called [email protected] and [email protected])

      */%//multiply, divide, modulo and divide

      +-Addition Subtraction

      \>> << Right SHIFT, left shift operator

      & Bit ' and '

      ^ | Bitwise operators

      <

      = < > > =

      Comparison operators

      <>

      == ! =

      equals operator

      = % = / = // = - = + = * = ** =

      Assignment operators

      Is isn't identity operator

      In no in member operator

      Not OR and logical operators

V. Structure of the procedure

Order

Branch

    • Basic syntax

      # The colon after the expression must not be less # indented to represent the same code block if

      Conditional expression:

      Statement 1

      Statement 2

      Statement 3

      ..

    • Two-Way Branch

      # if and else one level, the rest of the statement one level if

      Conditional expression:

      Statement 1

      Statement 2

      Else

      :

      Statement 1

      Statement 2

    • Multi-Channel Branch

      If

      Conditional expression:

      Statement 1

      .

      Elif

      Conditional expression:

      Statement 1

      Elif

      Conditional expression:

      Statement 1

      ..

      Else

      :

      Statement 1

      .

    • Python does not have a switch-case statement

Cycle

For loop

For variable in

Sequence:

Statement 1

Statement 2

Range

    • Generate a sequence of numbers

    • Range: [M,n]

      # Print 1~10 for I in range (1, 11

      ):

      Print (i)

For-else

    • When the For loop finishes, the Else statement is executed

    • Else Statement Optional

While loop

While

Conditional expression:

Statement block

# Another way of expression while

Conditional expression:

Statement Block 1

Else

Statement Block 2

Break,continue,pass of the Cycle

    • Break: Unconditionally end the entire cycle, referred to as circular death

    • Continue: Unconditional end of this cycle, new into the next round cycle

    • Pass: Indicates skip, usually used for positioning, no skip function

Vi. functions

    • def keyword

    • Code indentation

      # define Def

      Func ():

      Print ("This is a function"

      )

      # call Func ()

Parameters and return values for functions

    • Parameters: Responsible for passing some necessary data or information to the function

      • Formal parameters (formal parameter): The parameters used in the function definition have no specific value, just a placeholder symbol, become the formal parameter

      • Argument (actual parameter): The value entered when the function is called

    • Return value: The result of the function's execution

      • Use the return keyword

      • If there is no return, a none is returned by default

      • Once a function executes a return statement, it returns unconditionally, that is, the execution of the End function

        # return statement Basic use # function after the greeting returns a sentence def

        Hello (person):

        Print ("{0}, are you swollen?")

        . Format (person)

        Print ("Sir, you go without a forehead.")

        )

        Return "I have greeted {0}, {1} ignore me"

        . format (person, person)

        P

        = "Bright Moon" rst =

        Hello (P)

        Print (RST)

# define a function to print a row of 99 multiplication table def

PrintLine (ROW):

For Col in range (1, row + 1

):

# Print function The default task prints and wraps the print (row * col, end = ""

)

Print (""

)

# 99 Multiplication Table # version 2.0 for row in range (1, 10

):

PrintLine (Row)

Detailed parameters

    • Parameter classification

      • General parameters

      • Default parameters

      • Keyword parameters

      • Collect parameters

    • General parameters

      • See the example above

      • Define the variable name directly at the time of definition

      • Put a variable or value directly into the specified position when calling

        def function name (parameter 1, parameter 2,

        .):

        function body

        # Call the function name (value1, value2,

        .)

    • Default parameters

      • Formal parameters with default values

      • When called, the default value is used if no value is assigned to the corresponding parameter

        def func_name (p1 = v1, p2 = v2

        .):

        Func_block

        # call 1

        Func_name ()

        # call 2 value1 = value2 = Func_name (value1,value2)

    • Keyword parameters

      def func (p1 = v1, p2 = v2

      ..):

      Func_body

      # Call Function: Func (p1 = value1, p2 = value2

      .)

    • Collect parameters

      • Put in a specific data structure the parameters that have no location and cannot be defined with the parameter position.

        def func (*

        args):

        Func_body

        # access to args by list usage gets the parameters passed in # Call: Func (P1, p2, p3,

        ..)

Collection of parameter mixed call order issues

    • Collect parameters, keyword parameters, common parameters can be mixed use

    • The rule of use is that common parameters and keyword parameters take precedence

    • When defining general parameters, keyword parameters, collect parameter tuple, collect parameters Dict

return value

    • The difference between a function and a procedure

      • There are no return values

    • You need to return the content with return,

    • If no return is returned, none is returned by default

Recursive functions

    • Python has a limit on recursion depth, exceeding the limit error

      # Fibonacci Number # A list of numbers, the first value is 1, the second is also 1, and the value of each number is equal to the value of the first two digits and the # mathematical formula is: f (1) = 1, f (2) = 1, f (n) = f (n-1) + f (n-2) # for example: , 2,3,5,8,13 ..... # n denotes the value of the Fibonacci sequence of the nth number of digits Def

      FIB (n):

      if n = = 1

      :

      return 1 if n = = 2

      :

      Return 1 return fib (n-1) + fib (n-2

      )

      Print (FIB (3

      ))

      Print (FIB (10))

    • Hanoi Tower Problem

      • Rules:

      • Method:

    1. N=1: Move a plate on a to C directly, a->c

    2. n=2:

    3. N=3:

    4. n = N:

    1. Put the small plate from A to B, A->b.

    2. Put the big plate from A to C, A->c.

    3. Put the small plate from B to C, B->c.

    1. Put two plates on a, move through C to B, call recursive implementation

    2. Move the largest remaining plate on a to C, A->c.

    3. Put two plates on B, move to c with the aid of a, call recursion

    1. N-1 a plate on a, with the help of C, move to B, call recursion

    2. Put the biggest plate on a, and the only one, move to C, a->c

    3. N-1 a plate on B, move to c with the aid of a, call recursion

    1. Move one plate at a time

    2. At any time the big plates are down, the small plates are on top.

Def

Hano (n, a, B, c):

‘‘‘

Recursive implementation of Hanoi

N: Representing several plates

A: stands for the first tower, the beginning of the tower

B: A tower representing the second tower, the middle transition

C: On behalf of the third tower, the target tower

"If n = = 1

:

Print (A, "--"

C

Return

None

‘‘‘

if n = = 2:

Print (A, "--", b)

Print (A, "--", c)

Print (b, "--", c)

Return None

"# N-1 a plate, from tower A to the tower C, move to Tower B Hano (n-1

, A, C, b)

Print (A, "--"

C

# N-1 a plate, from Tower B, with a tower, move to Tower C Hano (n-1, B, A, c)

A = "a" b = "B" c = "c" n = 1

Hano (n, a, B, c)

N

= 2

Hano (n, a, B, c)

N

= 3 Hano (n, a, B, c)

find function Help documentation

    • Use the Help function

      Help (print)

    • Using __doc__

      Def

      Stu (name, age):

      ‘‘‘

      This is the textual content of the document

      :p Aram Name: Indicates the student's name

      :p Aram Age: Indicates the student's ages

      : return: This function has no value returned

      "Pass Print

      (Help (Stu))

      Print ("*" * 20

      )

      Print (stu. __doc__)

Vii. Scope of variables

    • Category: By scope

      • Global: Defined outside the function

      • Partial (local): Defined inside a function

    • LEGB Principles

      • L (local) local scope

      • E (enclosing function locale) outer nested functions Scope

      • The module scope where the G (Global module) function is defined

      • B (Buildin): Python built-in scope for magic

Promote local variables to global variables (using global)

Def

Fun ():

Global

B1

B1

= Print

(B1)

Print ("I AM in Fun"

)

# B2 's scope is fun b2 = Print

(B2)

Fun ()

Print (B1)

Globals, locals function

    • Local and global variables can be displayed through globals and locals

      # Globals and locals # Globals and locals are called built-in functions a = 1 b = 2 def

      Fun (c,d):

      E

      = 111 Print ("locals={0}"

      . Format (Locals ()))

      Print ("globals={0}"

      . Format (Globals ()))

      Fun

      100, 200)

Eval () function

    • Executes a string as an expression, returning the result of the execution of the expression

      Eval (string_code, globals = none, locals = none)

EXEC () function

Similar to the Eval function, but does not return results

EXEC (String_code, globals = none, locals = none)

This article is dedicated to the small whites who are still on the basis of Python 0! It's not a problem to make sure you get started

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.