User Tools

Site Tools


competitive_programming:python_interpreter

Python3 Interactive Interpreter

The Python3 interactive interpreter (typically invoked with python3 on the command line) allows for the entry of arbitrary Python3 commands, making it a great calculator and a great place to test simple ideas. The interpreter should feel familiar to users of shells made popular in many operating systems and read-eval-print loops in other languages.

Invocation

In Linux the interactive interpreter is invoked directly by calling python3 without any arguments (e.g., a .py file to execute). In Windows this is bundled into the IDLE development environment.

This will open the Python3 prompt:

$ python3
Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 23 2015, 02:52:03) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>

The quit command exits.

Using the Interactive Interpreter

Basics Commands

The Help System

Loops

The interactive interpreter is quite limited compared to what can be accomplished in an actual Python3 program (i.e., a .py file), however its functionality can be easily extended slightly beyond that of one-liners. (Nested) Loops can be quickly tested in order to evaluate syntax and functionality.

>>> from math import *
>>> for i in range(10):
...  print(int(log(2**i, 10))+1, end=' ') # single space before the print() to simulate indentation
...                                       # additional lines in the loop here or <return> to end
1 1 1 1 2 2 2 3 3 3 >>>

The above fragment computes powers of two, and then uses the decimal logarithm to compute the number of digits in each power.

This can be extended to basic nested structures.

>>> for i in range(3):
...  for j in range(3):             # preceded by a single space
...   print(i, j, sep=',', end=" ") # preceded by two spaces
...                                 # single <return> keystroke
0,0 0,1 0,2 1,0 1,1 1,2 2,0 2,1 2,2 >>>

If you are looking to do anything more complicated, it is likely that you should create a temporary '.py' file.

Interactive Interpreter: Importing Files

The import statement can be used to import arbitrary Python3 files, which can be useful for quick unit tests (and doesn't require further file manipulation to drive tests).

competitive_programming/python_interpreter.txt · Last modified: 2018/08/14 11:05 by jguerin