Python-basics-getting started, python-getting started

Source: Internet
Author: User

Python-basics-getting started, python-getting started

Python introduction and getting started

Python
Why python?

It is usually not easy to select your preferred language, but more based on your needs.

In other words, java was used before, and the university spent more than three years of practice and half a year of practice. Later, when I started testing and development, I met python.

Finally, I switched to python for development.

Fast writing, indentation, no curly braces, finger-saving, comfortable reading .....

I like it. It seems that I don't need any reason for being too cool.

If you can ignore the competition between languages, the battle of the editor, and so on, you can ignore it. If you can ignore it, you can ignore it. If you have enough tools, you can use it. If you are comfortable with it, you will be OK, A waste of water and energy to fight for a picture.

Life is short, I use python!

Introduction

Python Introduction: Go to the official website and check it yourself.

If you are interested, you can see: explanatory language + dynamic type language + strong type language

Disadvantage: google

International practice

Interactive Mode: (mainly used for testing, you can try ipython to support automatic tab completion)

Copy codeThe Code is as follows:
$ Python
>>> Print 'Hello world'

Script

Copy codeThe Code is as follows:
#! /Usr/bin/env python
Print 'Hello world'

Environment and other
Basic installation: google myself [install and configure a search engine, basic skills, don't explain, it looks like a long time ago I also wrote a http://blog.csdn.net/wklken/article/details/6311292

Environment:

We recommend that you use python2.7 + easy_install + pip + virtualenv + ipython.
Development tools:

Vim/sublimetext2/eclipse + pydev/pycharm
We recommend that you use idle or pydev as a beginner,
Encoding style:

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

Getting started
Start

Indent
Python functions do not have explicit begin and end, and they do not contain curly brackets indicating the start and end of a function. The only separator is a colon (:), and the Code itself is indented.

Example:

Copy codeThe Code is as follows:
# Functions
Def func (value ):
Print value # indent

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

Identifier
A variable is an example of an identifier. An identifier is the name used to identify something. Follow these rules when naming identifiers:

1. The identifiers in python are case sensitive.

2. The identifier must start with a letter or underline and can contain letters, underscores, and numbers. It is case sensitive.

3. The identifier starting with the following line has special significance.

• Class attributes that cannot be directly accessed starting with a single underscore (_ foo) must be accessed through the interface provided by the class, and cannot be imported using "from xxx import;
• (_ Foo) starting with a double underline represents a private member of the class;
• Foo, which starts with and ends with a double underline, represents a special identifier for special methods in python. For example, _ init _ () represents the constructor of the class.
4. The identifier cannot be a reserved word.

And elif global or yield
Assert else if pass
Break failed t import print
Class exec in raise
Continue finally is return
Def for lambda try
Del from not while
Variable
Assignment Statement

• The value assignment statement creates an object reference value.
• The variable name will be created when the first value is assigned
• The variable name must be assigned a value before being referenced.
Assignment Method

• Simple assignment
Variable (Variable) = Value (Value)

S = 'spam'
• Multi-variable assignment
In python, the original tuples and list assignment statements are formed and finally generalized to accept sequences of any type on the right, as long as they are of the same length. Note that the length must be equal

Variable1, variable2,... = Value1, Value2 ,...

S, h = 'A', 'B' tuples assignment, location [common]
[S, h] = ['A', 'B'] list assignment, location
A, B, c, d = 'spam' sequence assignment, universal
A, * B = 'spam' expand sequence unpackage (python3)

• Multi-objective Assignment

A = B = variable

S = h = 'spam' multi-objective Assignment
Note: the memory of multiple variables points to the same object. For variable types, modifying one variable will affect others.

• Auto-variable assignment
For example, + =,-=, * =.

In the auto-variable assignment, python only calculates the value once, while the normal writing method needs to calculate the value twice;

The self-changing value assignment modifies the original object instead of creating a new object.

S + = 42 enhanced assignment
X + = y
Advantages:

Less input by programmers

The left side only needs to be calculated once, and the optimization technology automatically changes the original location, making it faster
L + = [] original Modification
L = l + [] Copy to generate a new object
Operator
An expression can be decomposed into operators and operands.

The function of operators is to accomplish something. They are represented by symbols such as + or other specific keywords.

Operators need data to perform operations. Such data is called operands.

Operator priority list (from highest to lowest)

Operator description

'Expr' String Conversion
{Key: expr,...} dictionary
[Expr1, expr2. ..] list
(Expr1, expr2,...) tuples
Function (expr,...) function call
X [index: index] Slice
X [index] subscript index value
X. attribute reference
~ X bitwise Inversion
+ X,-x positive, negative
X ** y Power
X * y, x/y, x % y multiplication, division, modulo
X + y, x-y plus, minus
X <y, x> y shift
X & y
X ^ y returns an exclusive or
X | y by bit or
X <y, x <= y, x = y, x! = Y, x> = y, x> y comparison
X is y, x is not y equals Test
X in y, x not in y member judgment
Not x logic No
Logic and
X or y logic or
Lambda arg,...: expr Lambda anonymous Function
Combination rules

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

Computing Sequence

By default, the operator priority table determines which operator is calculated before another operator. However, if you want to change their computational order, you must use parentheses. Good practice: brackets are added for complex operations by default, instead of relying on the default combination and computing sequence.

True Value
True Value Test
• Any non-zero number or non-empty object is true
• Zero number, empty object and special object None are false
• Comparison and equality tests are recursively applied to the data structure.
• True or False is returned for comparison and equality tests.
Truth Table

Copy codeThe Code is as follows:
Object/Constant Value
"" False
"String" true
0 false
2> = 1 true
-2 <=-1 true
() Null tuples false
[] Empty list false
{} Empty dictionary false
None false


Boolean expression
Three Boolean expression Operators

Copy codeThe Code is as follows:
X and y
X or y
Not x


Comparison
• Numbers are compared by relative size
• Strings are alphabetically ordered. One character is compared with one character
• Compare the content of each part from left to right in the list and element group
• The dictionary is compared by the sorted key-Value List.
• The Number Mixing type is incorrect in python3, but python2.6 supports fixed but arbitrary sorting rules.
Boolean
• There are two values that never change: True and False.
• Boolean is a subclass of an integer, but cannot be inherited.
• The default value of the object without the _ nonzero _ () method is True.
• For any number or empty set whose value is 0, the value is False.
• In mathematical operations, the True and False values of Bollean correspond to 1 and 0 respectively.
Basic Control Flow
If
Basic Condition test statements are used to determine different situations and perform operations on different situations.

Basic Form

Copy codeThe Code is as follows:
If <condition>:
<Statement>
Elif <condition>:
<Statement>
Else:
<Statement>

Note:

Python determines Based on Indentation that elif and else are optional.

Example:

Copy codeThe Code is as follows:
A = 1
B = 2
C = 3; d = 4 # separate the two sentences with semicolons.

If a <B and c <d:
Print ("branch ")
Elif a = B:
Print ("branch B ")
Else:
Print ("branch c ")
Switch

Python does not have a switch statement. if you need to use if/elif/else to do the same job, you can use a dictionary in some cases.

You can also use dict.

If/else ternary Operators

A = (X and Y) or Z)
A = Y if X else Z
Example: a = 't'if x else 'A'
For
• Basic syntax
A loop control statement that can be used to traverse a sequence cyclically.

The else block is optional. It is executed when the loop ends. If the break terminates the loop, the else does not execute

Format:

Copy codeThe Code is as follows:
For <object variable> in <object set>:
If <condition>:
Break
If <condition>:
Continue
<Other statements>
Else:
<Other statements>


Note:

1. The object set can be a list, dictionary, and tuples.
2. for... in loop applies to any sequence
3. When for traverses a dictionary, it traverses the dictionary key.
• Rang & xrange
You can use the range () function to generate an integer list to complete the counting cycle.

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

An optional start parameter.
Number of stop termination, if x, generates an integer list from 0-(x-1)
An optional parameter for step. The default value is 1 if not specified.
Range () contains a sequence of [1, 2, 3, 4].

Differences between xrange and range

(Python3.x can be ignored)

In the Range method, it generates a list object, but in XRange, it generates an xrange object. When the returned content is not very large, or, in a loop, the efficiency of the two methods is almost the same when we check the results from the beginning. However, XRange is recommended when the returned items are large or the cycle is often Break, which saves space and improves efficiency.

Copy codeThe Code is as follows:
>>> Print range (1, 5)
[1, 2, 3, 4]
>>> Print xrange (1, 5)
Xrange (1, 5)


In the preceding statement, range returns a common List, And xrange returns a specific xrange object. Because the xrange method also creates an integer list (which uses the same parameters), it is very similar to the range method. However, the xrange method creates an integer in the list only when necessary. When a large number of integers need to be iterated, The xrange method is more suitable because it does not create a large list, which consumes a lot of computer memory.

While
Similar to the if statement, the statement contains a conditional test statement and can be executed repeatedly in a loop.

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

Format:

Copy codeThe Code is as follows:
While <condition>:
If <condition>:
Break
If <condition>:
Continue
<Other statements>
Else:
<Statement>

Note:

• When the while LOOP condition is set to False, the else block is executed.
• If the break is used to end the loop, the optional while else block is not executed.
• Python does not have do while or do until loop statements
Break & continue & pass
Break: Terminate the loop statement and stop the loop. If the for/while loop is terminated, the else does not execute

Continue, end current, enter the next cycle-jump to the beginning of the last cycle (to the first line of the loop)

Pass does not do anything. It is just a null placeholder statement. It is used in scenarios where the syntax must have any statements but the program does nothing.

Loop else block: it is executed only when the loop normally leaves, that is

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

Others
Loop writing skills:
Modifying an iterative sequence during an iteration is not secure (this is the case only when a variable sequence like a linked list is used ). If you want to modify the sequence of your iteration (for example, copy an item), you can iterate its replica. You can easily achieve this by using the cutting mark.

Copy codeThe Code is 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, you can use the iteritems () method to interpret the keywords and corresponding values at the same time.

Copy codeThe Code is as follows:
>>> Knights = {'gallahad': 'The plain', 'Robin ': 'The brave '}
>>> For k, v in knights. iteritems ():
... Print k, v
...
Gallahad the pure
Robin the brave

You can use the enumerate () function to obtain the index position and corresponding value during a sequence loop.

Copy codeThe Code is as follows:
>>> For I, v in enumerate (['Tic ', 'tac', 'toe']):
... Print I, v


Books introducing python without programming language basics

Basic Python tutorial (version 2nd)
By Magnus Lie Hetland)

Well written

Introduction to some python getting started books

I personally think the concise Python tutorial is suitable for beginners who have no basic programming skills and understand the basic syntax of Python.

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.