Variable
1. Rules for variable definitions:
Variable names can only be any combination of letters, numbers, or underscores
The first character of a variable name cannot be a number
The following keywords cannot be declared as variable names
[' and ', ' as ', ' assert ', ' Break ', ' class ', ' Continue ', ' Def ', ' del ', ' elif ', ' Else ', ' except ', ' exec ', ' finally ', ' for ', ' F ' Rom ', ' Global ', ' if ', ' import ', ' in ', ' was ', ' lambda ', ' not ', ' or ', ' pass ', ' print ', ' raise ', ' return ', ' try ', ' while ', ' WI Th ', ' yield ']
2. Assigning values to variables
Python internal digital Buffer pool (-5 257)
Does not consider Python's own memory optimization
String Assignment modified name2=name1, if name1 modified, name2 unchanged
String re-assignment, memory re-opening
Input
Name = Raw_input ("Input:"). Strip () # input string variable
num = Int (raw_input ("Input:"). Strip ()) # input string str to int type
String
String Common functions:
- Remove whitespace
- Segmentation
- Length
- Index
- Slice
"List" []
1. Create a list
Quick Create List, two ways: The Split method, the list function and the range function are used together.
Split method. Write a string, separating the characters with a space, and then use the Split method on the string.
A_list = ' A b c d e F g '. Spit ()//Create List [' A ', ' B ', ' C ', ' d ', ' e ', ' f ', ' G '], but this is a lot more concise
The list function is used in conjunction with the range function. You can quickly create a very large list.
A_list = List (range (100))//easy to create a list of 0 to 99
The index of the first character is 0, and the index of the last character is –1
2. Basic Operation:
- Index
- Slice
- Additional
- Delete
- Length
- Slice
- Cycle
- Contains
2. List type built-in function
List.append (obj) # Add an object to the list obj
List.count (obj) # returns the number of times an object obj appears in the list
List.extend (SEQ) # Add the contents of the sequence SEQ to the list
List.index (Obj,i=0,j=len (list)) # returns the K value of list[k] = = obj, and the range of K in i<=k<j; otherwise exception (# #取出在列表中的位置)
List.insert (index,obj) # Inserts an object at index position obj
List.pop (index=-1) # deletes and returns the object at the specified position, which is the last object by default (# #删除时按照下标删除)
List.remove (obj) # Remove object from List obj (# #删除时按照内容删除)
List.reverse () # Flip the list in place
List.sort (func=none,key=none,reverse=false) # Sorts the members in the list in the specified way, if the Func and key parameters are specified, the individual elements are compared in the specified manner, and if the reverse flag is set to True, The list is sorted in reverse order
Note: The index of the string and list is starting from 0, and the index of the last element is –1.
"tuples"()
# #不能修改
Basic operation:
- Index
- Slice
- Cycle
- Length
- Contains
"dictionary" unordered {}
1. Common operation:
- Index
- New
- Delete
- Key, value, key-value pairs
- Cycle
- Length
AB = {' Swaroop ': ' [email protected] ',
' Larry ': ' [email protected] ',
}
Ab[' C '] = 80 # Add a dictionary element
Del ab[' Larry '] # Delete dictionary elements
Ab.keys () # View all key values ##==> list
Ab.values () # Print all Values ##==> list
Ab.has_key (' a ') # to see if a key value exists
Ab.items () # Returns the entire dictionary list
2. Dictionary built-in method
Dict.clear () # Remove all elements from the dictionary
Dict copy () # Returns a copy of the dictionary (shallow copy)
Dict.fromkeys (Seq,val=none) # Creates and returns a new dictionary, with the element in SEQ making the dictionary key, Val doing the initial value of all the key pairs in the dictionary
Dict.get (Key,default=none) # The key in the dictionary dict, returns its corresponding value, and returns the default value if the key does not exist in the dictionary
Dict.has_key (Key) # returns True if the key exists in the dictionary instead of in and not
Dicr.items () # Returns a list that contains a dictionary of key, value pairs tuples
Dict.keys () # Returns a list containing the keys in the dictionary
Dict.iter () # Methods Iteritems (), Iterkeys (), itervalues () are the same as the non-iterative methods they correspond to, but they return an iteration instead of a list
Dict.pop (Key[,default]) # is similar to method get (). If the key key exists in the dictionary, delete and return Dict[key]
Dict.setdefault (Key,default=none) # is similar to set (), but if the key key is not present in the dictionary, it is assigned by Dict[key]=default
Dict.update (DICT2) # Adds a dictionary dict2 key-value pair to the dictionary Dict
Dict.values () # Returns a list containing all the worth of dictionaries
"cycle, Judge."
1, the Loop, the Judgment statement (For,if,else) should be followed by:
2. Break continue pass and recycle else
Break
Jump out of the nearest loop (jump out of the entire loop statement)
Continue
Jumps to the beginning of the nearest loop (to the first line of the loop, skipping this cycle)
Pass
Don't do anything, just empty placeholder statements
Loop Else block
Executes only if the loop is normally left (that is, no break statement is encountered)
"The comparison"
= = Value comparison,
Is memory address pair comparison must be the same address
"Global variables and local variables"
Summarize:
A variable name inside a function is considered a local variable if it first appears and appears before =. (if no definition will be error unboundlocalerror:local variable ' num ' referenced before assignment)
If the variable name inside the function appears first and appears after =, and the variable is defined in the global domain, the global variable is referenced here. (If the variable is not defined in the global domain, there is a "variable undefined" error, of course)
A global variable is used whenever a variable is used, and the variable is defined in the global domain and not locally defined.
If the variables used are defined in the global domain and are also defined in the local domain, local variables are used by default.
If you want to assign a value to a global variable in a function, you need to declare it with the global keyword.
"Basic operation of text"
Open File:
File_obj = File ("path", "mode")
The mode of opening the file is:
- R, open the file as read-only
- W, open a file for writing only. Overwrite the file if it already exists. If the file does not exist, create a new file.
- A, open a file for append. If the file already exists, the file pointer will be placed at the end of the file. In other words, the new content will be written to the existing content. If the file does not exist, create a new file to enter it.
- w+, open a file for read-write. Overwrite the file if it already exists. If the file does not exist, create a new file.
Details are as follows:
# Load all content into memory at once
Obj.read ()
# Load all content into memory at once and split into strings based on rows
Obj.readlines ()
# Read only one row of data at a time
For line in obj:
Print Line
Write the contents of the file:
Obj.write (' content ')
To close a file handle:
Obj.close ()
"Other summary and attention"
Capture parameter Import sys argv
>>> name = ' I am {0},age {1} '
>>> Name.format (' Alex ', 19)
python--First Day Summary