Teach you Python Quick Start from zero base

Output and input

type of data

Variables and constants

Conditional statements, looping statements

List (list), tuple (tuple), Dictionary (dict), collection (set)

function

Object Oriented (class)

Output and input:

Output:
1.Print ( "...") there can be a single quotation marks, parentheses can not (old version).

2. The output may also be continuous, only need to add a line preceding a comma output: print "...", "...".

3 may also output the result of the expression print 4 + 2

4 may output a different type of result: print "hello:" 4 + 2.
Input:
carrying a the raw_input () function, and may be entered into the results among the variables: language = raw_input ( "please input your best language:"), brackets for the previously input print it, but it returns a string type, when the index (for example, int type) we want other types, we can a = int (input ()) .

type of data

Data Type: integer, floating point (decimal), the string: single or double quotes enclosed, Boolean, null
Note: When variables were declared not need to mark the data type declaration, the system automatically identifies, for example, I declare an integer number equal to ten: a = 10, instead int a = 10. It is with c ++ difference is relatively large.
1. The calculation result between the integer is an integer, floating point and integer arithmetic result float, but where rounding occurs.
2. escape character: print ( 'hello' world ' ), this time inside the single quotes and outside the conflict, but this time want to output single quotation marks, you must use the escape character \, double quotation marks as well. \ n newline, when we write multiple lines, you can use three single quotes.
3. Boolean:. True, False
4. Boolean operations: calculating a value out of the comparison, for example, 3> 2 is a True Type.
5 and non-: and, or, Not
6. The string:
common methods:
Center: filling both sides by character (space by default), so that the string center. center (39): by fill characters, so that the string length becomes 39
Center (39, ' '), padding character becomes ' '.
find: Find string in a string which, if found, return the index of the first character string, otherwise -1.
the Join: elements for a combined string into a sequence of:
SEQ = [ '. 1', '2', '. 3', '. 4', '. 5']
On Sep = '+'
sep.join (SEQ)
finally becomes '. 3. 1 + 2 + + +. 5. 4'
Lower: returns a lowercase version string, x.lower ().
replace: the specified string into another string: replace ( 'is', ' hello'), is a string, hello the replacement string.
split: the string into a sequence:
'. 3. 1 + 2 + + + 5'.split. 4 (' + ') --------> ['. 1 ',' 2 ','. 3 ', '. 4', '. 5']
Strip: the empty string beginning and end of the blank but does not include an intermediate deleted, and returns the result of deletion.
String .strip ().
Of course, this can also specify which character or string to delete, strip ( '*').

Variables and constants

1. Variable: only a number, but also may be of various data types: str = "hello", which must be numerals, capital and - virtue of combination. Variables can not be used in the definition of the beginning of a number or special character. Principle Example: When you define a string variable, will open up a space in the memory, and let the variable to point to this space.
2. Constant: an amount that can not be changed, for example, PI is the ratio of the circumference, which itself can not be changed.

Conditional statements, looping statements

1.if statement: if + colon + + conditions achieved statement: if num> 0: print ( 'hello world') // preferably a colon cell line breaks and a retracted
2.else statement: else: realized statement
3.if else statement continuous use:
For example: IF NUM> 0:
...
elif NUM <0:
...
the else:
...
Note indent! ! ! !
4. More complex conditional statements:
A comparison operators: the equality operator (==), the same operator (is) (note here is operator is to detect whether the same two variables, but not equally, more rigorous)
membership operators (in): for example, the name of which is the name n among members, namely n in name is true.
5. loop:
a.while statement: while + Conditions:
execute statement (indentation must be performed between the same sentence, and to be more indented than while)
Example: the while X <100:
Print (X)
X ++;
B.FOR statement : example:
words = [ "the this", "that", ...]
for words in Word:
Print (Word)
. C out of the cycle: break

List (list), tuple (tuple), Dictionary (dict), collection (set)

Lists, tuples, dictionaries, a set of data structures which are python, the basic data structure sequence. The list can be modified but not tuples.
1. Sequence :
. Index A: By using the access number for each element, but can only access the individual elements
example: greeting = "hello"
we can access by character h greeting [0], python sequences which are from zero beginning, of course, there are some special features, can also index is negative, for example: greeting [-1] is the last character o.
b slices: a plurality of elements can be accessed within a specified range at once.
For example: name = [1,2,3,4,5,6,7,8,9]
name [. 3: 6] is a sequence of access name among the fourth to sixth elements, the index is not within range 6 Inside.
Note: When performing a slicing operation, if the first index specifies the second element is located behind the specified elements, the result is an empty sequence.
If the first index at the beginning of a sequence, may be omitted: name [: 6] to access the first to sixth elements.
. C sequences are added: splicing sequence is achieved by adding: [l, 2,3] + [4,5,6] = [1,2,3,4,5,6].
D sequence multiplication: When multiplying the sequence number x of time, the sequence will be repeated x times, for example: [42] * 5 is [42,42,42,42,42]
2. list:
a.list function: list ( "hello "), establishing a direct [ 'H', 'E', 'L', 'L', 'O'].
B modify the list: directly to the index assignment can be
for example: x = [1,1,1 ]
X [. 1] = 2
Then the list becomes x [1,2,1] a.
. c remove elements: the del statement.
Example: names = [ "Peter", "Zam", "Lisa"]
del names [. 1]
eventually become names [ "Peter", "Lisa"].
D slice assigned to:
For example: name = list ( "hello ")
name [2:] = list (" Y ")
final list becomes: [ 'h', 'e ', 'y']
this function can also be implemented insert:
Number = [l, 5]
Number [. 1 : 1] = [2,3,4]
eventually list becomes [1,2,3,4,5].
may also be implemented to delete:
example:
Number = [1,2,3,4,5]
Number [1 : 4] = []
final list becomes [1,5].
e list of methods:.
len (): get the list length, len (X)
the append: an object is added to the end of the list, such as:
LST = [l, 2,3]
lst.append (. 4)
final list becomes [ 3, 4], the number 4 is added to the back of the list.
clear: clear the list, such as:
LST = [l, 2,3]
lst.clear ()
final list is emptied into [].
copy: copy the list, such as:
= a [l, 2,3]
b = a.copy ()
so we put a list of copied contents inside them to the list b.
count: Calculates how many times the element occurs in the list, such as:
X = [1,2,3,4]
x.count (1)
indicates a count which occurred once.
extend: a plurality of value to the end of the list, such as:
a = [1,2,3]
B = [4,5,6]
a.extend (B)
then becomes a list [1,2,3 , 4,5,6]. But it is not the same as stitching, which is directly modify the list, rather than creating a new list, then high efficiency competition.
index: find the index of the first occurrence of a specified value in the list, such as, name.index ( 'h'), it is to find the index h in the name inside the first occurrence.
insert: insert an object list:
Number = [l, 2,3]
number.insert (. 1, 'Four')
list becomes [1, 'four', 2,3 ].
pop: Remove from among a list element, the default is the last element, and returns the element:
X = [l, 2,3]
Print (x.pop ())
the result is 3, and the list becomes [1,2 ].
Or:
Print (x.pop (0))
by deleting the first element, the result is 1, and the list becomes [2,3].
remove: deleting the first element of the specified value. remove (specified value)
reverse: reverse.
sort (): the list is sorted (does not return any value, is to modify the list to), but can be sorted: x.sort (), sorted (x ), the default is ascending.
3. tuple:
tuples can not be modified, tuple element which can be any type.
. a fact create a tuple is simply to put some values separated by a comma, then the tuple can be automatically created: x = 1,4, x is a tuple. Or may be parentheses
b.turple functions: as an argument to a sequence, to convert it to a tuple, if the sequence has a tuple, then it can be returned intact.
turple ([l, 2,3]) ------> (l, 2,3)
turple ( 'ABC') --------> ( 'A', 'B', 'C ')
index: returns the index of the value: x.index (element)
Note: the
definition of an empty tuple, can be written as (), but not empty tuple None, is the null value.
When defining a tuple element, to write (X,), but can not be written (x)
can not change the tuple inside members, but the members themselves may be varied tuple:
S = (1,2, [1,2])
S [2] = "hello" being given
s [2] [1] = 3 surface is not given, the tuple element does change, but in fact not change the tuple element, but the elements inside the list, beginning tuple the list has not changed to point to another list, or point to the original point, we can call it so-called "no change"
tuple immutable, relatively safe, try to use an alternative list to replace tuple list
4.dict dictionary:
The dictionary by the key and a value, key - value pairs called terms. Between the key and value separated by a colon, enclosed in braces.
For example, {1: 'peter', 2 : 'lisa'} is a dictionary. Dict order but the order data and our members do not necessarily defined, we need only remove items when the delete key.
a.dict can not be accessed via the following table (the index), only through the key.
b. Use pop function deletes, x.pop (key)
c. modifier keys corresponding value when it is time to visit with the key assignment, but the key can not be changed, but the dictionary key is unique and can not be repeated.
x = {1: 'a' , 2: 'b'}
Delete: x.pop (1).
Review: x [1] = 'c '.
D. keys must be hash, the key is a constant.
e.get method of: determining whether a key is present:
x.get (1), whether there is a key, if present, None is returned.
x.get (1, "key not exist "), if not, an output message back.
f. Members of key dict add, delete operation when dict hash table structure will change, members of the storage order will change, there will be chaos when traversal, as it has been traversed members may be again traversal.
For example:
Y = {. 1: 'A', 2: 'B'}
for Y in Key:
y.pop (Key)
Print (Key)
this error is reported.
In this case, it can be resolved:
We can take out members of the key dict placed among a list or other container, and then we traverse the entire list, remove the key, according to delete dict key, so as not to traverse after deleting changed dict.
. 1 = {Y: 'A', 2: 'B',. 3: 'C'}
List = []
for Y in Key:
list.append (Key)
Print (List)
for value in List:
IF value. 1 == :
Print (Y [value])
y.pop (value)
Print (Y)

5.set set
1. Definitions and Usage:
a. Set dict and the like, which is a set of key, but not stored value, two key properties are the same, the key element can not be modified, but the element itself can be modified , and almost tuple.
b.set definition requires as input a set list: SS = SET ([2,3,4])
c.set the key is disordered, and therefore can not be accessed by index, but can be accessed by conversion into the list .
d. You can add function by adding elements may be added repeatedly, but repeating the added element is invalid, which means that no duplicate set of elements.
e. Delete function by remove elements throw an exception if it does not exist, if you do not let it throw an exception, we can use dischard function
f.pop delete function can be achieved, but not the same method, which is in turn removed from the top . ss.pop ()

Calculate intersection and union 2.set:
SS1 = SET ([1,2,3,4])
SS2 = SET ([2,3,4,5,6])
SS = SS1 & SS2 -------- --------> intersection calculation result 2,3,4} {
SS = SS1 | SS2 ---------------------> and set operations.

function:

1. Built-in functions:
Built-in functions including the function name, parameters (parameters note type), and returns the value (or may not return values). These built-in functions are like inside the library that comes with python.
ABS: Results value = abs (-10) is 10: the absolute value function
2. custom functions:
1. Custom function is a function defined in terms of our own needs.
2. We define such a function when you need to use def statement, and a write function name, parentheses, brackets can write parameters written after a colon, and then write the function body in the indented block them, then you can return a value.
myabs DEF (value):
IF value> = 0:
return value
the else:
return -value
attention indentation! ! ! ! !
3. If the function body thought well how to write, then we can write a function in the pass inside.
3. Higher order functions
may receive the function parameters as a function of higher order function is
a.map function: a function f and a reception list, and the function f are sequentially by acting on each element of the list, and obtain a new list Back
map (f, [l, 2,3])
b.reduce functions: map and use the same, it must receive two parameters f, the reduce () for each element of the list of frequently called function f, and returns the final result value.
reduc sum may be used.
c.filter functions: a receiving function f and a list, the role of this function f is determined for each element, returns True or False, filter () automatically filters out elements meet the conditions according to the determination result returned by qualified the new list of elements, which must function as a Boolean function.
d sort function:. sorted, can be customized, the default is ascending order.
sorted (iterable, key = None, reverse = False), iterable objects iteration, key elements to perform the comparison, reverse ascending and descending, False Descending, True ascending

class

1. Definition of the class:
class Style (Object):
...
2. constructors:
We have a fixed constructor, all classes are true: DEF the init (Self, ...):
DEF the init (Self, name, Sex) :
the self.name name =
self.sex Sex =
3. destructor:
similar: DEF del (Self, ...):
4. attribute definition:
attributes can be defined directly, for example, directly written in the line following class: name = "Peter", which is equivalent to define a name attribute, which is equivalent to public property.
Or we can define the constructor function, for example:
DEF the init (Self, name, sex):
self.name = name
self.sex = sex
there is equivalent to define the name and sex of the property, but only in class inside access, equivalent to private.
The method defined:
Definition Format: def method name (Self, ...):
DEF BMethon (Self, args):
Super (B, Self) .AMethod (args)
6. The succession:
Format: class subclasses (parent):
subclasses of the parent class can use to call through Super:
class B (A):
DEF BMethon (Self, args):
Super (B, Self) .AMethod (args)

Published 22 original articles · won praise 27 · views 2853

Guess you like

Origin blog.csdn.net/weixin_44346470/article/details/100146075