What is the REPL?

A read–eval–print loop (REPL), also known as an interactive toplevel or language shell, is a simple, interactive computer programming environment that takes single user inputs (i.e. single expressions), evaluates them, and returns the result to the user; a program written in a REPL environment is executed piecewise.

A Quick Summary of Python PEP 8 Programming standards

Indentation, line-length & code wrapping

  • Always use 4 spaces for indentation (don’t use tabs)
  • Write in ASCII in Python 2 and UTF-8 in Python 3
  • Max line-length: 72 characters (especially in comments)
  • Always indent wrapped code for readablility
# Good:
result = some_function_that_takes_arguments(
    'argument one,
    'argument two',
    'argument three'
)

# Bad:
result = some_function_that_takes_arguments(
'argument one,
'argument two', 'argument three')
result2 = some_function_that_takes_arguments('argument one', 'argument two', 'argument three')

Imports

  • Don’t use wildcards
  • Try to use absolute imports over relative ones
  • When using relative imports, be explicit (with .)
  • Don’t import multiple packages per line
# Good:
import os
import sys
from mypkg.sibling import example
from subprocess import Popen, PIPE # Acceptable
from .sibling import example # Acceptable

# Bad:
import os, sys # multiple packages
import sibling # local module without "."
from mypkg import * # wildcards

Whitespace and newlines

  • 2 blank lines before top-level function and class definitions
  • 1 blank line before class method definitions
  • Use blank lines in functions sparingly
  • Avoid extraneous whitespace
  • Don’t use whitespace to line up assignment operators (=, :)
  • Spaces around = for assignment
  • No spaces around = for default parameter values
  • Spaces around mathematical operators, but group them sensibly
  • Multiple statements on the same line are discouraged
# Good:
spam(ham[1], {eggs: 2})
if x == 4:
    print x, y
    x, y = y, x
dict['key'] = list[index]
y = 2
long_variable = 3
hypot2 = x*x + y*y
c = (a+b) * (a-b)
def complex(real, imag=0.0):
    return magic(r=real, i=imag)
do_one()
do_two()

# Bad
spam ( ham[ 1 ], { eggs: 2 } ) # spaces inside brackets
if x == 4 : print x , y ; x , y = y , x # inline statements, space before commas
dict ['key'] = list [index] # space before dictionary key
y             = 2 # Using spaces to line up assignment operators
long_variable = 3
hypot2 = x * x + y * y # Too much space around operators
c = (a + b) * (a - b) # Too much space around operators
def complex(real, imag = 0.0):
    return magic(r = real, i = imag) # Spaces in default values

Comments

  • Keep comments up to date – incorrect comments are worse than no comments
  • Write in whole sentences
  • Try to write in “Strunk & White” English
  • Use inline comments sparingly & avoid obvious comments
  • Each line of block comments should start with “# “
  • Paragraphs in block comments should be separated by a line with a single “#”
  • All public functions, classes and methods should have docstrings
  • Docstrings should start and end with """
  • Docstring one-liners can be all on the same line
  • In docstrings, list each argument on a separate line
  • Docstrings should have a blank line before the final """
def my_function():
    """ A one-line docstring """

def my_other_function(parameter=False):
    """
    A multiline docstring.

    Keyword arguments:
    parameter -- an example parameter (default False) 

    """

Naming conventions

  • Class names in CapWords
  • Method, function and variables names in lowercase_with_underscores
  • Private methods and properties start with __double_underscore
  • “Protected” methods and properties start with _single_underscore
  • If you need to use a reserved word, add a _ to the end (e.g. class_)
  • Always use self for the first argument to instance methods
  • Always use cls for the first argument to class methods
  • Never declare functions using lambda (f = lambda x: 2*x)
class MyClass:
    """ A purely illustrative class """

    __property = None

    def __init__(self, property_value):
        self.__property = property_value

    def get_property(self):
        """ A simple getter for "property" """

        return self.__property

    @classmethod
    def default(cls):
        instance = MyClass("default value")
        return instance

Source: https://www.python.org/dev/peps/pep-0008/#introduction

Quick methods to add python Intrepreter into windows system path variable

All three methods are tested and it is working in all versions of windows OS.

Method 1:

  1. Hold down windows key and press pause key.
  2. Click Advanced System Settings.
  3. Click Environment Variables.
  4. Append ;C:\python27 to the Path variable

Method 2:

Setting path at Windows

To add the Python directory to the path for a particular session in Windows −

In command prompt − type path %path%;C:\Python and press Enter.

Note − C:\Python is the path of the Python directory

Python Environment Variables

Here are important environment variables, which can be recognized by Python −

S.No. System Variable & Description
1 PYTHONPATH

It has a role similar to PATH. This variable tells the Python interpreter where to locate the module files imported into a program. It should include the Python source library directory and the directories containing Python source code. PYTHONPATH is sometimes preset by the Python installer.

2 PYTHONSTARTUP

It contains the path of an initialization file containing Python source code. It is executed every time you start the interpreter. It is named as .pythonrc.py in Unix and it contains commands that load utilities or modify PYTHONPATH.

3 PYTHONCASEOK

It is used in Windows to instruct Python to find the first case-insensitive match in an import statement. Set this variable to any value to activate it.

4 PYTHONHOME

It is an alternative module search path. It is usually embedded in the PYTHONSTARTUP or PYTHONPATH directories to make switching module libraries easy.

Method 3:

  1. [Right Click]Computer > Properties >Advanced System Settings > Environment Variables
  2. Click [New] under “System Variable”
  3. Variable Name: PY_HOME, Variable Value:C:\path\to\python\version enter image description here
  4. Click [OK]
  5. Locate the “Path” System variable and click [Edit]
  6. Add the following to the existing variable:

    %PY_HOME%;%PY_HOME%\Lib;%PY_HOME%\DLLs;%PY_HOME%\Lib\lib-tk; enter image description here

  7. Click [OK] to close all of the windows.

As a final sanity check open a command prompt and enter python. You should see

>python "type version"

If you need to switch between versions, you only need to modify the PY_HOME variable to point to the proper directory. This is bit easier to manage if you need multiple python versions installed.

Dictionary .get method usage in python

Description

The method get() returns a value for the given key. If key is not available then returns default value None.

Syntax

Following is the syntax for get() method −

dict.get(key, default=None)

Parameters

  • key — This is the Key to be searched in the dictionary.
  • default — This is the Value to be returned in case key does not exist.

Return Value

This method return a value for the given key. If key is not available, then returns default value None.

Example

The following example shows the usage of get() method.

#!/usr/bin/python

diction = {'Name': 'Kumar', 'Age': 12}

print "Value : %s" %  diction.get('Age')
print "Value : %s" %  diction.get('School', "Nothing")

When we run above program, it produces following result −

Value : 12
Value : Nothing