Learn Python in Imooc (Getting started)

Source: Internet
Author: User
Tags cos sin square root

Python: Elegant, clear, simple

Suitable areas: Web sites and a variety of Web services, system tools and scripts, as a "glue" language to the development of other language modules packaged for easy use

Unsuitable areas: Hardware-close code (first C), mobile development: Ios/android has its own development language (Objc,swift/java), game development:

Practical application:
Abroad: YouTube, OpenStack
Domestic: Watercress, Sohu Flash mailbox and so on.

Widely used in: Google Yahoo NASA (NASA)

Compare with other languages
Type run Speed code amount
C compiled to machine code very fast very much
Java compiles to bytecode fast
Python explanation Execution Slow

Python source code cannot be encrypted

Cross-platform language

Version 2.7-Incompatible ――3.3 version

Some third-party libraries can no longer run version 3.3 using the ――2.7 version

CMD Command-line window
Python enters Python interactive window
Exit () Exits the interactive window

notepad++ Setting Preferences Utf-8 (no BOMD) format
No spaces at the beginning of the line Python is strict in indentation requirements

To the directory of Python files, perform dir to view all files, python file names execute python files

Data type
Integer hexadecimal 0x prefix 0-9,a-f representation
Floating-point 10 with e substitution
Any text enclosed in a single quotation mark "double quote" "
Boolean True False (note case) with and or not operation
Null value None Special null value is not 0 0 is meaningful

Print statement

The print statement can output the specified text to the screen,
Note:,>>> is a prompt for the Python interpreter when writing code in our Python interactive environment, not part of the code
Text Editor Write code don't add yourself >>>

Print statements can also be followed by multiple strings, separated by commas "," to be connected to a string of outputs

Print back once each string is printed, and "," will output a space,

Print can also be printed with integers or calculated results

Comments

Variable

With a variable name, the variable name must be a combination of uppercase and lowercase English, numeric, and _, and cannot start with a number

equals = is an assignment statement, you can assign any data type to a variable, the same variable can be repeatedly assigned, and can be different types of variables

This type of variable itself is called Dynamic language, which corresponds to static language.

Static language in the definition of variables is the variable type must be specified, if the assignment of type mismatch will error, Java is static language (dynamic language more flexible than static language)

Linear formula
an= a1+ (n-1) *d
sn = a1*n + (n (n-1) *d)/2
sn = (A1+an) *N/2

Defining strings

Strings can be represented by "" "

If you include ' just use ', enclose it.
If you include "just use".
If you include ' also contains ', use the escape character \

\ nthe line break
\ t tab
\ \ \ character itself

Raw strings and multiple lines of string

A string contains many characters that need to be escaped, and you can prefix the string with R to indicate that it is a raw string
R ' .... '
But R ' ... ' notation cannot represent multiple lines of string, nor can it represent a string containing ' and '

If you want to represent multiple lines of string, you can say "..."

Unicode string

ASCII encoding

GB2312 encoding

Print U ' Chinese '
Chinese

Escape: U ' chinese \ n \ japanese \ Korean '

Multi-line ' first line
Second line "'

Raw ' Python's Unicode string supports ' Chinese ',
"Japanese",
"Korean" and many other languages "

If you meet Unicodedecodeerror,
First line plus #-*-coding:utf-8-*-

Because Python regards 0, empty string ' and none as False, other numeric values and non-empty strings are considered True

List ordered lists

One of the data types built into Python is the list: lists. A list is an ordered set of elements that can be added and removed at any time. The elements in the list are arranged in order. just use [] to enclose all the elements of a list, which is a list object.

The list contains elements that do not require the same data type, and we can include all kinds of data in the list:

When using an index, be careful not to cross the border

When using a reverse index, also be careful not to cross the border

Add new Element
The first option is to append the new classmate to the end of the list by using the Append () method of the list:

Append () always adds a new element to the tail of the list.

The middle method is inserted with the list's insert () method, which accepts two parameters, the first parameter is the index number, and the second parameter is the new element to be added:

Delete Element

Delete the last element with the pop () method of list

Deletes the element at the specified position with the pop (ordinal) method of the list

Replace l[1]= ' element '

Tuple ordered list

Tuple is another ordered list, and Chinese is translated as "tuple". Tuple and list are very similar, however, once a tuple is created, it cannot be modified.

The difference between list and tuple

The only difference between creating a tuple and creating a list is to replace [] with ().

The tuple does not have the Append () method, nor the insert () and Pop () methods. Therefore, the new classmate can not directly add to the tuple, old classmates want to quit a tuple also not.

The way to get a tuple element is exactly the same as the list, and we can access the element normally using indexed methods such as t[0],t[-1], but cannot be assigned to another element

Tuple and list, can contain 0, one and any number of elements.
It is precisely because the tuple with the () definition of a single element is ambiguous, so Python specifies that the element tuple should have a comma ",", which avoids ambiguity:

tuple element embedding [] can change the contents of a tuple


If statement:

Note: The indentation rules for Python code. Code with the same indentation is treated as a block of code, with 3, 4 lines of print statements constituting a block of code (but excluding print on line 5th). If the IF statement evaluates to True, the code block is executed.

Indent please strictly follow Python's customary notation: 4 spaces, do not use tab, do not Mix tab and space, otherwise it is easy to cause syntax errors due to indentation.

NOTE: The If statement is followed by an expression, and then with: Represents the code block to begin with.

If you hit the code in a Python interactive environment, also pay special attention to indentation, and exit indentation requires more than one line of return:

If...else ... Statement:

Use if ... else ... Statement, we can execute an if code block or an else code block, depending on the value of the conditional expression, either True or False.

Note: Else there is a ":" later.

If-elif-else statement:

To avoid nesting structures if ... else ..., we can use the If ... Multiple elif ... else ... Structure, write all the rules at once:

For loop:

Take each element of the list in turn, assign the element to name, and then execute the For loop body (that is, the indented block of code)

While loop
Another loop that differs from the For loop is the while loop, which does not iterate over the elements of the list or tuple, but rather determines whether the loop ends with an expression.
The while loop first evaluates x < N, if true, executes the block of code for the loop body, otherwise, exits the loop.

In the loop, x = x + 1 causes X to increase and eventually exits the loop because X < N is not true.

Without this statement, the while loop always evaluates to True for x < N, it loops indefinitely and becomes a dead loop, so pay special attention to the exit condition of the while loop.

Break statement:

When using a For loop or while loop, you can use the break statement if you want to exit the loop directly inside the loop.

During the loop, you can use break to exit the current loop, and you can use continue to skip the subsequent loop code and continue the next loop.

Nested loops:

Inside the loop, you can also nest loops

For x in [' A ', ' B ', ' C ']:
For y in [' 1 ', ' 2 ', ' 3 ']:
Print x + y

Dict Key-value pairs:
D = {
' Adam ': 95,
' Lisa ': 85,
' Bart ': 59
}
The name is called Key, and the corresponding result, called Value,dict, is to find value by key.

The curly braces {} indicate that this is a dict, and then follow the Key:value and write them out. The last comma of a key:value can be omitted.

Since Dict is also a collection, the Len () function can calculate the size of any collection:

Note: A key-value is counted one, so the dict size is 3.

Visit dict
You can simply use the form of D[key] to find the corresponding value, which is like the list, but the list must return the corresponding element using the index, and Dict uses key:

Note: The value of dict is accessed by key, and Dict returns the corresponding value as long as the key exists. If key does not exist, it will directly error: Keyerror.

There are two ways to avoid keyerror:

First, determine whether the key exists, with the in operator:
If ' Paul ' in D:
Print d[' Paul '

The second is to use the dict itself to provide a get method, when the key does not exist, return to none:
Print D.get (' Bart ')

Features of Dict

The lookup speed is fast (and the list's lookup rate decreases as the element increases.) )

However, dict search speed is not without cost, dict the disadvantage is that the memory is large, but also waste a lot of content, the list is just the opposite, the memory is small, but the search speed is slow.

Because Dict is located by key, in a dict, key cannot be duplicated.

The second feature of Dict is that the stored key-value sequence pair is not in order! This is not the same as list:

You cannot store an ordered collection with Dict.

The third feature of Dict is that elements that are key must be immutable, and the basic types of python, such as strings, integers, and floating-point numbers, are immutable and can be used as keys. But the list is mutable and cannot be a key.

{
' 123 ': [1, 2, 3], # key is Str,value is List
123: ' 123 ', # key is Int,value is str
(' A ', ' B '): True # key is a tuple, and each element of a tuple is an immutable object, value is a Boolean
}

The most commonly used key is also a string, because it is most convenient to use.

Dict is mutable, which means we can add new Key-value to dict at any time.

d[' Paul '] = 72

If the key already exists, the assignment replaces the original value with the new value:

Use the For loop directly to traverse the Dict key:
>>> d = {' Adam ': $, ' Lisa ': $, ' Bart ': 59}
>>> for key in D:
... print Key
...
Lisa
Adam
Bart
Because the corresponding value can be obtained by key, the value can be obtained in the loop body.

The role of Dict is to establish a set of keys and a set of value mappings, Dict key cannot be duplicated.

Set unordered:

The way to create a set is to call set () and pass in a list,list element as the set element:
s = set ([' A ', ' B ', ' C '])
The set holds a series of elements, which are similar to the list, but the set elements are not duplicates and are unordered, which is similar to the Dict key.
Set cannot contain duplicate elements
Set will automatically remove duplicate elements

Because set stores unordered collections, we cannot access them through an index.

Accessing an element in a set actually determines whether an element is in the set.

You can use the in operator to determine:

It appears that the case is important, ' Bart ' and ' Bart ' are considered to be two different elements.

Features of Set

The internal structure of set is much like the dict, the only difference is that it does not store value, so it is very fast to determine whether an element is in set.

The set stored element is similar to the Dict key, and must be an immutable object, so any mutable object cannot be placed in the set.

Finally, the set stores the elements that are not in order.

You can iterate through the elements of a set directly using a For loop:

Note: When observing A For loop, the order of the elements and the order of the list is likely to be different when traversing set, and the results of running on different machines may be different.

Notice that the set element is a tuple, so that the for loop variable is assigned a tuple in turn.

Because set stores a set of unordered elements that are not duplicated, the update set mainly does two things:

One is to add the new element to the set, and the other is to remove the existing element from the set

When adding an element, use the Add () method of Set:

If the added element already exists in set, add () will not error, but will not be added:

When removing elements from a set, use the Remove () method of Set:

If the deleted element does not exist in the set, remove () will error:

So with Add () can be added directly, and remove () before you need to judge.

Determines whether the element is in set, using the in operator.

ABS () with only 1 parameters
A comparison function cmp (x, y) requires two parameters
the int () function can convert other data types to integers:
The STR () function converts other types to str:

Function

In Python, define a function to use the DEF statement, write down the function name, parentheses, the arguments in parentheses, and the colon: and then, in the indent block, write the function body, and the return value of the function is returned with a return statement.

Note that when the statement inside the function body executes, once it executes to return, the function finishes and returns the result. As a result, very complex logic can be implemented inside the function through conditional judgments and loops

If there is no return statement, the result is returned after the function is executed, except that the result is none.

Return none can be shortened to return.

# The Math package provides the sin () and cos () functions, which we first refer to with import:

Import Math
def move (x, y, step, angle):
NX = x + step * Math.Cos (angle)
NY = y-step * Math.sin (angle)
Return NX, NY

In syntax, returning a tuple can omit parentheses, and multiple variables can receive a tuple at the same time, assigning the corresponding value by location, so the function returned by Python is actually a tuple, but it is easier to write.

Note: The Python math package provides the SQRT () function for calculating the square root.
The use of recursive functions requires careful prevention of stack overflow. In the computer, the function call is implemented through a stack (stack) of this data structure, each time into a function call, the stack will add a stack of frames, whenever the function returns, the stack will be reduced by a stack of frames. Because the size of the stack is not infinite, there are too many recursive calls that can cause the stack to overflow.

The definition of a function move (n, a, B, c) is to move n discs from A through B to C.

def move (n, a, B, c):
If n ==1:
Print a, '--', C
Return
Move (N-1, A, C, b)
Print a, '--', C
Move (n-1, B, A, c)
Move (4, ' A ', ' B ', ' C ')
.
Python's own int () function, in fact, there are two parameters, we can both pass a parameter, and can pass two parameters:

The second argument of the Int () function is the conversion, if not passed, the default is decimal (base=10), and if passed, use the passed in parameters.
As you can see, the function's default parameter is to simplify the call, and you just need to pass in the necessary parameters. However, when needed, additional parameters can be passed in to override the default parameter values.

Learn Python in Imooc (Getting started)

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.