Hello world!

The beginning of almost everything in computer programming :-)

Let's see different alternatives to run Python code.

1. "Batch" execution of single Python commands


In [ ]:
!python -c "print('Hello world!')"

2. Interacting with Jupyter Notebook

This interface (what you are reading now) is know as Jupyter Notebook, an interactive document, which is a mix of Markdown and Python code executed by IPython:


In [ ]:
print("Hello world!") # Modify me and push <SHIFT> + <RETURN>

3. Interacting with the Python interpreter

Run python in a shell and type: print("Hello world!") <enter> quit().

$ python
Python 2.7.10 (default, Oct 23 2015, 19:19:21) 
[GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.59.5)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> print("Hello world!")
Hello world!
>>> quit()
$

Alternatively, instead of python we can use ipython, which provides dynamic object introspection, command completion, access to the system shell, etc.

$ ipython
Python 3.5.1rc1 (v3.5.1rc1:948ef16a6951, Nov 22 2015, 11:29:13) 
Type "copyright", "credits" or "license" for more information.

IPython 5.1.0 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]: print("Hello world!")
Hello world!

In [2]: help(print)
Help on built-in function print in module builtins:

print(...)
    print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)

    Prints the values to a stream, or to sys.stdout by default.
    Optional keyword arguments:
    file:  a file-like object (stream); defaults to the current sys.stdout.
    sep:   string inserted between values, default a space.
    end:   string appended after the last value, default a newline.
    flush: whether to forcibly flush the stream.

(type: <q> to exit)

In [3]: quit() # <ctrl> + <d> also works in Unixes
$

Interpreted?

Python is an interpreted programming language. When we run a Python program, we are executing the translation to bytecode of each Python statement of our program over the Python Virtual Machine (PVM). The .pyc files that appear after running a collection of modules as a script for the first time, contains the bytecode of such modules. This is used by Python to speed up their future executions.


In [ ]:
def hello():
    print('Hello world!')
import dis

dis.dis(hello)

4. Running Python programs (modules) as scripts


In [ ]:
!cat hello_world.py

In [ ]:
# Check the code (optional)
!pyflakes3 hello_world.py

In [ ]:
!./hello_world.py # Specific of Unix

In [ ]:
!python hello_world.py

In [ ]:
%run hello_world.py # Specific of Ipython