Integer, floating point, string, Boolean, null (None); print statement note: 1. When we write code in a Python interactive environment, >>> is the prompt of the Python interpreter, not part of the code. 2. When writing code in a text editor, never add >>> yourself. The print statement can also follow multiple strings separated by commas (,) to form a string of output. Print prints each string in turn, printing a space when a comma is encountered. Python comments begin with a # and continue until the end of the line. Multi-line comments are in triple quotation marks ”’ ”’. A variable name is a combination of uppercase and lowercase letters, digits, and underscores (_), and cannot start with a number. 5. String (1) Strings can be expressed in brackets of “” or “”. Note: If the string contains “, we can enclose “. Similarly, if the string contains’, we can enclose “”. Escape some special characters of the string if the string contains both ‘and’. Python strings are escaped with \. Such as:

#LiMing said “I’m a gay”! LiMing said/” I’m a gay/ “! (2) Raw string and multi-line string characters in raw string do not need to escape, r ‘… ‘represents a single line character, r “”… The table has multiple rows. Unicode consolidates all languages into one code, so that there is no garble anymore. Unicode usually uses two bytes to represent a character, and the original English encoding is changed from a single byte to a double byte by filling all the high bytes with zeros. Print u’ id ‘: print u’ id’ Ur “” Python Unicode strings support” Chinese “, “Japanese “,” Korean “and many other languages. List (1) LIST is an ordered collection in which elements can be added and removed at any time. Enclosing all the elements of a list with [] is a list object. (2) Access list by index (similar to array). For example: L = [95.5, 85, 59]print L[-1] print L[-2] print 85print L[-3] print 95.5 Append () always adds new elements to the end of the list. The insert() method, which takes two arguments, the first being the index number and the second being the new element to be added. (5) Delete elements. The pop() method returns the deleted element. A tuple is another kind of ordered list. A tuple is very similar to a list, but once a tuple is created, it cannot be modified. The only difference between creating a tuple and creating a list is that [] is replaced by (). The tuple element is obtained in exactly the same way as the list element. (2) Create a tuple. T = (1,); t = (1,); t = (1,); For example: (1) if score>60: print ‘passed’#if-elif-elseif age >= 18: print ‘adult’elif age >= 6: print ‘teenager’elif age >= 3: Print ‘kid’else:print ‘baby’ for loop L = [‘Adam’, ‘Lisa’, ‘Bart’]for name in L:print name (3) while N = 10x = 0while x < N: print x = x + 1 (4) The function of a dict is to establish a mapping relationship between a set of keys and a set of values. A dict key cannot be duplicated. For example: d = {‘Adam’: 95, ‘Lisa’: 85, ‘Bart’: 59} Extension: Len () can calculate the size of any set. (1) Access dict. Use d[key] to find the corresponding value. Note: A dict value is accessed through the key, and the dict returns the value as long as the key exists. If the key does not exist, KeyError is reported. There are two ways to avoid KeyError: first, check whether the key exists, using the IN operator. Second, use a get method provided by dict itself, and return None (2) if the Key does not exist. The first feature of dict is fast lookup, and the second feature of dict is that the stored key-value pairs are out of order. A third feature of dict is that the elements used as keys must be immutable, so lists cannot be used as keys. Dict example: for key in D :… A set holds a list of elements, much like a list, but the elements of a set are non-repetitive and unordered, much like dict keys. (1) Create a set by calling set() and passing in a list. The elements of the list will be the elements of the set:

S = set([‘A’, ‘B’, ‘C’]) (2) Sets have A similar internal structure to dict, except that they do not store values. A set stores elements that, like a dict key, must be immutable. S = set([‘Adam’, ‘Lisa’, ‘Bart’])>>> for name in s:… Print name (4) update the set add elements, use the set of the add () method: if you add elements already exists in the set, the add () is not an error, but will not add: delete the elements in the set, use the set of the remove () method: Remove () reports an error if the deleted element does not exist in the set. Functions can be documented directly from Python’s official website: the web link also provides help for the ABS function at the interactive command line through help(abs). To define a function, use the DEF statement, write the function name, parentheses, arguments in parentheses, and colon:, and then write the function body in an indent block. The return value of the function is returned by the return statement. Return None can be shortened to return. Python functions that return multiple values actually return a tuple. (2) recursive function example: Hannotta problem function move(n, a, b, C) is defined to move N disks from A to C with the help of B. 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) The second argument to the int() function is converted to base. If not, it defaults to decimal (base=10). If passed, the argument passed is used. The name of a variable parameter is preceded by a sign. We can pass zero, one, or more arguments to a variable parameter. The Python interpreter assembles a tuple from the set of arguments passed in to the mutable arguments. Select (1) [‘Adam’, ‘Lisa’, ‘Bart’, ‘Paul’] L[0:3] or L[:3] from index 0 to index 3. So the result is [‘Adam’, ‘Lisa’, ‘Bart’] L[:] means from beginning to end, and L[:] actually copies a new list. The slicing operation can also specify a third argument: L[::2][‘Adam’, ‘Bart’] the third argument means that every N elements are taken. The above L[::2] will take one element in every two, i.e. every other element. Replace a list with a tuple, and the slicing operation is exactly the same, except that the result of slicing is also a tuple. (2) reverse slice L = [‘ Adam ‘, ‘Lisa’, ‘Bart’, ‘Paul] > > > L [- 2:] [‘ Bart’, ‘Paul] > > > L [: – 2] [‘ Adam’, ‘Lisa’] > > > L [1-3: -] [‘ Lisa ‘. ‘Bart’]>>> L[-4:-1:2][‘Adam’, ‘Bart’] (3) Slicing strings’ XXX ‘and Unicode strings u’ XXX’ can also be viewed as a kind of list, where each element is a single character. Therefore, strings can also be sliced, but the result is still a string. * note:

  1. Ordered collections: list, tuple, STR, and Unicode;
  2. Unordered set: set
  3. Index iteration L = [‘Adam’, ‘Lisa’, ‘Bart’, ‘Paul’]>>> for index, name in enumerate(L):… print index, ‘-‘, name… The 0-adam1-lisa2-bart3-Paul Enumerate () function automatically turns each element into a tuple (index, element) that iterates to get both the index and the element itself. (2) Iterate over the dict value
  4. The values() method actually converts a dict into a list of values.
  5. But the itervalues() method does not convert; it takes values from the dict in turn as it iterates, so itervalues() saves less memory than values() to generate a list.

    (3) Iterate over dict keys and values

    The items() method converts the dict object into a list of tuples.

    Iteritems () doesn’t convert dict to list, but instead keeps giving tuples during iteration, so iteritems() doesn’t take up extra memory.

    Nine, lists,

    (1) Generate a list

    Method one is loop:

    L = []>>> for x in range(1, 11):… L.append(x x)… >>>

    L[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

    But the loop is too tedious, and the list generator can generate the list with a single line instead of a loop:

    [x
    x for x in range(1, 11)][1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

    (2) Complex expressions

    d = { ‘Adam’: 95, ‘Lisa’: 85, ‘Bart’: 59 }

    In the generated table, please mark the score in red for those who failed.

    Tip: Red can be implemented.

    We can get cleaner code if we replace the string formatting code with a function:

    def generate_tr(name, score):

    return ‘%s%s’ % (name, score)tds = [generate_tr(name, score) for name,

    score in d.iteritems()]

    In this way, you just need to modify the generate_tr() function, marking score red if necessary.

    d = { ‘Adam’: 95, ‘Lisa’: 85, ‘Bart’: 59 }def generate_tr(name, score):

    if score < 60:

    return ‘%s%s’ % (name, score)

    return ‘%s%s’ % (name, score)tds = [generate_tr(name, score) for name,

    score in d.iteritems()]print ”print ”

    print ‘\n’.join(tds)print ‘
    Name Score



    (3) Conditional filtering for example:

    def toUppers(L):

    Return [s.upper() for sin L if isinstance(s, STR)] #isinstance(x, STR);

    Print toUppers ([‘ Hello ‘, ‘world’, 101]) # output [‘ Hello ‘, ‘world’]