{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "UCL\n", "\n", "\n", "[](011_Python_data_types.ipynb)\n", "[](005_Packages.ipynb)\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# 010 Introduction to Python" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Introduction\n", "\n", "[Python](http://www.python.org/) is a high level programming language that is freely available, relatively easy to learn and portable across different computing systems. In Python, you can rapidly develop solutions for the sorts of problems you might need to solve in your MSc courses and in the world beyond. Code written in Python is also easy to maintain, is (or should be) self-documented, and can easily be linked to code written in other languages.\n", "\n", "Relevant features include: \n", "\n", "- it is automatically compiled and executed \n", "- code is portable provided you have the appropriate Python modules. \n", "- for compute intensive tasks, you can easily make calls to methods written in (faster) lower-level languages such as C or FORTRAN \n", "- there is an active user and development community, which means that new capabilities appear over time and there are many existing extensions and enhancements easily available to you.\n", "\n", "For further background on Python, look over the material on [Advanced Scientific Programming in Python](https://python.g-node.org/wiki/schedule) and/or the [software-carpentry.org](http://software-carpentry.org/v3/py01.html) and [python.org](http://www.python.org/) web sites.\n", "\n", "\n", "### Purpose\n", "\n", "In this section we will learn some of the fundamental concepts in Python concerning variables, as well as writing comments and the use of the function `print()` and newline and tab characters.\n", "\n", "### Prerequisites\n", "\n", "You will need some understanding of the following:\n", "\n", "* [001 Using Notebooks](001_Notebook_use.ipynb)\n", "* [003 Getting help](003_Help.ipynb)\n", "\n", "Remember that you can 'run' the code in a code block using the 'run' widget (above) or hitting the keys ('typing') and at the same time. \n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Some basics" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Comments \n", "\n", "Comments are statements ignored by the language interpreter.\n", "\n", "Any text after a `#` in a *code block* is a comment." ] }, { "cell_type": "markdown", "metadata": { "solution2": "hidden", "solution2_first": true }, "source": [ "#### Exercise 1\n", "\n", "* Try running the code block below\n", "* Explain what happened ('what the computer did')" ] }, { "cell_type": "markdown", "metadata": { "solution2": "hidden" }, "source": [ "**ANSWER**\n", " \n", "Nothing 'apparently' happened, but really, the code block was interpreted as a set of Python commands and executed. As there is only a comment, there was no output." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### `print()`\n" ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "ExecuteTime": { "end_time": "2020-07-22T14:28:42.215616Z", "start_time": "2020-07-22T14:28:42.212303Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Help on built-in function print in module builtins:\n", "\n", "print(...)\n", " print(value, ..., sep=' ', end='\\n', file=sys.stdout, flush=False)\n", " \n", " Prints the values to a stream, or to sys.stdout by default.\n", " Optional keyword arguments:\n", " file: a file-like object (stream); defaults to the current sys.stdout.\n", " sep: string inserted between values, default a space.\n", " end: string appended after the last value, default a newline.\n", " flush: whether to forcibly flush the stream.\n", "\n" ] } ], "source": [ "help(print)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To print some value (by default, to the terminal you are using, knows as the standard output `stdout`), use the `print(...)` function.\n", "\n" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "hello world\n", "hello world\n" ] } ], "source": [ "# For example, to print the string 'hello world':\n", "print('hello world')\n", "\n", "# to print the list ('hello','world'):\n", "print('hello', 'world')" ] }, { "cell_type": "markdown", "metadata": { "solution2": "hidden", "solution2_first": true }, "source": [ "#### Exercise 2\n", "\n", "* Insert a new cell below here\n", "* Print out the string `Today I am learning Python`." ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "solution2": "hidden" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Today I am learning Python\n" ] } ], "source": [ "# ANSWER\n", "print('Today I am learning Python')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### newline and tab\n", "\n", "We can gain more control over our printing by understanding some special characters we use in print formatting:\n", "\n", " newline \\n\n", " tab \\t\n", " \n", "When we specify these characters in a print statement, they have the impact of starting text on the following time, and aligning text the next tab location respectively. These are concepts you will be familiar with from word processing, although you may not have thought about them explicitly.\n", "\n", "Any time we place these characters in a string that we print out, they will affect the formatting out our printed statement:" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "hello world\n", "hello\n", "world\n", "hello\tworld\n" ] } ], "source": [ "# For example, to print the string 'hello world'\n", "# with a simple space\n", "print('hello world')\n", "\n", "# with a newline in the middle\n", "print('hello\\nworld')\n", "\n", "# with a tab in the middle\n", "print('hello\\tworld')" ] }, { "cell_type": "markdown", "metadata": { "solution2": "hidden", "solution2_first": true }, "source": [ "#### Exercise 3\n", "\n", "* Insert a new cell below here\n", "* print a string `\"all the world's a stage and all the men and women merely players\"`\n", "* print this same string, but with each word on a new line\n", "* print this same string with two columns of words, for as many lines as needed" ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "solution2": "hidden" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "all the world's a stage and all the men and women merely players\n" ] } ], "source": [ "#ANSWER\n", "\n", "# print a string \"all the world's a stage\"\n", "print(\"all the world's a stage and all the men and women merely players\")" ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "solution2": "hidden" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "all\n", "the\n", "world's\n", "a\n", "stage\n", "and\n", "all\n", "the\n", "men\n", "and\n", "women\n", "merely\n", "players\n" ] } ], "source": [ "#ANSWER\n", "\n", "# print this same string, but with each word on a new line\n", "print(\"all\\nthe\\nworld's\\na\\nstage\\nand\\nall\\nthe\\nmen\\nand\\nwomen\\nmerely\\nplayers\")" ] }, { "cell_type": "code", "execution_count": 7, "metadata": { "solution2": "hidden" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "all\tthe\n", "world's\ta\n", "stage\tand\n", "all\tthe\n", "men\tand\n", "women\tmerely\n", "players\n" ] } ], "source": [ "# ANSWER\n", "# print this same string with two columns of words, for as many lines as needed\n", "# This needs alternating newline and tab\n", "print(\"all\\tthe\\nworld's\\ta\\nstage\\tand\\nall\\tthe\\nmen\\tand\\nwomen\\tmerely\\nplayers\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Variables and Values " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Variables and values\n", "\n", "The idea of **variables** is fundamental to any programming. \n", "\n", "You can think of this as the *name* of *something*, so it is a way of allowing us to refer to some object in the language. A related idea we will find useful is to think of the variable name as a **key**. What the variable *is* set to is called its **value**. \n", "\n", "Putting these ideas together, we can think of the variable name and its value as a `key: value` pair:\n", "\n", " key: value\n", "\n", "We can say that the `value` is **assigned to** the `key`.\n", "\n", "**Remember: the `key` is the name of the variable, the `value` is what is stored in the variable.**" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "So let's start with a variable we will call (*declare to be*) `my_store`.\n", "\n", "We will give a *value* of the string `'one'` to this variable:" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "one\n" ] } ], "source": [ "# assign the value 'one' to the variable (key) my_store\n", "my_store = 'one'\n", "\n", "# Print the value of my_store\n", "print(my_store)" ] }, { "cell_type": "markdown", "metadata": { "solution2": "hidden", "solution2_first": true }, "source": [ "#### Exercise 4\n", "\n", "* Insert a new cell below here\n", "* set a variable called `message` to contain the string `hello world`\n", "* print the value of the variable `message`" ] }, { "cell_type": "code", "execution_count": 9, "metadata": { "scrolled": true, "solution2": "hidden" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "hello world\n" ] } ], "source": [ "# ANSWER\n", "\n", "message = 'hello world'\n", "print(message)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Symbol names and conventions\n", "\n", "Symbol names, such as those used for variables, in Python can contain the usual character set `a-z`, `A-Z`, `0-9`, as well as `_`. \n", "\n", "Symbol names cannot start with a number. \n", "\n", "Normal variables start with a letter. Those starting and ending with double underscore `_` have [special meaning](https://docs.python.org/3.8/reference/lexical_analysis.html#reserved-classes-of-identifiers) and should only be used in those special contexts (e.g. `__doc__`, or `__main__`).\n", "\n", "The convention is that variables start with a lower case character and [classes](https://docs.python.org/3/tutorial/classes.html) start with capitals. e.g.:\n", "\n", " my_var = 10\n", "\n", " class ClassName:\n", " \n", " .\n", " .\n", " .\n", " \n", "\n", "### Invalid names\n", "\n", "The following are *not* valid in names and will result in an error:\n", "\n", " * characters liable to intepretation (`SyntaxError: invalid syntax`), including (comma! `,`) and:\n", " \n", " +, -, *, **, =, $, ! etc.\n", " \n", " * extended characters (`SyntaxError: invalid character in identifier`) such as emojis\n", " \n", " πŸ˜€, ζˆ‘εœ¨θΏ™ι‡Œ etc.\n", " \n", "[Reserved keywords](https://docs.python.org/3.8/reference/lexical_analysis.html#keywords) cannot be used as variable names:\n", "\n", " False class finally is return\n", " None continue for lambda try\n", " True def from nonlocal while\n", " and del global not with\n", " as elif if or yield\n", " assert else import pass\n", " break except in raise\n", " \n", "as these have particular meanings in Python syntax.\n", "\n", "All of these can obviously be used as `values` in strings, just not as `key` names.\n", "\n", "See [https://docs.python.org/3.4/reference/lexical_analysis.html](https://docs.python.org/3.4/reference/lexical_analysis.html) for further details." ] }, { "cell_type": "markdown", "metadata": { "solution2": "hidden", "solution2_first": true }, "source": [ "#### Exercise 5\n", "\n", "* Make a code cell below\n", "* declare the variable `dash='\\n----------'` and print it\n", "* declare your own variables to contain the following values, trying to use a range of allowed names\n", "\n", " 1, 2, 'one', 'hello world', '1\\n2\\n3\\t 4 5 6\\nπŸ˜€, ζˆ‘εœ¨θΏ™ι‡Œ'\n", " \n", "* print the variables to see if they contain what you expect, followed in each instance by `dash` (to space the answers out)" ] }, { "cell_type": "code", "execution_count": 10, "metadata": { "solution2": "hidden" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "----------\n", "1 \n", "----------\n", "2 \n", "----------\n", "one \n", "----------\n", "hello world \n", "----------\n", "1\n", "2\n", "3\t 4 5 6\n", "πŸ˜€, ζˆ‘εœ¨θΏ™ι‡Œ \n", "----------\n" ] } ], "source": [ "# ANSWER\n", "\n", "# Make a code cell below\n", "# declare the variable dash='\\n----------' and print it\n", "dash='\\n----------'\n", "print(dash)\n", "\n", "# declare your own variables to contain the following values, trying to use a range of allowed names\n", "# 1, 2, 'one', 'hello world', '1\\n2\\n3\\t 4 5 6\\nπŸ˜€, ζˆ‘εœ¨θΏ™ι‡Œ'\n", "\n", "avar = 1\n", "bvar = 2\n", "one = 'one'\n", "Hello = 'hello world'\n", "string_thing = '1\\n2\\n3\\t 4 5 6\\nπŸ˜€, ζˆ‘εœ¨θΏ™ι‡Œ'\n", "\n", "#print the variables to see if they contain what you expect, followed in each instance by dash (to space the answers out)\n", "print(avar,dash)\n", "print(bvar,dash)\n", "print(one,dash)\n", "print(Hello,dash)\n", "print(string_thing,dash)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Summary\n", "\n", "In this section, you have had an introduction to the Python programming language, running in a [`jupyter notebook`](http://jupyter.org) environment.\n", "\n", "You have seen how to write comments in code, how to form `print` statements, `\\n` and `\\t` and basic concepts of variables and values.\n", "\n", "* Rules and conventions for symbol names.\n", "\n", "| command | purpose | \n", "|-|---|\n", "| `#` | hash symbol, followed by comments|\n", "| `print()` | print function|\n", "| `\\n` | newline character|\n", "| `\\t` | tab character|\n", "| `varname = value` | set variable `varname` to `value`|\n", "|`__doc__, __main__` | special method names |\n", "\n", "* variables start with a lower case character and classes start with capitals\n", "* Reserved keywords:\n", "\n", " False class finally is return\n", " None continue for lambda try\n", " True def from nonlocal while\n", " and del global not with\n", " as elif if or yield\n", " assert else import pass\n", " break except in raise\n", " \n", "\n", "\n", "\n", "\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "[](011_Python_data_types.ipynb)\n", "[](005_Packages.ipynb)\n", "\n", "\n" ] } ], "metadata": { "kernelspec": { "display_name": "Python [conda env:geog0111-geog0111]", "language": "python", "name": "conda-env-geog0111-geog0111-py" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.7.8" }, "latex_envs": { "LaTeX_envs_menu_present": true, "autocomplete": true, "bibliofile": "biblio.bib", "cite_by": "apalike", "current_citInitial": 1, "eqLabelWithNumbers": true, "eqNumInitial": 1, "hotkeys": { "equation": "Ctrl-E", "itemize": "Ctrl-I" }, "labels_anchors": false, "latex_user_defs": false, "report_style_numbering": false, "user_envs_cfg": false }, "toc": { "base_numbering": 1, "nav_menu": {}, "number_sections": false, "sideBar": false, "skip_h1_title": false, "title_cell": "Table of Contents", "title_sidebar": "Contents", "toc_cell": false, "toc_position": { "height": "calc(100% - 180px)", "left": "10px", "top": "150px", "width": "207px" }, "toc_section_display": false, "toc_window_display": false }, "varInspector": { "cols": { "lenName": 16, "lenType": 16, "lenVar": 40 }, "kernels_config": { "python": { "delete_cmd_postfix": "", "delete_cmd_prefix": "del ", "library": "var_list.py", "varRefreshCmd": "print(var_dic_list())" }, "r": { "delete_cmd_postfix": ") ", "delete_cmd_prefix": "rm(", "library": "var_list.r", "varRefreshCmd": "cat(var_dic_list()) " } }, "types_to_exclude": [ "module", "function", "builtin_function_or_method", "instance", "_Feature" ], "window_display": false } }, "nbformat": 4, "nbformat_minor": 4 }