A simple introduction to the python foundation tutorial that explains the of variable and how to use the control language

  • 2020-04-02 13:30:32
  • OfStack

Introduction to the
If you're interested, take a look: interpreted language + dynamically typed language + strongly typed language

Interactive mode :(mainly to experiment, you can try ipython)


$python
>>> print 'hello world'

The script


#!/usr/bin/env python
print 'hello world'


Environment:

Python2.7 + easy_install + PIP + virtualenv + ipython is recommended

The indentation
Python functions have no obvious begin and end, and no curly braces to indicate the beginning and end of a function. The only delimiter is a colon (:), followed by the indentation of the code itself.

Example:


# function 
def func(value):
    print value  # The indentation 
    if value == 1:
        value += 1
    elif value == 2:
        pass
    else:
        value += 10

identifier
Variables are examples of identifiers. An identifier is a name used to identify something. Here are some rules to follow when naming identifiers:

1. Identifiers in python are case sensitive.

2. The identifier begins with a letter or an underscore. It may include letters, underscores, and Numbers

3. Identifiers that begin with an underscore have special meaning.

The class attribute that starts with a single underscore (_foo) cannot be accessed directly should be accessed through the interface provided by the class, and cannot be imported by "from XXX import *".
S (s) that start with a double underscore represent private members of the class;
(foo) that starts and ends with a double underscore represents an identity specific to a particular method in python, such as init (), which represents the constructor of the class.

4. Identifiers cannot be reserved words


and            elif        global   or    yield
assert         else        if       pass
break          except      import   print
class          exec        in       raise
continue       finally     is       return
def            for         lambda   try
del            from        not      while

variable

Assignment statement

1. The assignment statement establishes the object reference value
2. Variable names are created when first assigned
3, the variable name must be assigned before the reference, can not refer to the undeclared value of the variable


Assignment way

Simple assignment
Variable =Value


s =  ' spam'

Multivariate assignment

The original tuples and list assignment statements in python are formed and eventually generalized to accept that the right side can be any type of sequence, as long as the length is the same. Notice, the lengths must be the same
Variable1, variable2,... = Value1, Value2,...


s,h =  ' a','b'   Tuple assignment, positional    "Common" 
[s,h] =[ ' a','b']  List assignment, positional 
a,b,c,d =  ' spam'  Sequence assignment, universal 
a,*b =  ' spam'  Extended sequence unpacking ( python3 ) 

Multiple target assignment


a=b=variable
s = h =  ' spam'  Multiple target assignment 

Note: multiple variables point to the same object in memory. For mutable types, modifying one can affect the others

Since the variable assignment


 Such as += . -= . *= And so on. 

In the auto-variable assignment, python computes only once, while the normal notation computes twice.

Instead of creating a new object, auto-assign modifies the original object.


s +=42  Strengthen the assignment 
x += y

Advantages:


 The left side only needs to calculate once, the optimization technology is automatically modified in place, faster 
l +=[]  Place to modify 
l = l+[]  Copy to generate a new object 

The operator
An expression can be decomposed into operators and operands

The function of operators is to accomplish something, and they are represented by symbols such as + or other specific keywords

Operators require data to perform operations, and such data is called operands

Operator priority list (from highest to lowest)


 The operator     describe 
'expr'   String conversion 
{key:expr,...}   The dictionary 
[expr1,expr2...]     The list of 
(expr1,expr2,...)    tuples 
function(expr,...)   A function call 
x[index:index]   slice 
x[index]     Index value 
x.attribute  Attribute references 
~x   According to the not 
+x . -x  Positive and negative 
x**y     power 
x*y . x/y . x%y  Multiply, divide and take the modulus 
x+y . x-y    Add and subtract 
x<<y . x>>y  shift 
x&y  Bitwise and 
x^y  The bitwise exclusive or 
x|y  Bitwise or 
x<y . x<=y . x==y . x!=y . x>=y . x>y    To compare 
x is y . x is not y  Equivalent test 
x in y . x not in y  Members of the judgment 
not x    Logical not 
x and y  Logic and 
x or y   Logic or 
lambda arg,...:expr Lambda Anonymous functions 

Combined with regular

Operators are usually combined from left to right, that is, operators with the same priority are evaluated from left to right

Calculate the order

By default, the operator priority table determines which operator is evaluated before the others. However, if you want to change the order of their calculations, you have to use parentheses. Good practice: parenthesis complex operations by default, rather than relying on default binding and order of computation

The true value
True test

1. Any non-zero number or non-empty object is true
2. The number zero, empty object and special object None are false
Comparison and equality tests are recursively applied to data structures
4. Comparison and equality tests return True or False


Truth table


 object / constant     value 
""   false 
"string"     true     
0    false 
2>=1     true 
-2<=-1   true 
() An empty tuple   false 
[] An empty list   false 
{} An empty dictionary   false 
None     false 

Boolean expression
Three Boolean expression operators


x and y
x or y
not x

To compare
Numbers are compared by relative size
Strings are compared character by character in lexicographical order
Lists and tuples compare the contents of each section from left to right
Dictionaries are compared by a sorted list of keys and values
Numeric hybrid type comparisons are incorrect in python3, but python2.6 supports a fixed but arbitrary collation

Boolean number
There are two values True and False that never change
A Boolean is a subclass of an integer but cannot be subinherited
The default value for an object without a nonzero() method is True
For any number or empty set with a value of 0, the value False
In mathematical operations, the True and False values of Bollean correspond to 1 and 0, respectively
Basic control flow

The if
A basic conditional test statement used to determine different situations that may be encountered and to act on them

Basic form


if < conditions >:
   < statements >
elif < conditions >:
   < statements >
else:
   < statements >

Pay attention to

Python determines by indentation that the elif and else sections are optional

Example:


a = 1
b = 2
c = 3;d=4 # The two are separated by a semicolon, but branch is recommended 
if a < b and c < d:
    print("branch a")
elif a == b:
    print("branch b")
else:
    print("branch c")
switch

Python itself does not have a switch statement, so if necessary, the if/elif/else implementation does the same thing, and in some cases a dictionary might be considered

You can also use dict

If /else ternary operator


A = ((X and Y) or Z)
A = Y  if X else Z
 Ex. :  a =  ' t' if x else  ' a'
[code]
for
 The basic grammar 
 Loop control statement that can be used to loop through a sequence 
else Block optional, executed when the loop terminates, if break Terminate the loop, else Does not perform 
 Format: 
[code]
for < Object variables > in < A collection of objects >:
    if< conditions >:
       break
    if< conditions >:
       continue
    < Other statements >
else:
    < Other statements >

Note:

1. Object collections can be lists, dictionaries, tuples, etc
2. The for... The in loop works for any sequence
When traversing a dictionary, the keys of the dictionary are traversed


rang & xrange

You can complete the counting loop by generating a list of integers through the range() function


range([start,] stop[, step])

Start optional parameter, starting number
Stop terminating number, if x, produces a list of integers from 0-(x-1)
Step optional, step size, unwritten default is 1
Range (1,5) contains the sequence [1,2,3,4]

Xrange is different from range

(invisible in python3.x)

In the Range method, it will generate a list of objects, but in the XRange, it will generate an XRange object, when the return of things is not very large, or in a loop, basically is to check to the bottom of the case, the efficiency of the two methods is about the same. However, it is recommended to use XRange when the return is large, or if the loop is often broken out, to save space and improve efficiency.


>>> print range(1, 5)
[1, 2, 3, 4]
>>> print xrange(1, 5)
xrange(1, 5)

In the above statement, range returns a normal List, and xrange returns an object of a specific xrange type. Because the xrange method also creates a list of integers (which USES the same parameters), it is very similar to the range method. However, the xrange method creates integers in the list only when needed. The xrange method works best when you need to iterate over a large number of integers, because it doesn't create a huge list, which consumes a lot of computer memory.

while

Similar to the if statement, contains a conditional test statement, a loop, that allows the repeated execution of a block of statements.

Optional else statement block, the same as the else block for.

Format:


while < conditions >:
   if < conditions >:
      break
   if < conditions >:
      continue
   < Other statements >
else:
   < statements >

Description:

The else block is executed when the while loop condition becomes False
If you end the loop with a break, the optional else block while does not execute
Python does not have a do while or do until loop statement
Break & continue & pass
Break, terminates the loop statement, stops the loop, if the for/while loop terminates, the else does not execute

Continue, close the current loop, go to the next loop - skip to the beginning of the nearest loop (go to the first line of the loop)

Pass doesn't do anything, it's just a placeholder statement, and it's used for situations where the syntax has to have something, but the program doesn't do anything, right

Loop else block: executes only when the loop leaves normally, i.e

If you break from a for or while loop, any corresponding loop else block will not execute. Remember, the break statement can also be used in the for loop

other

Tips for writing loops:
It is not safe to modify the sequence of iterations during iteration (this is only true if you use a mutable sequence such as a linked list). If you want to modify the sequence of your iteration (for example, copy the option), you can iterate over its copy. This can be easily done by using a cut mark

> > >

 for x in a[:]: # make a slice copy of the entire list
...    if len(x) > 6: a.insert(0, x)

When looping through a dictionary, the keyword and the corresponding value can be read together using the iteritems() method

>>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
>>> for k, v in knights.iteritems():
...     print k, v
...
gallahad the pure
robin the brave

When looping through a sequence, both the index position and the corresponding value can be obtained using the enumerate() function.

>>> for i, v in enumerate(['tic', 'tac', 'toe']):
...     print i, v


Related articles: