python-Basics-Getting Started introduction _python

Source: Internet
Author: User
Tags bitwise data structures terminates in python

Introduction to Python and Getting started

Python
Why is Python

Choose your favorite language, this is often not easy, more is based on demand

In other words, before the Java, the university spent three years + internship six months, and then into the post to do the test development, met the Python

In the end, turn to Python to develop a

Write quickly, indent, do not have to play curly braces, save the finger, read comfortable ...

Like, seemingly do not need anything too bull reason, with comfortable on the line

What language dispute, editor war What, can ignore ignore it, can ignore it, tools, enough, with this comfortable on the OK, waste of saliva energy struggle to fight to figure what?

Life are short, I use python!

Brief introduction

Python introduction: To the official website from a look

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

Pros and Cons: Google yourself

International

Interactive mode: (mainly to test, you can try Ipython Support tab automatic completion)

Copy Code code as follows:

$python
>>> print ' Hello World '

Script

Copy Code code as follows:

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

Environment and other
Basic installation: Own google[installation and configuration A lot of search, basic skills, do not explain, looks like a long time ago I also wrote an article http://blog.csdn.net/wklken/article/details/6311292

Environment:

Recommended python2.7 + Easy_install + pip + virtualenv + Ipython
Development tools:

Vim/sublimetext2/eclipse+pydev/pycharm
Suggest beginners idle or Pydev bar, with a handy on the line,
About coding style:

Google's: http://google-styleguide.googlecode.com/svn/trunk/pyguide.html
Chinese: http://www.bsdmap.com/articles/zh-google-python-style-guide/
--------------------------------------------------------------------------------

Entry
No, start.

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.

• A class attribute that is not directly accessible by the representative of a single underline (_foo) is accessed through the interface provided by the class, and cannot be imported with "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

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

• An assignment statement establishes an object reference value
• Variable names are created when they are first assigned
• Variable names must be assigned before reference and cannot refer to variables without declared assignment
How to assign a value

• Simple Assignment
Variable (variable) =value (value)

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,...

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

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
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.

s +=42 Enhanced Assignment
X + y
Advantages:

Less programmer input

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)

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
• Any non-0-digit or Non-empty object is True
• Number zero, empty objects and special objects none are fake
• Comparisons and equivalence tests are recursively applied to data structures
• 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
• Strings are in dictionary order, one character by one character comparison
• Lists and tuples compare the contents of each section from left to right
• Dictionaries are compared by 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 objects without the __nonzero__ () method is True
• Value false for any number or empty set with a value of 0
• In mathematical operations, true and false for Bollean values correspond 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

A = ((X and Y) or Z)
A = Y if X else Z
Example: a = ' t ' if x else ' a '
For
• Basic grammar
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:

Copy Code code as follows:

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
Rang & xrange
You can create a list of integers by using the range () function to complete the counting loop

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

If the while loop condition becomes false, the else block is executed
• If you use the break end loop, the while optional else block does not execute
Python does not have a 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.