Core Python: Extra

Good to know in Python

  1. 299_792_458 is interpreted as the same number as 299792458, hence we can separate any pair of digits by an underscore character “_” for clarity. (1.602_176_634e-34.)

  2. 1.67263e-7 represents the number 1:67263 * 10^(-7), 'e' or 'E' is used to separate the significand from the exponent.

  3. ** (highest precedence)

    *, /, //, %

    +, - (lowest precedence)

  4. Polymorphism: the same function, abs(), does different things to different objects. If passed a real number, x, it returns |x|, the nonnegative magnitude of that number, without regard to sign; if passed a complex number, z = x + iy, it returns the modulus, |z|.

  5. Banker's rounding: when a floating number is between 2 integers, it returns the even number).

  6. Use lower-case names, with words separated by underscores rather than “CamelCase”: for example, mean_height and not MeanHeight for variables as a good coding practice. CameCase is usually reserved for a class name.

  7. math.isclose(0.1**2, 0.01) -> isclose, to test whether two floating-point numbers are equal to within some absolute or relative tolerance. The relative tolerance can be set with the rel_tol argument.

  8. Order of precedence in the logical operators: not, and, or. But in a compound expression comparison operators are evaluated first.

  9.       # Creating complex numbers
          z1 = 3 + 4j  # 3 is the real part, 4 is the imaginary part
          z2 = 2 - 5j  # 2 is the real part, -5 is the imaginary part
    
          # Arithmetic operations with complex numbers
          addition = z1 + z2
          subtraction = z1 - z2
          multiplication = z1 * z2
          division = z1 / z2
    
          # Accessing real and imaginary parts
          real_part = z1.real
          imaginary_part = z1.imag
    
          # Conjugate of a complex number
          conjugate = z1.conjugate()
    
  10. a = 256
    b = 256
    a is b
    True
    # Python keeps a cache of commonly used, small integer objects
    # (on my system, the numbers 􀀀5 to 256).
    a = 257
    b = 257
    a is b
    False
    
  11. IPython shell is better than the Python shell

  12. Typing a single “?” outputs an overview of the usage of IPython’s main features.

  13. %quickref provides a brief reference summary of each of the main IPython commands and “magic”.

  14. help() or help(object) invokes Python’s own help system.

  15. Typing one question mark after an object name provides information about that object.

    a = [1, 2, 3]
    a?
    # Type:        list
    # String form: [1, 2, 3]
    # Length:      3
    # Docstring:
    # Built-in mutable sequence.
    
    import numpy as np
    In [7]: np.linspace?
    Signature:
    np.linspace(
    start ,
    stop ,
    num=50,
    endpoint=True ,
    retstep=False ,
    dtype=None ,
    axis=0,
    )
    Docstring: ...
    
  16. A Python package is simply a structured arrangement of modules within a directory on the file system. To make a package, the module files are placed in a directory, along with a file named __ini__.py. It may be an empty file (zero bytes long) if no special initialization is required, but it must exist for the directory to be considered by Python to be a package.

  17. The urllib package in Python 3 is a set of modules for opening and retrieving the content referred to by Uniform Resource Locators (URLs), typically web addresses accessed with HTTP(S) (HyperText Transfer Protocol) or FTP (File Transfer Protocol).

    import urllib.request
    req = urllib.request.Request('https://www.wikipedia.org')
    from urllib.error import URLError , HTTPError
    try:
        response = urllib.request.urlopen(req)
    except HTTPError as e:
        print('The server returned error code', e.code)
    except URLError as e:
        print('Failed to reach server at {} for the following reason:\n{}'
        .format(url, e.reason))
    else:
        content = response.read()
    
  18. The urllib.parse module allows you to encode data from a Python dictionary into a form suitable for submission to a web server.

    # Wikipedia API using a GET request
    url = 'https://wikipedia.org/w/api.php'
    data = {'page': 'Monty_Python', 'prop': 'text', 'action': 'parse', 'section': 0}
    encoded_data = urllib.parse.urlencode(data)
    full_url = url + '?' + encoded_data
    full_url
    # 'https://wikipedia.org/w/api.php?page=Monty_Python&prop=text&action=parse
    # &section=0'
    req = urllib.request.Request(full_url)
    response = urllib.request.urlopen(req)
    html = response.read().decode('utf -8')
    
    # POST request
    req = urllib.request.Request(url, encoded_data)
    
  19. Some real numbers that can be expressed as a ratio of two integers are called rationals and pi, e, and root 2 cannot and are irrational.

  20. Longer comments should be complete sentences, with the first word capitalized. Explain why your code does what it does, don’t simply explain what it does.

    # Increase i by 10:
    i += 10
    
    # Skip the next 10 data points.
    i += 10
    
  21. Catastrophic cancellation A drastic loss of significance experienced in floating-point arithmetic when a quantity is subtracted from another with a very similar value.

  22. Introspection The ability of a program or interactive shell session to provide information about an object at runtime. For example, the expression type(x) returns the type of the object identified by the name x.

  23. Magic number A constant numerical value used as a literal (q.v.) in a program instead of being assigned to a meaningful variable name. Generally avoided in clear, maintainable code.

  24. Stability (of an algorithm) An algorithm is said to be stable if it is relatively unaffected by approximation errors of various sorts that can occur in its execution or input data; if these errors are magnified (typically leading to the catastrophic failure of the algorithm to obtain a meaningful result), it is said to be unstable.

  25. Vectorization The batch operation of a single operation on an entire array, without the need for an explicit Python loop – this improves both speed and readability.

  26. A well-conditioned problem is one for which small relative errors in the input data lead to small relative errors in the solution; an ill-conditioned problem is one for which small input errors lead to large errors in the solution.

  27. Rubberducking: If you explain the problem to someone else, you sometimes find the answer before you finish asking the question. Often you don’t need the other person; you could just talk to a rubber duck. And that’s the origin of the wellknown strategy called rubber duck debugging.