Simple introductory instructions for the Python Basics tutorial (variables and Control language usage) _python

Source: Internet
Author: User
Tags bitwise terminates in python

Brief introduction
Interested to see: Explanatory language + Dynamic type language + strongly typed language

Interactive mode: (mainly to test, you can try Ipython)

Copy Code code as follows:

$python
>>> print ' Hello World '

Script

Copy Code code as follows:

#!/usr/bin/env python
print ' Hello World '


Environment:

Recommended python2.7 + Easy_install + pip + virtualenv + Ipython

Indent
The Python function has no obvious begin and end, and no curly braces indicating the beginning and ending of the function. The only delimiter is a colon (:), and then the code itself is indented.

Example:

Copy Code code as follows:

#函数
def func (value):
Print Value #缩进

If value = 1:
Value + 1
Elif value = 2:
Pass
Else
Value + 10

Identifier
A variable is an example of an identifier. An identifier is a name used to identify something. At the time of naming identifiers, you should follow these rules:

The identifiers in 1.python are case-sensitive.

2. The identifier begins with a letter or an underscore, which can include letters, underscores and numbers, and is case-sensitive

3. Identifiers that begin with an underscore are of special significance.

Class attributes that are not directly accessible by the representative of a single underscore (_foo) are accessed through the interfaces provided by the class and cannot be imported with the "from XXX import *".
A double underline (__foo) represents a private member of a class;
The start and end of a double underscore (foo) represents a particular method-specific identity in Python, such as Init (), which represents the constructor of a class.

4. Identifiers cannot be reserved words

Copy Code code as follows:

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 but

Variable

Assignment statement

1, the assignment statement establishes the object reference value
2. Variable names are created when they are first assigned
3, the variable name must be assigned before the reference, cannot refer to the variable without declared assignment


How to assign a value

Simple assignment
Variable (variable) =value (value)

Copy Code code as follows:

s = ' spam '

Multi-variable assignment

The original tuple and list assignment statements in Python are formed and finally generalized to accept that the right can be any type of sequence, as long as the length is equal. Note that the length must be equal
Variable1,variable2,... =value1,value2,...

Copy Code code as follows:

S,h = ' A ', ' B ' tuple assignment, positional ' common '
[S,h] =[' A ', ' B '] list assignment, positional
a,b,c,d = ' spam ' sequence assignment, versatility
a,*b = ' spam ' Extended sequence unpack (Python3)

Multi-Objective assignment

Copy Code code as follows:

A=b=variable

s = h = ' spam ' Multi-target assignment


Note: Multiple variable memory to the same object, for the variable type needs, modify one will affect the other

Self-variable assignment

Copy Code code as follows:

such as +=,-=,*= and so on.

In the Self variable assignment, Python only computes once, and the normal writing needs to be calculated two times;

A variable assignment modifies the original object, rather than creating a new object.

Copy Code code as follows:

s +=42 Enhanced Assignment
X + y

Advantages:

Copy Code code as follows:

The left only need to calculate once, optimize the technology automatically change, faster
L +=[] in situ modified
L = l+[] replication, generating new objects

Operator
An expression can be decomposed into operators and operands

The function of an operator is to accomplish something that is represented by symbols such as + or other specific keywords

Operators require data for operations, and such data is called operands

List of operator precedence (from highest to lowest)

Copy Code code as follows:

Operator description
' Expr ' string conversion
{key:expr,...} Dictionary
[Expr1,expr2 ...] List
(EXPR1,EXPR2,...) META Group
function (expr,...) Function call
X[index:index] Slice
X[index] Subscript index value
X.attribute Property Reference
~x by Bitwise counter
+x,-x positive, negative
X**y Power
X*y,x/y,x%y multiply, divide, take modulo
X+y,x-y Plus, minus
X<<y,x>>y shift
X&y by Bit and
X^y per-Bitwise XOR OR
X|y bitwise OR
X<y,x<=y,x==y,x!=y,x>=y,x>y comparison
X is y,x are not y equivalent test
X in y,x not in Y member judgments
Not x Logical No
X and Y Logic and
x or y logic or
Lambda arg,...: expr Lambda anonymous function

Binding law

Operators are usually combined left to right, that is, operators with the same precedence are evaluated in Left-to-right order

Order of calculation

By default, the operator precedence table determines which operator is evaluated before the other operators. However, if you want to change the order in which they are calculated, you have to use parentheses. Good practice: The default is to add parentheses to complex operations, rather than relying on default binding and calculation Order

Truth
Truth test

1, any non-0 numbers or Non-null objects are true
2, number zero, empty objects and special objects none are false
3, comparison and equivalence testing will be recursively applied to the data structure
4. Comparison and equality tests return TRUE or False


Ic

Copy Code code as follows:

Object/Constant Value
"" False
"String" really
0 Fake
2>=1 really
-2<=-1 really
() null tuple fake
[] Empty list fake
{} Empty dictionary fake
None Fake

Boolean expression
Three Boolean expression operators

Copy Code code as follows:

X and Y
X or Y
Not X

Comparison
Numbers are compared by relative size
string in dictionary order, one character by one character comparison
Lists and tuples compare the contents of each section from left to right
The dictionary is compared by a sorted list of key values
Numeric blending type comparisons are wrong in Python3, but python2.6 support, fixed but arbitrary collation

Boolean number
There are two values that never change true,false
Boolean is a subclass of an integral type, but cannot be inherited again
The default value for an object without the nonzero () method is True
For any number or empty set with a value of 0, the value is False
In mathematical operations, the Bollean value of true and false corresponds to 1 and 0, respectively.
Basic Control Flow

If
Basic conditional test statements to determine the different situations that might be encountered and to operate on different situations

Basic form

Copy Code code as follows:

If < conditions:
< statements >
Elif < conditions:
< statements >
Else
< statements >

Attention

Python based on indentation, the elif and else parts are optional

Example:

Copy Code code as follows:

A = 1
b = 2
c = 3;d=4 #两个放一句用分号隔开, but recommended branch

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, if necessary, with if/elif/else implementation of the same work, some cases may consider using a dictionary

It can also be used in the form of dict

If/else ternary operator

Copy Code code as follows:

A = ((X and Y) or Z)
A = Y if X else Z
Example: a = ' t ' if x else ' a '
[Code]

For

Basic syntax

A circular control statement that can be used to iterate through a sequence

Else block is optional, executed at the end of the loop, if the break terminates the loop, else does not execute

Format:
[Code]
For < object variable > in < object set:
if< conditions:
Break
if< conditions:
Continue
< other statements >
Else
< other statements >

Attention:

1. A collection of objects can be a list, a dictionary, a tuple, etc.
2.for.. In loops are applicable for any sequence
3.for traversing a dictionary, the key of the dictionary is traversed

Copy Code code as follows:

Rang & Xrange

You can create a list of integers by using the range () function to complete the counting loop

Copy Code code as follows:

Range ([Start,] stop[, step]

Start optional argument, starting number
Stop number, if x, generates a list of integers from 0-(x-1)
Step optional parameters, steps, not written defaults to 1
Range (1,5) contains a sequence of [1,2,3,4]

Xrange and Range differences

(python3.x can be ignored)

In the method of range, it generates a list object, but in xrange it generates a Xrange object, and the two methods are more efficient when the returned items are not very large, or in a loop, and are basically checked from scratch. However, when the return of something large, or the cycle will often be break out, or recommend the use of xrange, so that both save space, but also improve efficiency.

Copy Code code as follows:

>>> 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 particular xrange type. Because the Xrange method also creates an integer list that uses the same parameters, it is very similar to the Range method. However, the Xrange method creates integers in the list only when needed. When you need to iterate a large number of integers, the Xrange method is more applicable because it does not create a great list, which consumes a lot of computer memory.

While

Like an If statement, contains a conditional test statement that loops, allowing a repeating block of statements to be executed.

Optional ELSE statement block, same as for else block.

Format:

Copy Code code as follows:

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 use the break end loop, the while optional else block does not execute
Python does not have a do while or do Until loop statement
Break & Continue & Pass
Break, terminate the loop statement, stop the loop, and if it terminates in the For/while loop, the else does not execute

Continue, end current, go to next round loop-jump to the beginning of the nearest loop (come to the first line of the loop)

Pass does nothing, just empty placeholder statements, it is used for those grammatical must have what statement, but the program does not do the occasion

Loop Else BLOCK: Executes only if the loop is normal to leave, that is,

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

Other

Tips for Writing loops:
It is unsafe to modify the iteration sequence during the iteration (this is only true if you are using a mutable sequence such as a linked list). If you want to modify the sequence of your iterations (for example, copy the selection), you can iterate over its copy. You can do this easily with a cutting mark.

>>>

Copy Code code as follows:
For x in a[:]: # Make a slice copy of the entire list
... if Len (x) > 6:a.insert (0, X)

When looping in a dictionary, keywords and corresponding values can be interpreted at the same time using the Iteritems () method
Copy Code code as follows:

>>> 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, index positions and corresponding values can be obtained at the same time using the enumerate () function.
Copy Code code as follows:

>>> for I, V in enumerate ([' Tic ', ' tac ', ' toe ']):
... print I, V

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.