Skip to content

Instantly share code, notes, and snippets.

@alvesjnr
Created January 15, 2014 10:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alvesjnr/8433891 to your computer and use it in GitHub Desktop.
Save alvesjnr/8433891 to your computer and use it in GitHub Desktop.
{
"metadata": {
"name": ""
},
"nbformat": 3,
"nbformat_minor": 0,
"worksheets": [
{
"cells": [
{
"cell_type": "heading",
"level": 1,
"metadata": {},
"source": [
"An Informal Introduction to Python"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In the following examples, input and output are distinguished by the presence or\n",
"absence of prompts (``>>>`` and ``...``): to repeat the example, you must type\n",
"everything after the prompt, when the prompt appears; lines that do not begin\n",
"with a prompt are output from the interpreter. Note that a secondary prompt on a\n",
"line by itself in an example means you must type a blank line; this is used to\n",
"end a multi-line command.\n",
"\n",
"Many of the examples in this manual, even those entered at the interactive\n",
"prompt, include comments. Comments in Python start with the hash character,\n",
"``#``, and extend to the end of the physical line. A comment may appear at the\n",
"start of a line or following whitespace or code, but not within a string\n",
"literal. A hash character within a string literal is just a hash character.\n",
"Since comments are to clarify code and are not interpreted by Python, they may\n",
"be omitted when typing in examples.\n",
"\n",
"Some examples:"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"# this is the first comment\n",
"SPAM = 1 # and this is the second comment\n",
" # ... and now a third!\n",
"STRING = \"# This is not a comment.\""
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": "*"
},
{
"cell_type": "heading",
"level": 2,
"metadata": {},
"source": [
"Using Python as a Calculator"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let's try some simple Python commands."
]
},
{
"cell_type": "heading",
"level": 3,
"metadata": {},
"source": [
"Numbers"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The interpreter acts as a simple calculator: you can type an expression at it\n",
"and it will write the value. Expression syntax is straightforward: the\n",
"operators ``+``, ``-``, ``*`` and ``/`` work just like in most other languages\n",
"(for example, Pascal or C); parentheses can be used for grouping. For example:"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"2+2"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": "*"
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"# This is a comment\n",
"2+2"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": "*"
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"(50-5*6)/4"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": "*"
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"# Integer division returns the floor:\n",
"7/3"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": "*"
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"7/-3"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": "*"
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The equal sign (``'='``) is used to assign a value to a variable. Afterwards, no\n",
"result is displayed before the next interactive prompt:"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"width = 20\n",
"height = 5*9\n",
"width * height"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": "*"
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"A value can be assigned to several variables simultaneously:"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"x = y = z = 0 # Zero x, y and z\n",
"x"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"y"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": "*"
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"z"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": "*"
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Variables must be \"defined\" (assigned a value) before they can be used, or an\n",
"error will occur:"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"n # try to access an undefined variable"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": "*"
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"There is full support for floating point; operators with mixed type operands\n",
"convert the integer operand to floating point:"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"3 * 3.75 / 1.5"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": "*"
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"7.0 / 2"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": "*"
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Complex numbers are also supported; imaginary numbers are written with a suffix\n",
"of ``j`` or ``J``. Complex numbers with a nonzero real component are written as\n",
"``(real+imagj)``, or can be created with the ``complex(real, imag)`` function."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"1j * 1J"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": "*"
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"1j * 1J"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": "*"
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"3+1j*3"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": "*"
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"(3+1j)*3"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": "*"
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"(1+2j)/(1+1j)"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": "*"
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Complex numbers are always represented as two floating point numbers, the real\n",
"and imaginary part. To extract these parts from a complex number *z*, use\n",
"``z.real`` and ``z.imag``."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"a=1.5+0.5j"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": "*"
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"a.real"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": "*"
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"a.imag"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": "*"
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The conversion functions to floating point and integer (float(), int() and long()) don\u2019t work for complex numbers \u2014 there is no one correct way to convert a complex number to a real number. Use abs(z) to get its magnitude (as a float) or z.real to get its real part."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"a=3.0+4.0j\n",
"float(a)"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": "*"
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"abs(a) # sqrt(a.real**2 + a.imag**2)"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": "*"
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In interactive mode, the last printed expression is assigned to the variable\n",
"``_``. This means that when you are using Python as a desk calculator, it is\n",
"somewhat easier to continue calculations, for example:"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"tax = 12.5 / 100\n",
"price = 100.50\n",
"price * tax"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": "*"
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"price + _"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": "*"
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"round(_, 2)"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": "*"
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This variable should be treated as read-only by the user. Don't explicitly\n",
"assign a value to it --- you would create an independent local variable with the\n",
"same name masking the built-in variable with its magic behavior."
]
},
{
"cell_type": "heading",
"level": 3,
"metadata": {},
"source": [
"Strings"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Besides numbers, Python can also manipulate strings, which can be expressed in\n",
"several ways. They can be enclosed in single quotes or double quotes:"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"'spam eggs'\n",
"'doesn\\'t'\n",
"\"doesn't'\n",
"'\"Yes,\" he said.'\n",
"\"\\\"Yes,\\\" he said.'\n",
"'\"Isn\\'t,\" she said.'"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": "*"
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The interpreter prints the result of string operations in the same way as they\n",
"are typed for input: inside quotes, and with quotes and other funny characters\n",
"escaped by backslashes, to show the precise value. The string is enclosed in\n",
"double quotes if the string contains a single quote and no double quotes, else\n",
"it's enclosed in single quotes. The keyword `print` statement produces a more\n",
"readable output for such input strings.\n",
"\n",
"String literals can span multiple lines in several ways. Continuation lines can\n",
"be used, with a backslash as the last character on the line indicating that the\n",
"next line is a logical continuation of the line::\n",
"\n",
"```python\n",
" hello = \"This is a rather long string containing\\n\\\n",
" several lines of text just as you would do in C.\\n\\\n",
" Note that whitespace at the beginning of the line is\\\n",
" significant.\"\n",
"\n",
" print hello\n",
"```\n",
"\n",
"Note that newlines still need to be embedded in the string using ``\\n`` -- the\n",
"newline following the trailing backslash is discarded. This example would print\n",
"the following:\n",
"\n",
"\n",
"```\n",
" This is a rather long string containing\n",
" several lines of text just as you would do in C.\n",
" Note that whitespace at the beginning of the line is significant.\n",
"```\n",
"\n",
"Or, strings can be surrounded in a pair of matching triple-quotes: ``\"\"\"`` or\n",
"``'''``. End of lines do not need to be escaped when using triple-quotes, but\n",
"they will be included in the string.\n",
"\n",
"\n",
"```\n",
" print \"\"\"\n",
" Usage: thingy [OPTIONS]\n",
" -h Display this usage message\n",
" -H hostname Hostname to connect to\n",
" \"\"\"\n",
"```\n",
"produces the following output:\n",
"\n",
"\n",
"```\n",
" Usage: thingy [OPTIONS]\n",
" -h Display this usage message\n",
" -H hostname Hostname to connect to\n",
"```\n",
"\n",
"If we make the string literal a \"raw\" string, ``\\n`` sequences are not converted\n",
"to newlines, but the backslash at the end of the line, and the newline character\n",
"in the source, are both included in the string as data. Thus, the example::\n",
"\n",
"```\n",
" hello = r\"This is a rather long string containing\\n\\\n",
" several lines of text much as you would do in C.\"\n",
"\n",
" print hello\n",
"```\n",
"\n",
"would print:\n",
"\n",
"```text\n",
" This is a rather long string containing\\n\\\n",
" several lines of text much as you would do in C.\n",
"```\n",
"\n",
"Strings can be concatenated (glued together) with the ``+`` operator, and\n",
"repeated with ``*``:"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"word = 'Help' + 'A'\n",
"'<' + word*5 + '>'"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": "*"
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Two string literals next to each other are automatically concatenated; the first line above could also have been written word = 'Help' 'A'; this only works with two literals, not with arbitrary string expressions:"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"'str' 'ing' # <- This is ok"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": "*"
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"'str'.strip() + 'ing' # <- This is ok"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": "*"
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"'str'.strip() 'ing' # <- This is invalid"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": "*"
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Strings can be subscripted (indexed); like in C, the first character of a string has subscript (index) 0. There is no separate character type; a character is simply a string of size one. Like in Icon, substrings can be specified with the slice notation: two indices separated by a colon."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"word[4]"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": "*"
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"word[0:2]"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": "*"
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"word[2:4]"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": "*"
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Slice indices have useful defaults; an omitted first index defaults to zero, an omitted second index defaults to the size of the string being sliced."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"word[:2] # The first two characters"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": "*"
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"word[2:] # Everything except the first two characters"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": "*"
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Unlike a C string, Python strings cannot be changed. Assigning to an indexed position in the string results in an error:"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"word[0] = 'x'"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": "*"
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"word[:1] = 'Splat'"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": "*"
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"However, creating a new string with the combined content is easy and efficient:"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"'x' + word[1:]"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": "*"
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"'Splat' + word[4]"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": "*"
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Here\u2019s a useful invariant of slice operations: s[:i] + s[i:] equals s."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"word[:2] + word[2:]"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": "*"
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Degenerate slice indices are handled gracefully: an index that is too large is replaced by the string size, an upper bound smaller than the lower bound returns an empty string."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"word[1:100]"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": "*"
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"word[10:]"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": "*"
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"word[2:1]"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": "*"
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Indices may be negative numbers, to start counting from the right. For example:"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"word[-1] # The last character\n",
"'A'\n",
">>> word[-2] # The last-but-one character\n",
"'p'\n",
">>> word[-2:] # The last two characters\n",
"'pA'\n",
">>> word[:-2] # Everything except the last two characters\n",
"'Hel'"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": "*"
},
{
"cell_type": "code",
"collapsed": false,
"input": [],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": "*"
},
{
"cell_type": "code",
"collapsed": false,
"input": [],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": "*"
},
{
"cell_type": "code",
"collapsed": false,
"input": [],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": "*"
},
{
"cell_type": "code",
"collapsed": false,
"input": [],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": "*"
},
{
"cell_type": "code",
"collapsed": false,
"input": [],
"language": "python",
"metadata": {},
"outputs": []
}
],
"metadata": {}
}
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment