Variables and Constants

variable

Python is a dynamic language, which means that the type of Python variables themselves is not fixed. You don’t declare variables before you use them in Python (don’t write something like int a; ), assign an initial value to it before it is first used (use a = 0 directly).

constant

In fact, there are no constants defined in Python syntax.

However, PEP 8 defines the naming convention for constants as uppercase letters and underscores. In practice, there is nothing to prevent other code from modifying or deleting a “constant” the first time it is assigned.

To use real constants, implement one yourself, for example, constant-in-Python.

A null value

Python uses None to represent null values. None is not displayed on the interactive command line, but can be printed with print() :

>>> None
>>> a = None
>>> a
>>> print(a)
None
Copy the code

Boolean value

Python has Boolean values True and False.

True value problem

False: False, None, 0, ”, [], {},… ; The remaining values are true.

Boolean value related operations

Logical operator Which is equal to
and &&
or `
not !

⚠️【 Note that ‘and’ has a higher priority than ‘or’.

Comparison operator
<.>.= =.! =

The result of using the comparison operator is a Boolean (True or False).

Using a logical operator does not necessarily result in a Boolean:

The specific operation can refer to the following table generated by this procedure:

# * * note that is the value of the first column and | or the value of the first line! 支那
li = ['and'.'or']
ls = [True.False.None.0.1.2.'"abc"']

for opt in li:
    # head
    print('<%s>' % opt, end='\t')
    for j in ls:
        print(j, end='\t')
    print('\n')

    for i in ls:
        # col
        print(i, end='\t')
        for j in ls:
            # row
            print(
                    eval('%s %s %s' % (i, opt, j)),
                    end='\t'
                    )
        print('\n')
    # end
    print('\n-------\n')
Copy the code

As you can see, the rule of and is:

Both before and after are true, after return; Before and after both have a false, return false; Before and after both are false, return before;

The rules of or are:

Before and after both are true, return before; There is a truth between the two before and after, which returns to truth; Both before and after are false, after return;

In addition, the rules for NOT are:

Return False if the object is True

digital

int, float

Python has two types of numbers built in: int and float.

digital meaning Said the scope of precision
int The integer There’s no limit to the size It’s always accurate
float Floating-point number (based on binary There is a certain size limit, after which is expressed as INF Same as C, it’s not accurate

The plural

Python also has built-in support for complex numbers, using the suffix J or J for the imaginary part (for example, 3+5j).

>>> a = 3 + 1j
>>> b = 3 - 1j
>>> a * b
(10+0j)
>>> 
Copy the code

See the official documentation for details on this.

Other number types

In the library, Python also has support for other numeric types such as exact Decimal (a Decimal based floating point number) and Fraction.

Decimal (Decimal)

In Python’s standard library, the Decimal library provides a decimal-based floating point decimal type. This number type fixes the inaccuracy of float and allows for more precise (but not absolutely accurate) mathematical calculations with DECIMAL.

>>> from decimal import *
>>> 0.1 + 0.1 + 0.1 - 0.3   # float
5.551115123125783 e-17       # This result is not accurate
>>> Decimal(0.1) + Decimal(0.1) + Decimal(0.1) - Decimal(0.3)   # decimal
Decimal('2.775557561565156540423631668 e-17')    # More accurate
>>> getcontext().prec = 12    # limits the number of Decimal places
>>> Decimal(0.1) + Decimal(0.1) + Decimal(0.1) - Decimal(0.3)
Decimal('1.11022302463 e-17')
Copy the code

As in the previous example, to use the Decimal type,

  • First of all,import decimal;
  • And then usedecimal.Decimal(Num)To get a Decimal instance, where Num can be one of the following:
>>> Decimal('3.14')     The # content is the string of float
Decimal('3.14')
>>> Decimal((0, (3.1.4), -2))  # tuple (sign, digit_tuple, exponent) : (-1) * sign * digit_tuple: (10 ^ exponent
Decimal('3.14')
>>> Decimal(314)        # int, float is fine
Decimal('314')
>>> Decimal(Decimal(314))  # Another instance of Decimal
Decimal('314')
>>> Decimal(3.14 \ \ 'n')    You can have whitespace before and after #
Decimal('3.14')
Copy the code
  • Decimal.getcontext ().prec represents the significant digit,

    • throughprint(decimal.getcontext().prec)To view the current value. The default is 28 bits
    • throughdecimal.getcontext().prec = PlacesTo set the number of significant bits, the precision value is[1, MAX_PREC], the value of MAX_PREC is yes on 64-bit machines999999999999999999, 32 bits425000000(This is because the value needs to be an integer that can be converted to C, seePython version of the source code)!
  • Add, subtract, multiply and divide

A Fraction is a Fraction.

In the fractions library, the type Fraction is defined to express fractions, and the operation of addition, subtraction, multiplication and division is taken into account.

The use method is as follows:

>>> from fractions import *
>>> Fraction(1.5)    # Pass float, and the score representation is automatically computed
Fraction(3.2)
>>> Fraction(1.3)   # in the numerator and denominator
Fraction(1.3)
>>> Fraction(2.6)   # Default will be physicalized
Fraction(1.3)
>>> Fraction(2.6, _normalize=False)    # Specifies no physicochemical
Fraction(2.6)
>>> Fraction(Fraction(1/11))    # Another Fraction instance, as well as Decimal instances
Fraction(3275345183542179.36028797018963968)
>>> Fraction('22/7')    # Use a string representing fractions, note numerator/denominator, no Spaces between them, and white space before and after them
Fraction(22.7)
Copy the code

string

Representation of strings

In Python, strings can be enclosed in single quotes (‘… ‘) or double quotes (“…”) ) to identify a string within a single line. You can also use three consecutive single/double quotes (” “… “‘ or” “”…” “”) to represent and format multi-line characters.

Python does not have a single character type; A character is simply a string of length 1.

>>> st = '1\
... 2\
... 3\
... a'
>>> st
'123a'
>>> st = "' 1.2
.3
.a
.' ' '
>>> st
'1\n2\n3\na\n'
>>> 
Copy the code

⚠️ [Note] single quotes can contain double quotes, ‘asd”123″ FGH ‘is allowed, as can “””.

A character encoding

First, attach a comparison of several character encodings:

coding The length of the ‘A’ ‘in’
ASCII 1 Byte 01000001 (No such character)
Unicode It’s usually 2 bytes 00000000 01000001(ASCII zero fill) 01001110, 00101101,
UTF-8 Variable (1~6 bytes) 01000001(UTF-8 contains ASCII) 11100100 10111000 10101101

Python3.x encodes strings in Unicode by default.

Functions that encode <=> characters:

  • ord(): Gets the integer representation of the character;
  • chr(): Converts the encoding to the corresponding character;

Such as:

>>> ord('A')
65
>>> ord('in')
20013
>>> chr(66)
'B'
>>> chr(20014)
'丮'
Copy the code

The Python string type is STR.

STR is represented in memory as Unicode, with one character corresponding to several bytes.

In writing the second level cache (- > local hard disk | remote – > network), the STR will into bytes.

Bytes Indicates the unit of bytes.

Python uses single/double quotes with a b prefix for bytes.

str bytes
'ABC' b'ABC'

str <=> bytes:

  • encode(): str –> bytes
>>> 'abc'.encode('ascii')
b'abc'
>>> 'Chinese'.encode('utf-8')
b'\xe4\xb8\xad\xe6\x96\x87'
>>> 'Chinese'.encode('ascii')    # out of range
''' Traceback (most recent call last): File "
      
       ", line 1, in 
       
         UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128) '''
       

Copy the code
  • decode(): bytes –> str
>>> b'abc'.decode('ascii')
'abc'
>>> b'\xe4\xb8\xad\xe6\x96\x87'.decode('utf-8')
'Chinese'
>>> b'\xe4\xb8\xad\xe6\x96\x87'.decode('ascii')    # out of range
''' Traceback (most recent call last): File "
      
       ", line 1, in 
       
         UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position 0: ordinal not in range(128) '''
       
>>> # Decode () error if bytes contains bytes that cannot be decoded;
>>> # You can pass in 'errors='ignore' when calling decode() to ignore error bytes.
>>> b'\xe4\xb8\xad\xe6\x96\x87asd'.decode('ascii', errors='ignore')
'asd'
Copy the code

⚠️ [Note] To avoid garbled characters, always convert STR and bytes using UTF-8 encoding.

Escape character

Escape characters can be used in Python strings, as shown in the following table:

Escape character describe
\(at the end of the line) Line continuation operator
\ \ Backslash notation
\ ' Single quotes
\" Double quotation marks
\a Ring the bell
\b Backspace (Backspace)
\e escape
\ 000 empty
\n A newline
\v Vertical TAB
\t Horizontal TAB
\r enter
\f Change the page
\xxx Octal numbers, for example:'\ 100'On behalf ofThe '@'
\oyy Octal numbers, yy represents characters, such as:'\o12'On behalf of the line
\xyy A hexadecimal number, yy represents a character, such as:'\x0a'On behalf of the line
\uxxxx A hexadecimal number. XXXX represents a character, for example:'\u4e2d\u6587'On behalf of'Chinese'
\other Other characters are printed in normal format, such as:'\sds'On behalf of'\\sds'

To unescape, prefix the string r:

>>> print('C:\some\name')  # here \n means newline!
C:\some
ame
>>> print(r'C:\some\name')  # note the r before the quote
C:\some\name
Copy the code

Basic string operations

Get string length

Python’s built-in len() function can get the length of multiple types of objects, including strings.

>>> len(word)
6
>>> This method is equivalent to:
>>> word.__len__()
6
Copy the code

String concatenation

  • Two adjacent strings of text are automatically concatenated together.
>>> 'Py' 'thon'
'Python'
>>> This function can be used to write long strings:
>>> text = ('Put several strings within parentheses '
            'to have them joined together.')
>>> text
'Put several strings within parentheses to have them joined together.'
Copy the code
  • A string of+*

Strings can be concatenated (stuck together) by the + operator, and can be repeated by *.

>>> # 3 times 'un', followed by 'ium'
>>> 3 * 'un' + 'ium'
'unununium'
Copy the code

String interpolation

There are four main ways to interpolate strings:

  1. String concatenation
>>> a = 123
>>> "a is " + str(a) + ":)" 
'a is 123:)'
Copy the code
  1. %Tuples interpolation
>>> a = 123
>>> b = 66.77
>>> c = 'hello'
>>> 'a = %s, b = %s, c = %s' % (a, b, c)
'a = 123, b = 66.77, c = hello'
Copy the code
  1. A string offormatmethods
>>> 'a = {arg_a}, b = {arg_b}, c = {arg_c}'.format(arg_a="Oriental", arg_b=123, arg_c=333.44+8j)
'c = (333.44+8j)'
Copy the code

Or it can be anonymous:

>>> 'Another way: {0}, {2}, {1}, {3}'.format("zero".2.1.0.3)
'Another way: zero, 1.0, 2, 3'
Copy the code
  1. f-string

Python 3.6 introduced f-string to make interpolation more elegant:

>>> a = 123
>>> b = 456.789
>>> f'{a} + {b} = {a+b}'
'123 + 456.789 = 579.789'
Copy the code

For more information on F-String, see this RealPython article or check out the source of F-String: PEP 498 — Literal String Interpolation.

String segmentation

The split method of a string can be used to split a string with the specified string:

>>> 'a b c'.split(' ')
['a'.'b'.' '.' '.'c']
>>> 'he-*-ll-*-o--'.split('- * -)
['he'.'ll'.'o--']
Copy the code

String substitution

Part of a string can be replaced with the string’s replace method:

>>> 'he-*-ll-*-o--'.replace('- * -.'... ')
'he... ll... o--'
Copy the code

String index and slice

  • The index
character P y t h o n
Positive index Zero (0) 1 2 3 4 5
Inverted index – 6 – 5 4 – – 3 2 – – 1
>>> word = 'Python'
>>> word[0]  # character in position 0
'P'
>>> word[-2]  # second-last character
'o'
Copy the code
  • slice

Indexes are used to get a single character, and slicing lets you get a substring.

The rule for slicing is as follows: STR [start: End: interval] * Start: the beginning index (fetch), which is 0 by default * End: the end index (not fetch), by default, the last character of the string (fetch) * Interval: the number of intervals after each fetch (>0), which is 1 by default. If the value is negative, the interval is inverted

>>> word[0:2]  # characters from position 0 (included) to 2 (excluded)
'Py'
>>> # Several common modes:
>>> word[1: -1]    # Remove the first character (can be used to remove parentheses, quotes)
'ytho'
>>> word[::-1]    # String reverse
'nohtyP'
Copy the code

⚠️ [Note] The slice contains the beginning character, not the end character. S [: I] + s[I :] == s ⚠️

Regular expressions

You can’t use strings to get around regular expressions. Python has a built-in regular expression module, Re.

We’re not going to show you how to write regular expressions here, just how to do common regular expression operations in Python. There are problems with the re itself, please find other resources to learn.

Match:

import re
pattern = r'abc(.*?) def'	# Have a lot of '\' in the re, use the r string to cancel escape
test = 'abc123def'
if re.match(pattern, test):
    print('ok')
else:
    print('failed')
Copy the code

Extract:

import re
pattern = r'abc(.*?) def(\d+)'
test = 'abc123def456'
m = re.match(pattern, test)
if m:
    print(m.groups())
else:
    print('failed')
Copy the code

The extracted groups(‘123’, ‘456’) can be obtained by using m.group ().

Segmentation:

# segmentation
re.split(r'[\s\,\;] + '.'a,b;; c d')
Copy the code

Collection types

In my mind, a string is also a collection type (if you’ve learned C, a string is just a list of characters). So, a lot of the operations that we’ve just done with strings will apply to the list that follows.

list

List: list, written in [].

>>> l0 = []
>>> l1 = [1.2.3]
>>> l2 = list("hello")
>>> print(f'{l0}\n{l1}\n{l2}')
[]
[1.2.3]
['h'.'e'.'l'.'l'.'o']
Copy the code

Index & Slice:

  • The get:LST [index | | slice]
  • Set:LST [index | | slice] = value
>>> L [0] = 3.14 >>> L [0] 3.14Copy the code

Index & Slice and string are the same, you can go back here.

Let’s look at the basic operation of list:

Lst.append (value), lst.extend(iterable)

>>> l = []
>>> l.append(12)
>>> l.append("abc")
>>> l.append(999)
>>> l.append([3.4])
>>> l.extend(['you'.'good'])
>>> l.extend({'then': 1.'see': 2})
>>> l
[12.'abc'.999[3.4].'you'.'good'.'then'.'see']
Copy the code

Append and Extend add a single element and a list of elements.

With slicing, append is equivalent to LST [len(LST):] = [value], and extend LST [len(LST):] = iterable.

Insert: lst.insert(index, value)

>>> l = []
>>> l.insert(0.100)
>>> l.insert(len(l), 200)       # equivalent to L. apend (200)
>>> l.insert(1.300)
>>> l.insert(1.400)
>>> l
[100.400.300.200]
Copy the code

Delete: lst.remove(value), lst.pop(index), clear()

Remove is to remove a value that exists in the list. If it does not exist, ValueError is reported.

Pop deletes the value in the list at the given index. If the index is out of bounds, IndexError is reported.

Clear is to clear (delete) all elements. You can do something similar with del a[:].

>>> l
[100.400.300.200]
>>> l.remove(400)
>>> l
[100.300.200]
>>> l.pop()		Pop (-1) or pop(len(l)-1)
200
>>> l.pop(0)
100
>>> l
[300]
>>> l.remove('fool')
Traceback (most recent call last):
  File "<stdin>", line 1.in <module>
ValueError: list.remove(x): x not in list
>>> l.pop(999)
Traceback (most recent call last):
  File "<stdin>", line 1.in <module>
IndexError: pop index out of range
>>> l.clear()
>>> l
[]
Copy the code

Other operations:

  • list.index(x[, start[, end]]): You give the value, it returns the index
  • list.count(x): You give the value and it tells you how many
  • list.sort(key=None, reverse=False): a relatively fast address sort
  • list.reverse(): The list is reversed, and the tune is turned on.
  • list.copy(): Return one of your ownShallow copy.

There are so many things you can write about lists that you could write a separate article on them… (I’ll talk about it later, maybe I’ll write it after the review data structures class.)

tuple

Tuple: A tuple, similar to a list, but often written inside ().

Tuple can get, not set. That is, no append, no pop, no index assignment.

>>> t = (1.2.3)
>>> t[1] = "sdfdsf"
Traceback (most recent call last):
  File "<stdin>", line 1.in <module>
TypeError: 'tuple' object does not support item assignment
>>> t
(1.2.3)
>>> t.append(12)
Traceback (most recent call last):
  File "<stdin>", line 1.in <module>
AttributeError: 'tuple' object has no attribute 'append'
>>> t.pop()
Traceback (most recent call last):
  File "<stdin>", line 1.in <module>
AttributeError: 'tuple' object has no attribute 'pop'
>>> t[1:]
(2.3)
Copy the code

Note that I just wrote “tuples are always in ().” Why are tuples always in parentheses? If you have this question, give yourself a chance to turn the new fast, read the document: docs.python.org/3/tutorial/… .

Here it is:

A tuple consists of a number of values separated by commas.

Meaning: “A tuple is a series of values separated by commas!” If you don’t use parentheses, look at this example:

>>> t = 12345.54321.'hello! '
>>> t[0]
12345
>>> t
(12345.54321.'hello! ')
>>> # Tuples can be nested:
.u = t, (1.2.3.4.5)
>>> u
((12345.54321.'hello! '), (1.2.3.4.5))
>>> # Tuples immutable:
.t[0] = 88888
Traceback (most recent call last):
  File "<stdin>", line 1.in <module>
TypeError: 'tuple' object does not support item assignment
>>> # But can contain variable elements:
.v = ([1.2.3], [3.2.1])
>>> v
([1.2.3], [3.2.1])
Copy the code

As you can see, tuples are useful in Python for packaging and passing a series of elements, such as function arguments!

set

A set is an unordered set that guarantees unique elements.

We usually use it to eliminate duplication and ensure uniqueness. Of course, you should know that a set corresponds roughly to a set in mathematics, so a set can be used for union, intersection, difference, and complement (which, as you can imagine, can’t be used for mathematical complement, but can be used for symmetry difference).

There are two ways to create a set: the set() function and using curly braces {ele1, ele2,… }. But if you want to empty a set, you can only use set(), not {}! Because you should know that {} builds an empty dictionary.

>>> s = {}
>>> type(s)
<class 'dict'> > > >s = set() > > >type(s)
<class 'set'> > > >s1 = set([1.2.3]) > > >s1{1, 2, 3} > > >s2= {3, 4, 5, 5} >>>s2{3, 4, 5} > > >type(s2)
<class 'set'>
Copy the code
>>> a
{1.2.3}
>>> b
{3.4.5}
>>> a | b    # and, similar to "logic or" : in a or b or both
{1.2.3.4.5}
>>> a & b    # intersection, similar to "logical and" : in a and in B
{3}
>>> a - b    # difference, similar to "logical difference" : in A not in B
{1.2}
>>> a ^ b    Symmetric difference, similar to "logical xor" : either in A or in B, but not both
{1.2.4.5}
Copy the code

dict

Dict: dictionaries, key-value pairs, and the underlying implementation is hash tables. The literals are {key1: value1, key2: value2,… }.

Since dict is written the same as set {}, as you can imagine, dict also guarantees uniqueness — dict guarantees keys to be unique.

A key can be any “immutable” value, that is, a number, a string, or a tuple containing no mutable elements.

>>> d = {1: 'abc'.'2': 2.0001}
>>> d[1]
'abc'
>>> d['2']
2.0001
Copy the code
>>> tel = {'jack': 4098.'sape': 4139}
>>> tel['guido'] = 4127
>>> tel
{'jack': 4098.'sape': 4139.'guido': 4127}
>>> tel['jack']
4098
>>> del tel['sape']		# Delete element
>>> tel['irv'] = 4127
>>> tel
{'jack': 4098.'guido': 4127.'irv': 4127}
>>> list(tel)			# take key
['jack'.'guido'.'irv']
>>> sorted(tel)
['guido'.'irv'.'jack']
>>> 'guido' in tel		Is the # key in the dictionary
True
>>> 'jack' not in tel
False
Copy the code

Dict () ¶ Dict () is a dict() function for more dictionary initialization techniques.

>>> dict([('sape'.4139), ('guido'.4127), ('jack'.4098)])
{'sape': 4139.'guido': 4127.'jack': 4098}
>>> dict(sape=4139, guido=4127, jack=4098)
{'sape': 4139.'guido': 4127.'jack': 4098}
Copy the code

The derived type

Comprehensions are used to create instances of a collection type.

For example, if you want to create a “list of squares from 1 to 10,” how do you write the code?

Of course, the data is small, and we can certainly do this:

a = [1.4.9.16.25.36.49.64.81.100]
Copy the code

But what if it’s 1 to 100,1 to 100,000? You want to use a loop right:

>>> a = []
>>> for i in range(1.101) :.    a.append(i**2)
.
Copy the code

But that’s not simple enough!

“List of squares from 1 to 10” is just one sentence, and the code should be a simple one line! That’s what the derivation does:

>>> [x**2 for x in range(1.11] [1.4.9.16.25.36.49.64.81.100]
Copy the code

The general form of the derivation is:

[Any expressionfororifOther]Copy the code

Here’s an example to give you a good impression:

>>> [(x, y, x*y) for x in [1.2.3] for y in [3.1.4] ifx ! = y] [(1.3.3), (1.4.4), (2.3.6), (2.1.2), (2.4.8), (3.1.3), (3.4.12)]
>>> # equivalent to:
>>> combs = []
>>> for x in [1.2.3] :.    for y in [3.1.4] :.        ifx ! = y:.            combs.append((x, y, x*y))
...
>>> combs
[(1.3.3), (1.4.4), (2.3.6), (2.1.2), (2.4.8), (3.1.3), (3.4.12)]
Copy the code

Actually, exactly what we just wrote is a list derivation. We also have set comprehensions and even dict comprehensions.

>>> {x for x in 'abracadabra' if x not in 'abc'}
{'r'.'d'}
>>> {x: x**2 for x in (2.4.6)}
{2: 4.4: 16.6: 36}
Copy the code

You might also want to write this:

>>> (x**2 for x in range(1.11))
<generator object <genexpr> at 0x107988bd0>
Copy the code

Ha ha, it’s a little different, this time it gives you a generator — a generator, that’s not a derivation, I’m not going to do it here, we’ll talk about that later.

Finally, two interesting examples:

>>> [[(j, i, j*i) for j in range(1, i+1)] for i in range(1.10)] or>>> [(j, i, j*i) for i in range(1.10) for j in range(1, i+1[[()]1.1.1)], [[1.2.2), (2.2.4)], [[1.3.3), (2.3.6), (3.3.9)], [[1.4.4), (2.4.8), (3.4.12), (4.4.16)], [[1.5.5), (2.5.10), (3.5.15), (4.5.20), (5.5.25)], [[1.6.6), (2.6.12), (3.6.18), (4.6.24), (5.6.30), (6.6.36)], [[1.7.7), (2.7.14), (3.7.21), (4.7.28), (5.7.35), (6.7.42), (7.7.49)], [[1.8.8), (2.8.16), (3.8.24), (4.8.32), (5.8.40), (6.8.48), (7.8.56), (8.8.64)], [[1.9.9), (2.9.18), (3.9.27), (4.9.36), (5.9.45), (6.9.54), (7.9.63), (8.9.72), (9.9.81)]]
Copy the code

The multiplication table, it works the same either way.

>>> matrix = [
.    [1.2.3.4]..    [5.6.7.8]..    [9.10.11.12]..]
>>> [[row[i] for row in matrix] for i in range(4)], [[1.5.9], [2.6.10], [3.7.11], [4.8.12]]
Copy the code

That’s right! The transpose of a matrix can be done using just one line of code in the derivation.


To be continued…

Next: [Python process Control]