Skip to content

Instantly share code, notes, and snippets.

@evildmp
Created November 30, 2013 10:31
Show Gist options
  • Save evildmp/7717458 to your computer and use it in GitHub Desktop.
Save evildmp/7717458 to your computer and use it in GitHub Desktop.

Getting started with Python

The Python interpreter

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
>>>

Simple maths

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

Variables

>>> 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

Strings

>>> "hello" + "world"
'helloworld'
>>> a = "hello"
>>> b = "world"
>>> a + b
'helloworld'

Comparisons, and True and False

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 >=

Tuples, lists and sets

Tuples

>>> 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'

Lists

>>> elements = list(elements)
>>> type(elements)
<type 'list'>

Lists can be sliced in the same way.

Dictionaries

Loops

Functions

if/then

Scripts

Classes

The Quadcopter

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment