Python for users of C-like languages:

I’m going to assume you are familiar with at least one C-like language, and describe the differences and similarities between Python and C-like languages. Note that when I say ‘C’ in the examples below, I probably mean C++, or C-like. I know that C doesn’t contain bool or cout. =P

  • Python is dynamically typed. Instead of specifying the type of a variable in the code, it is determined dynamically by the Python interpreter when the script is run. The following example shows how a variable would be created to store the integer ‘7’ in C and Python respectively:
// C
int my_cool_variable = 7;
# Python
my_cool_variable = 7
  • Python uses line breaks to specify the end of a line. The following examples show how multiple lines of code would be written in C and Python respectively:
// C
int first = 1;
int second = 2;
# Python
first = 1
second = 2
  • Python functions are a little different. They do not specify type, because Python is dynamically typed. Also, a Python function has a colon (:) after the parentheses, and the rest of the function is indented. The following examples show how functions are defined in C and Python respectively:
// C
int function1()
{
    int a = 1 + 2;
    return a - 1;
}

bool function2()
{
    int a = 3;
    int b = 2;
    return a == b;
}
# Python
def function1():
    a = 1 + 2
    return a - 1

def function2():
    a = 3
    b = 2
    return a == b
  • Python uses indentation to specify loop boundaries and nesting. Rather than specifying the start and end of a loop or function with curly braces, Python uses a colon, followed by indentation.
// C-like
int a = 0;
while (a < 7)
{
    cout << a;
    if (a == 3)
    {
        cout << "That's my favourite number.";
    }
    a++
} 
# Python
a = 0
while a < 7:
    print(a)
    if a == 3:
        print("That's my favourite number.")
    a += 1
  • Python uses ‘#’ for one line comments, and lots of #’s for multi-line comments. (Some people will try to tell you that Python uses “"”triple-quoted strings””” as multi-line comments. You can do this if you like, but it is not technically correct. “"”Triple-quoted strings””” will be instantly garbage collected on run, whereas #comments will be completely ignored, so #comments are generally better. One legitimate use for “"”triple-quoted strings””” is docstrings. Docstrings are strings directly after the start of a module, or a function or a class, and are used for interactively accessible documentation among other things.
// One line C comment.
/*
  Multi-
  line
  C 
  comment.
*/
# One line Python comment

#  Multi-
#  line
#  Python
#  comment.

"""
Something that acts like a multi-line
comment, but is usually frowned upon.
"""

def new_function():
    """Docstring that says what this
    function does"""

# Accessing a docstring from within a program
docstring = new_function.__doc__
  • Google is your friend. Have fun.