• Python is an object oriented programming language.
  • Almost everything in Python is an object, with its properties and methods.
  • A Class is like an object constructor, or a “blueprint” for creating objects.
  • Different from JavaScript, there are no primitives in Python.
  • Python have a good documentation.

Python vs. JavaScript

REPL

REPL(Read-Eval-Print-Loop)

  • Python has it’s own interpreter. And Python have different version interpreter. For example Pythone 2.7 still popular, but the new stable version is 3.10 at the moment. something like: python3 yourcode.py
  • JavaScript need a JavaScript runtime to support, like Browser, NodeJS.

Code Blocks

  • JavaScript makes use of curly brackets for defining code blocks. Python, on the other hand, uses indentation for defining code blocks.
  • While JavaScript has the semi-colon (;) that serves as the statement terminator (though it is not mandatory), Python uses a newline.

Data type

Mutability

  • Python support mutable data type, like set, and immutable data type, like list.
  • JavaScript have primitive type concept which are immutable. All object is mutable. But each property of the object have it’s own descriptor which can config the mutability of the property.

Number

  • In python, there are different numeric type like int, float, fixed-point decimal.
  • In JavaScript, there are number and bigInt. Number type is double floating point number.

Object

  • Objects are Python’s abstraction for data. All data in a Python program is represented by objects or by relations between objects. (Everything in python is object)
  • Is it everything is object in JavaScript? NO, primitive is not object.
  • Object in JavaScript, is very easy to create. But in Python, Each object has a class from which it is instantiated.

In JavaScript, a simple iterator can be:

let myIter = {
  n: 0,
  next: function() {
    return (value: this.n++, done: false);
  }
}

In Python, a iterator looks like:

class MyNumbers:
  def __iter__(self):
    self.n = 0
    return self

  def __next__(self):
    self.n += 1
    return self.n

myclass = MyNumbers()
myiter = iter(myclass)
next(myiter)

Class

JavaScript class

  • JavaScript class, which have been described as syntax sugar, is build on the top of prototype chain.
  • JavaScript class works very well. You don’t need to always translate back to prototype chain to understand the code.
  • JavaScript actually implement class as function.
  • JavaScript class support class, new, constructor, extends, super, static key words. JavaScript class put everything in one place, to implement OOP coding concept which similar to Java, C++.

Python class

  • Each value is an object. Each object is an instance of a class. Even a class is an instance of the metaclass - type.
  • class itself is an object. class instance is an object too.
  • class in python is not function.
  • Method object is not Function object in Python! But they are same thing in JavaScript.
  • Python supports a form of multiple inheritance. But JavaScript support just one.

iterable, iterator

JavaScript

  • An object is iterable if it implement the @@iterator method.
  • An object is iterator when it implements the next() according to some semantics: done_value_object = myIterator.next(). // if done == false, can keep calling myIterator.next() to return done_value_object. // if done == true, then iterator is completed.

Python

Python have different concepts of iterator and iterable from JavaScript.

  • exception StopIteration is used to signal the end of an iteration.
  • built-in function iter() and next() used to implement iteration.

generator

JavaScript generator

  • syntax: * function (){}
  • generator is an iterator which maintain by the language itself.
  • a generator object (iterator) for the function will be returned when meet yield.
  • yield will return value.
  • generator function also support return keyword. generator function will totally complete when return.
  • generator can work with promise to make code better.

Python generator

  • syntax: when a function contain keyword yield, then it is generator.
  • If you used next() after iteration have been completed, then you’ll get an explicit StopIteration exception.

Static method

static concept is similar between Python, JavaScript, C++, Java. static methods can be accessed from classes instead of instants.

in JavaScript

  • there are static keyword.
  • static method can’t be access by instance.

in Python

  • Using built-in function staticmethod() to turn method to static. But can using syntaxtic sugar decorator @staticmethod

  • static methods can be access both by class and instance. Class.staticmethodFunc() or even Class().staticmethodFunc()

FAQ

User input

Python allows for user input. That means we are able to ask the user for input.

username = input("Enter username:")
print("Username is: " + username)

input() function always return string.

_ underscore in Python

  • Underscore (_) is valid for making identifier in Python. Just like 0-9, a-z, A-Z.
  • There are some traditional usage, like

ignore values:

a, *_, b = (7, 6, 5, 4, 3, 2, 1)
print(a, b)

lopping ten times using _

for _ in range(5):
    print(_)

Separating Digits of Numbers:

million = 1_000_000
binary = 0b_0010
octa = 0o_64
hexa = 0x_23_ab

print(million)
print(binary)
print(octa)
print(hexa)

Naming Using Underscore(_)

Underscore(_) can be used to name variables, functions and classes, etc..,

Single Pre Underscore: _variable: It is used for internal use. For example you import all the methods and names from my_functions.py, Python doesn’t import the names which starts with a single pre underscore.

Single Post Underscore: variable_: You can avoid conflicts with the Python Keywords by adding an underscore at the end of the name which you want to use.

Double Pre Underscores: __variable: It is used for the name mangling. Double Pre Underscores tells the Python interpreter to rewrite the attribute name of subclasses to avoid naming conflicts.

class Sample():
    def __init__(self):
        self.a = 1
        self._b = 2
        self.__c = 3
obj1 = Sample()
dir(obj1)

['_Sample__c', '__class__',... '_b', 'a']

Double Pre and Post Underscores:- __variable__: In Python, you will find different names which start and end with the double underscore. They are called as magic methods. stay away from them.

loop, if, elif, else

All these keyword in Python and JavaScript are come from C language. They are very similar.

Loop

  • Python support while and for..in.
  • The while is same with while in JavaScript.
  • The for..in is similar with for..of in JavaScript.
  • Both while and for..in Support break, continue keyword. No return keyword inside loop! It is same with JavaScript.
  • Both loops support else keyword. But JavaScript is not support.

if, elif, else

Python use elif. JavaScrpt use else if.

What do asterisk operator means in Python

For numeric data type, * is used for multiplication.

For sequences such as string, list and tuple, * is a repetition operator

>>> s="Hello"
>>> s*3
'HelloHelloHello'

packing arguments given to function * for Positional arguments and ** for keyword arguments.

from random import randint
def roll(*dice):
    return sum(randint(1, die) for die in dice)

print(roll(4, 5, 6))

What do *-on-its-own in parameter means

like sorted built-in function: sorted(iterable, /, *, key=None, reverse=False)

The * enforce that the arguments after * must be specified as keyword arguments. Not accept positional arguments any more.

unpack sequence or collection

The single star * unpacks the sequence/collection into positional arguments, so you can do this:

def sum(a, b):
    return a + b
values = (1, 2)
s = sum(*values)

num_list = [1,2,3,4,5]
num_list_2 = [6,7,8,9,10]
new_list = [*num_list, *num_list_2]
# [1,2,3,4,5,6,7,8,9,10]

name = ['levin', 'middlename', 'another middle', 'wen']
first, *middle, last = name
print(middle) # ['middlename', 'another middle']

The double star ** uppacks the dictionary and thus named arguments:

values = { 'a': 1, 'b': 2 }
s = sum(**values)

# will execute as:
s = sum(a=1, b=2)

pleace * prior to an iterator, it will unpack the iterator.

For example, zip() is a lazy function which return an iterator of tuples. When zip() in conjunction with the * operator can be used to unzip a list:

>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> list(zip(x, y))
[(1, 4), (2, 5), (3, 6)]
>>> x2, y2 = zip(*zip(x, y))
>>> x == list(x2) and y == list(y2)
True

pack value

We can pack several values into one variable (list) using the * operator:

*names, = 'Michael', 'John', 'Nancy'
# names 
['Michael', 'John', 'Nancy']
# (The reason for using a trailing comma after *names is because the left side of the assignment must be a tuple or list. when pack into list, need * and , ) try this:
*names, other = 'Michael', 'John', 'Nancy'
# names 
['Michael', 'John']
# other
'Nancy'

# Or pack them into a tuple: 

names = 'Michael', 'John', 'Nancy'
# names 
('Michael', 'John', 'Nancy')

Multiple assignment

Assign multiple values to multiple variables

a, b, c = 0.1, 100, 'string'

a = 100, 200
print(a)# (100, 200)
print(type(a))# <class 'tuple'>

# a, b = 100, 200, 300 # ValueError
# a, b, c = 100, 200 # ValueError

a, *b = 100, 200, 300
print(b)# [200, 300]
print(type(b))# <class 'list'>

Assign the same value to multiple variables

a = b = c = 'string' # usually no problem

But assign mutable object, usually that is not what you expect:

a = b = [0, 1, 2]
a[0] = 10
print(b) # [100, 1, 2]

Get detail of How do Python run the code

Using cProfile.run():

import cProfile
cProfile.run('sum([i * 2 for i in range(10000)])') # list comprehension

you will get information below:

5 function calls in 0.001 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.001    0.001    0.001    0.001 <string>:1(<listcomp>)
        1    0.000    0.000    0.001    0.001 <string>:1(<module>)
        1    0.000    0.000    0.001    0.001 {built-in method builtins.exec}
        1    0.000    0.000    0.000    0.000 {built-in method builtins.sum}
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}

another example: cProfile.run('sum((i * 2 for i in range(10000)))') # generator comprehension

Get variable size of memory sys.getsizeof():

>>> import sys
>>> nums_squared_lc = [i ** 2 for i in range(10000)]
>>> sys.getsizeof(nums_squared_lc)
87624
>>> nums_squared_gc = (i ** 2 for i in range(10000))
>>> print(sys.getsizeof(nums_squared_gc))
120

How to test speed of some code?

Following codes are get the time which have been spend on running the codes. and You can get which code is faster. f-string format is faster than modulo, .format().

>>> import timeit
>>> timeit.timeit("""name = "Eric"
... age = 74
... '%s is %s.' % (name, age)""", number = 10000)
0.003324444866599663

>>> timeit.timeit("""name = "Eric"
... age = 74
... f'{name} is {age}.'""", number = 10000)
0.0024820892040722242

>>> timeit.timeit("""name = "Eric"
... age = 74
... f'{name} is {age}.'""", number = 10000)
0.0024820892040722242

Expressions vs. statements?

Expressions

Expressions only contain identifiers, literals and operators (where operators include arithmetic and boolean operators, the function call operator () the subscription operator [] and similar), and can be reduced to some kind of “value”, which can be any Python object. Examples:

3 + 5
map(lambda x: x*x, range(10))
[a.x for a in some_iterable]
yield 7

Statements

Statements, on the other hand, are everything that can make up a line (or several lines) of Python code. Note that expressions are statements as well. Examples:

# all the above expressions
print 42
if x: do_y()
return
a = 7

How to Import Another File in Python

If same directory, can import directly.

import otherpythonfile

Add the path of your .py files to sys.path

When a module named mymodule is imported, the interpreter first searches for a built-in module with that name. If not found, it then searches for a file named mymodule.py in a list of directories given by the variable sys.path.

sys.path is initialized from these locations:

  1. current directory,
  2. PYTHONPATH,
  3. installation default.

So, after you add path to the sys.path, you are supposed to make it:

import sys
import os
sys.path.append(os.path.abspath("/home/el/foo4/stuff"))

init.py

add a empty file __init__.py to each directory which your_import_file.py located. It works perfectly!

What is pickling and unpickling in Python?

  • The Python pickle is defined as a module which accepts any Python object and converts it into a string representation.
  • It dumps the Python object into a file using the dump function; this process is called Pickling.
  • The process of retrieving the original Python objects from the stored string representation is called as Unpickling.

What is PyPI, pip, PyPy

  • PyPI (/ˌpaɪpiˈaɪ/) (Python Package Index), is the official third-party software repository for Python. Some package managers, including pip, use PyPI as the default source for packages and their dependencies.
  • pip is the package manager for Python. You can use pip to install packages from the Python Package Index and other indexes. Just like npm for JS.
  • PyPy (/ˈpaɪpaɪ/) is an implementation of the Python programming language. PyPy often runs faster than the standard implementation CPython because PyPy uses a just-in-time compiler.

What is IPython, Jupyter

IPython

IPython (Interactive Python) is a command shell for interactive computing in multiple programming languages, originally developed for the Python programming language, that offers introspection, rich media, shell syntax, tab completion, and history.

IPython provides a rich architecture for interactive computing with:

  • A powerful interactive shell.
  • A kernel for Jupyter.
  • Support for interactive data visualization and use of GUI toolkits.
  • Flexible, embeddable interpreters to load into your own projects.
  • Easy to use, high performance tools for parallel computing.

Project Jupyter

Project Jupyter (/ˈdʒuːpɪtər/ (listen)) is a project to develop open-source software, open standards, and services for interactive computing across multiple programming languages.

  • It was spun off from IPython in 2014 by Fernando Pérez and Brian Granger.
  • Project Jupyter’s name is a reference to the three core programming languages supported by Jupyter, which are Julia, Python and R.
  • Project Jupyter has developed and supported the interactive computing products Jupyter Notebook, JupyterHub, and JupyterLab.

Try not use global variable.

global_var = 10
def foo(x):
  print(global_var) # here will try to access the local variable global_var, but not defined.
  global_var = x
  print(global_bar)

The code above will cause error in python.

Compare arrays, Dictionarys, sets, strings

Python will compare the elements inside, so if all the elements same, then they are equal.

array1 = [1, 2, 3]
array2 = [1, 2, 3]
array1 == array2 // True

dict1 = {'x': 500, 'y': 5874, 'z': 560}
dict2 = {'x': 500, 'y': 5874, 'z': 560}
dict1 == dict2 // True

set1 = {1,2,3,6,'x'}
set2 = {1,2,3,6,'x'}
set1 == set2 // True

str1 = 'Gandhiewrnagar'
str2 = 'Gandhiewrnagar'
print(str1 == str2)// True. Even id() is same when string not long enough. (string interning)

Even nested collection, Python will check deep as well!

This is different from JavaScript. When you compare two arrays using the == operator in JavaScript, you are actually comparing the object references rather than the contents of the arrays.