Type Python
in a terminal window:
$ python Python 2.7.2+ (default, Jul 20 2012, 22:15:08) [GCC 4.6.1] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>>
You're now in the Python interpreter. To exit, hit control d
.
In the interpreter, you type commands and press return:
>>> 2 + 2 4 >>> 23 * 4.3 98.89999999999999 >>> hello computer File "<stdin>", line 1 hello computer ^ SyntaxError: invalid syntax >>>
We're using Python operators.
>>> 6 - 7 -1 >>> 8 / 2 4 # division in some versions of Python >>> 8 / 3 2 # use floating-point values to get around this >>> 8 / 3.0 2.6666666666666665 >>> 3 ** 2 9
http://docs.python.org/2/tutorial/introduction.html#using-python-as-a-calculator
>>> a = 3 >>> b = 27 >>> b / a 9 >>> c = a + b >>> c 30 # errors! >>> d Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'd' is not defined
>>> "hello" + "world" 'helloworld' >>> a = "hello" >>> b = "world" >>> a + b 'helloworld'
Python comparison operators
- ::
>>> # are they equal? >>> 1 == 2 False >>> 1 == 1 True >>> a = 10 >>> b = 10 >>> a == b True # are they not equal? >>> 1 != 2 True # greater and less than >>> 2 > 1 True >>> 1 < 2 True # also <= and >=
>>> elements = ("hydrogen", "helium", "lithium", "beryllium", "boron") >>> type(elements) <type 'tuple'> >>> elements[0] 'hydrogen' >>> elements[3] 'beryllium' >>> elements[1:4] ('helium', 'lithium', 'beryllium') >>> elements[-1]
'boron'
>>> elements = list(elements) >>> type(elements) <type 'list'>
Lists can be sliced in the same way.
if/then