Basic python Tutorial-Python tutorial

Source: Internet
Author: User
This article mainly introduces the knowledge needed to learn python in the first step (how to use variables and control languages). If you need it, refer to the introduction below.
If you are interested, you can see: Explanatory language + dynamic type language + strong type language

Interactive mode: (for experiment, try ipython)

The code is as follows:


$ Python
>>> Print 'Hello world'

Script

The code is as follows:


#! /Usr/bin/env python
Print 'Hello world'


Environment:

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

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:

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

A class attribute that starts with a single underscore (_ foo) represents a class attribute that cannot be accessed directly. it must be accessed through the interface provided by the class. it cannot be imported using "from xxx import;
(_ Foo) starting with a double underline represents the private member of the class;
The (foo) that begins 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.

The code is as follows:


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

1. The value assignment statement creates an object reference value.
2. the variable name will be created when the value is assigned for the first time.
3. a variable name must be assigned a value before being referenced. a variable without a value declared cannot be referenced.


Assignment method

Simple assignment
Variable (Variable) = Value (Value)

The code is as follows:


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

The code is as follows:


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

The code is as follows:


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-changing value assignment

The code is as follows:


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.

The code is as follows:


S + = 42 enhanced assignment
X + = y

Advantages:

The code is as follows:


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)

The code is as follows:


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 shift
X & y
X ^ y returns an exclusive or
X | y by bit or
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

1. any non-zero number or non-empty object is true.
2. zero number, empty object and special object None are false
3. comparison and equality tests are recursively applied to the data structure.
4. True or False is returned for comparison and equality tests.


Truth table

The 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

The code is as follows:


X and y
X or y
Not x

Comparison
The number is compared by relative size.
Character string in alphabetical order. one character can be compared with one character.
List and meta-group, and compare the content of each part from left to right
The dictionary is compared by the sorted key-value list.
It is incorrect to compare the mixed numeric types 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 an 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

The code is as follows:


If <条件> :
<语句>
Elif <条件> :
<语句>
Else:
<语句>


Note:

Python determines based on indentation that elif and else are optional.

Example:

The 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

The code is 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 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:
[Code]
For <对象变量> In <对象集合> :
If <条件> :
Break
If <条件> :
Continue
<其他语句>
Else:
<其他语句>

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.

The code is as follows:


Rang & xrange

You can use the range () function to generate an integer list to complete the counting cycle.

The code is as follows:


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.

The 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:

The code is as follows:


While <条件> :
If <条件> :
Break
If <条件> :
Continue
<其他语句>
Else:
<语句>

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

>>>

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

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

The code is as follows:


>>> For I, v in enumerate (['tic ', 'tac', 'toe']):
... Print I, v

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.