Python

Basic syntax, classes, conventions. Best for programmers who already know Js/Java/Ruby.

41 flashcards · Programming Languages · by lakesare

  1. Ruby: hash Js: object Python: ?

    Dictionary.

  2. list = ['a', 'b', 'c', 'd']; print "list[1:3]: ", list[1:3] #=> ?

    list[1:3]: ['b', 'c'] Just like js's list.slice(1, 3), it returns a new list (without modifying it) from [1arg, 2arg).

  3. range(0, 10) #=> ?

    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] Just like with list[1:3].

  4. Js: undefined, null Ruby: nil Python: ?

    None None is not a null pointer or a null reference but an actual object of which there is only one instance.

  5. Ruby: 3.times { |i| ... } Python: ?

    for i in range(0, 3): print(i)

  6. Ruby: class Person def initialize(name) end end Js: class Person { constructor(name) {} } Java: public class Person { public Person(String name) {} } Python: ?

    class Person: def __init__(self, name): self.name = name

  7. How to know if some object is None?

    if item is None: if item is not None: Comparisons to singletons like None should always be done with is or is not, never the equality operators." Therefore, "if item == None:" is inadvisable.

  8. Create a class Dog with: class variable sound instance variable name

    class Dog: sound = 'woof' # class variable shared by all instances def __init__(self, name): self.name = name # instance variable unique to each instance

  9. Write if else syntax in Python.

    if age >= 21: print('old') elif age >= 16: print('ok'); else: print('perfect');

  10. class Person: def __init__(self, name): self.name = name How to create a person?

    person = Person('Evgenia')

  11. Ruby: def hi 'Hello' end Python: ?

    def hi(): return 'Hello'

  12. Explain these underscore naming conventions: Single Leading Underscore: _var Single Trailing Underscore: var_ Double Leading Underscore: __var Double Leading and Trailing Underscore: __var__

    _var - convention: private variables [not entirely a convention, on * imports _vars are not imported] var_ - convention: to avoid naming conflicts __var - enforced: truly private variables, will get mangled (prefixed with ClassName) on inheritance __var__ - convention: not touched by interpreter, but don't use them in your program, python uses them Now if you use a wildcard import to import all names from the module, Python will not import names with a leading underscore Links: https://dbader.o…

  13. When does the support for Python 2 end?

    The official end-of-life date for the Python 2 series is 2020. After that, you'll have to find ways to get support for this series as new vulnerabilities can always arise. Since 2.7.13 is expected to be the last major release in the 2.7 series, new features won’t be backported, and only security and bug fixes will be going in from now until 2020. (ActiveState will continue to support the Python 2 series for a very long time, but new language features will be only available in Python 3.)

  14. How to launch python 2 vs 3 from terminal?

    $ python will launch the homebrew-installed Python 3 interpreter. $ python2 will launch the homebrew-installed Python 2 interpreter (if any). $ python3 will launch the homebrew-installed Python 3 interpreter.

  15. Js: class Dog extends Animal{} Python: ?

    class Dog(Animal):

  16. print('hi \n hi') => ? print(r'hi \n hi') => ?

    print('hi \n hi') => hi hi print(r'hi \n hi') => hi \n hi

  17. What's literal in Python?

    Something that the parser recognizes as syntax for writing an object directly, succinct and easily visible way to write a value: -3, -2, -1, 0, 1, 2, 3 (int literals) 2+3j, 0+5j, 2j, -3-5j (complex literals) 3.5, -2.7 (float literals) "", "hello" (str literals) u"", u"hello" (unicode literals) [], [1,2] (list literals) (), (1,), (1,2) (tuple literals) {}, {'a': 2} (dict literals) {1,2,3} (set literal introduced in Python 2.7) None (I think this is considered a literal, and not a keyword or simp…

  18. What's a raw string in Python?

    A "raw string literal" is a slightly different syntax for a string literal, in which a backslash, \, is taken as meaning "just a backslash" (except when it comes right before a quote that would otherwise terminate the literal) -- no "escape sequences" to represent newlines, tabs, backspaces, form-feeds, and so on. In normal string literals, each backslash must be doubled up to avoid being taken as the start of an escape sequence. print('hi \n hi') => hi hi print(r'hi \n hi') => hi \n hi

  19. What are raw strings mostly used for in Python?

    This syntax variant exists mostly because the syntax of regular expression patterns is heavy with backslashes (but never at the end, so the "except" clause above doesn't matter) and it looks a bit better when you avoid doubling up each of them. # import Python's regular expressions module import re p = re.compile(r'\d+') Regular expressions use the backslash character ('\') to indicate special forms or to allow special characters to be used without invoking their special meaning. This collides…

  20. pass vs break vs continue?

    break leaves a loop continue jumps to the next iteration pass does nothing, just to avoid IndentationError: expected an indented block

  21. What does __name__ refer to?

    __name__ is either: string 'name of the current module' if module is being run directly - string '__main__'

  22. What does this code achieve? if __name__ == '__main__': celery_instance.start()

    Only execute .start() when we execute the module directly, e.g.: python celery_instance.py

  23. Source distribution

    A distribution format (usually generated using python setup.py sdist) that provides metadata and the essential source files needed for installing by a tool like pip, or for generating a Built Distribution.

  24. What's the MANIFEST.in file used for?

    It lists the files to include in the distribution (apart from the default files!). When building a source distribution for your package, by default only a minimal set of files are included. You may find yourself wanting to include extra files in the source distribution, such as an authors/contributors file, a docs/ directory, or a directory of data files used for testing purposes.

  25. What's the seaborn python package used for?

    Prettier than matplotlib, and visualises statistical data. Seaborn is a Python data visualization library based on matplotlib. It provides a high-level interface for drawing attractive and informative statistical graphics.

  26. Why is seaborn frequently imported as sns?

    Samuel Norman Seaborn is a fictional character portrayed by Rob Lowe on the television serial drama The West Wing. So, it's a joked initialism. The show was designed with Sam as the main character, and as such he is the protagonist of the pilot episode and remains a focal point and lens for the show through at least the first season.

  27. What's the pandas python package used for?

    Creates tables from objects. Pandas is mainly used for data analysis. Pandas allows importing data from various file formats such as comma-separated values, JSON, SQL, Microsoft Excel. Pandas allows various data manipulation operations such as merging, reshaping, selecting, as well as data cleaning, and data wrangling features.

  28. [Matplotlib] What's the function to create this?

    import matplotlib.pyplot as plt plt.plot(x_values, y_values) plt.title("Squares Chart")

  29. [Matplotlib] What does plt.subplot(1, 2, 1) do?

    It draws 2 plots in one image. plt.subplot(1, 2, 1) means the figure has 1 row, 2 columns, and this plot is the 1st plot.

  30. What does pandas stand for?

    Panel data The name is derived from the term “panel data”, an econometrics term for multidimensional structured data sets.

  31. [Quantities] What does pq stand for?

    Python Quantities Here pq stands for “physical quantities” or “python quantities”.

  32. [Quantities] How do you read uV in quantities package?

    MicroVolts

  33. [Numpy] What does dtype stand for?

    Data-type

  34. [Numpy] Visually imagine A > 0.

  35. [Numpy] Visually imagine syntax for applying a mask to numpy arrays.

    arr[mask]

  36. [Numpy] What does ndarray stand for?

    n-dimensional array numpy.array is a function that returns a numpy.ndarray object. There is no object of type numpy.array. An ndarray is a (usually fixed-size) multidimensional container of items of the same type and size. The number of dimensions and items in an array is defined by its shape, which is a tuple of N non-negative integers that specify the sizes of each dimension. The type of items in the array is specified by a separate data-type object (dtype), one of which is associated with ea…

  37. [Numpy] What is the likely data type of this object? type(object) //=> <class 'numpy.ndarray'>

    A structured array. Structured arrays are ndarrays whose datatype is a composition of simpler datatypes organized as a sequence of named fields.The recommended way to test if a dtype is structured is with if dt.names is not None rather than if dt.names, to account for dtypes with 0 fields

  38. [Numpy] How are structured array (hashes) implemented in Numpy?

    ndarray, but with a special dtype! Structured arrays are ndarrays whose datatype is a composition of simpler datatypes organized as a sequence of named fields.//=> <class 'numpy.ndarray'>

  39. Visually imagine 1-dimensional array.

  40. Visually imagine 2-dimensional array.

  41. Visually imagine 3-dimensional array.