{ "cells": [ { "cell_type": "markdown", "id": "52cb0aec", "metadata": {}, "source": [ "--- \n", " \n", "\n", "

Department of Data Science

\n", "

Course: Tools and Techniques for Data Science

\n", "\n", "---\n", "

Instructor: Muhammad Arif Butt, Ph.D.

" ] }, { "cell_type": "markdown", "id": "e224b328", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "

Lecture 2.2

" ] }, { "cell_type": "markdown", "id": "eaca51ac", "metadata": {}, "source": [ "\"Open" ] }, { "cell_type": "markdown", "id": "6065d4a7", "metadata": {}, "source": [ "## _01-hellojupyter.ipynb_" ] }, { "cell_type": "markdown", "id": "d01cae8f", "metadata": {}, "source": [ "### [Go to Jupyter.org](https://jupyter.org)\n", "### [Click to read Documentation](https://jupyter.readthedocs.io/en/latest/content-quickstart.html)" ] }, { "cell_type": "markdown", "id": "aa986aeb", "metadata": {}, "source": [ "## Learning agenda of this notebook\n", "1. A review of Jupyter notebook Interface\n", "2. Performing Arithmetic operations\n", "3. Use of comments\n", "4. Use of Built-in `print()` function\n", "5. Getting Help\n", "6. Running Bash Shell Commands in Jupyter notebook\n", "7. IPython Magic Commands" ] }, { "cell_type": "markdown", "id": "4cd487ed", "metadata": {}, "source": [ "## 1. A review of the Jupyter notebook Interface\n", "Jupyter Notebook previously called IPython Notebook is a web application that allows you to run live code, embed visualization and explonatory text all in one place. Jupyter notebooks (with a lower case 'n') are files with .ipynb extension containing JSON data\n", "1. **Header:** At the top of the notebook document is the header which contains the _notebook title_, _menu bar_, and _toolbar_, which are used to control notebook navigation and document structure.\n", "2. **Body:** The body of a notebook is composed of cells. Each cell contains either markdown, code input, code output, or raw text.\n", "3. **Types of cells:**\n", " - **Markdown cells** are used to build a nicely formatted narrative around the code in the document. These cells can either be rendered or unrendered. When they are rendered, a nice formatted representation of the cell's contents will be presented. When they are unrendered, the raw text source of the cell will be presented.\n", " - **Code cells** are used to define the computational code in the document. They come in two forms:\n", " - **Input cell** where the user types the code to be executed, and  \n", " - **output cell** which is the representation of the executed code. Depending on the code, this representation may be a simple scalar value, or something more complex like a plot or an interactive widget.\n", " -**Raw cells:** These are used when text needs to be included in raw form, without execution or transformation.\n", "4. **Modes of a cell:**\n", " - **Edit mode** is indicated by a **green** cell border and a prompt showing in the editor area. When a cell is in edit mode, you can type into the cell, like a normal text editor. Enter edit mode by pressing `Enter` or using the mouse to click on a cell's editor area.\n", " - **Command mode** is indicated by a **blue** cell border. When in command mode, the structure of the notebook can be modified as a whole, but the text in individual cells cannot be changed. Most importantly, the keyboard is mapped to a set of shortcuts for efficiently performing notebook and cell actions. Enter command mode by pressing `Esc` or using the mouse to click *outside* a cell's editor area.\n", "\n", "5. **Keyboard Short cuts:** Keyboard shortcuts are a very popular aspect of the Jupyter environment because they facilitate a speedy cell-based workflow. Following shortcuts work in command mode:\n", " - Press H to see the list of short cuts\n", " - Shift+Enter to execute code of a code-cell and to render the contents of a markdown cell. It also shifts control to cell down. If there is none it creates one. To avoid shifting control to lower cell after you execute a cell code use instead\n", " - Scroll up and down your cells with your Up and Down keys.\n", " - Press A or B to insert a new cell above or below the active cell.\n", " - DD (D twice) will delete the active cell.\n", " - L to toggle view linenumbers within a code cell\n", " - Z will undo cell deletion. \n", " - M will transform the active cell to a Markdown cell.\n", " - Y will set the active cell to a code cell.\n", " - to toggle between commenting and uncommenting the current LOC or highlighted LOCs\n", " - Hold Shift and press Up or Down to select multiple cells at once. With multiple cells selected, Shift + M will merge your selection." ] }, { "cell_type": "markdown", "id": "52571bcd", "metadata": {}, "source": [ "## 2. Performing Arithmetic Operations using Python\n", "\n", "Let's begin by using Python as a calculator. You can write and execute Python using a code cell within Jupyter. \n", "\n", "> **Working with cells**: To create a new cell within Jupyter, you can select \"Insert > Insert Cell Below\" from the menu bar or just press the \"+\" button on the toolbar. You can also use the keyboard shortcut `Esc+B` to create a new cell. Once a cell is created, click on it to select it. You can then change the cell type to code or markdown (text) using the \"Cell > Cell Type\" menu option. You can also use the keyboard shortcuts `Esc+Y` and `Esc+M`. Double-click a cell to edit the content within the cell. To apply your changes and run a cell, use the \"Cell > Run Cells\" menu option or click the \"Run\" button on the toolbar or just use the keyboard shortcut `Shift+Enter`. You can see a full list of keyboard shortcuts using the \"Help > Keyboard Shortcuts\" menu option.\n", "\n", "Run the code cells below to perform calculations and view their result. Try changing the numbers and run the modified cells again to see updated results." ] }, { "cell_type": "code", "execution_count": 7, "id": "39d7d785", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'hello Jupyter: JUlia PYThon R'" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "'hello Jupyter: JUlia PYThon R'" ] }, { "cell_type": "markdown", "id": "b8b3fed5", "metadata": {}, "source": [ "Python supports the following arithmetic operators:\n", "\n", "| Operator | Purpose | Example | Result |\n", "|------------|-------------------|-------------|-----------|\n", "| `+` | Addition | `2 + 3` | `5` |\n", "| `-` | Subtraction | `3 - 2` | `1` |\n", "| `*` | Multiplication | `8 * 12` | `96` |\n", "| `/` | Division | `100 / 7` | `14.28..` |\n", "| `//` | Floor Division | `100 // 7` | `14` | \n", "| `%` | Modulus/Remainder | `100 % 7` | `2` |\n", "| `**` | Exponent | `5 ** 3` | `125` |\n" ] }, { "cell_type": "code", "execution_count": 25, "id": "a0f2df50", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "14" ] }, "execution_count": 25, "metadata": {}, "output_type": "execute_result" } ], "source": [ "2 + 3 + 9" ] }, { "cell_type": "code", "execution_count": 26, "id": "bc5fabdd", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "26" ] }, "execution_count": 26, "metadata": {}, "output_type": "execute_result" } ], "source": [ "99 - 73" ] }, { "cell_type": "code", "execution_count": 27, "id": "ea7b88ba", "metadata": { "scrolled": true }, "outputs": [ { "data": { "text/plain": [ "-33709.28" ] }, "execution_count": 27, "metadata": {}, "output_type": "execute_result" } ], "source": [ "23.54 * -1432" ] }, { "cell_type": "code", "execution_count": 28, "id": "1373d987", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "14.285714285714286" ] }, "execution_count": 28, "metadata": {}, "output_type": "execute_result" } ], "source": [ "100 / 7" ] }, { "cell_type": "code", "execution_count": 29, "id": "cea673fe", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "14" ] }, "execution_count": 29, "metadata": {}, "output_type": "execute_result" } ], "source": [ "100 // 7" ] }, { "cell_type": "code", "execution_count": 30, "id": "e5e1cb18", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "2" ] }, "execution_count": 30, "metadata": {}, "output_type": "execute_result" } ], "source": [ "100 % 7" ] }, { "cell_type": "code", "execution_count": 31, "id": "92fed413", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "125" ] }, "execution_count": 31, "metadata": {}, "output_type": "execute_result" } ], "source": [ "5 ** 3" ] }, { "cell_type": "markdown", "id": "617a4432", "metadata": {}, "source": [ "As you might expect, operators like `/` and `*` take precedence over other operators like `+` and `-` as per mathematical conventions. You can use parentheses, i.e. `(` and `)`, to specify the order in which operations are performed." ] }, { "cell_type": "code", "execution_count": 32, "id": "52524d6c", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "1.53125" ] }, "execution_count": 32, "metadata": {}, "output_type": "execute_result" } ], "source": [ "((2 + 5) * (17 - 3)) / (4 ** 3)" ] }, { "cell_type": "markdown", "id": "b6342788", "metadata": {}, "source": [ "## 3. Use of Comments\n", "Note that we're using the `#` character to add *comments* within our code. \n", "\n", "> **Comments**: Comments and blank lines are ignored during execution, but they are useful for providing information to humans (including yourself) about what the code does. Comments can be inline (at the end of some code), on a separate line, or even span multiple lines. \n", "\n", "Inline and single-line comments start with `#`, whereas multi-line comments begin and end with three quotes, i.e. `\"\"\"`. Here are some examples of code comments:" ] }, { "cell_type": "code", "execution_count": 9, "id": "1bf354ab", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "10" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# This is a single line comment\n", "# Keyboard shortcut to comment/un-comment some LOC(s) is \n", "\n", "\"\"\"\n", "A multi-line comment starts and ends with a tripple double quotes\n", "A docstring is a documentation string. As a comment, this Python Syntax is used to explain code.\n", "But unlike comments, they are more specific. Also, they are retained at runtime.\n", "This way, the programmer can inspect them at runtime. Delimit a docstring using three double-quotes. \n", "\"\"\"\n", "\n", "'''\n", "A multi-line comment can also starts and ends with a tripple single quotes\n", "'''\n", "x=10 # A comment ends with newline\n", "x" ] }, { "cell_type": "markdown", "id": "b4933e01", "metadata": {}, "source": [ "## 4. Use of Built-in `print()` Function\n", "- **`print`**: The `print` is a Python built-in function that is used to display information. It takes one or more inputs, which can be text (within quotes, e.g., `\"this is some text\"`), numbers, variables, mathematical expressions, etc. We'll learn more about variables the next tutorial.\n", "\n", "- Jupyter allows you to write multiple lines of code within a single code cell. However, the result of the last line of code within a cell is displayed as the output. \n", "\n", "* Python `print()` function receives variable number of comma separated values and all the comma separated elements/variables get printed on the output separated by spaces (by default)\n", "- To find out the arguments that you can pass to a function or method in IPython, just place the cursor inside parenthesis and hit once: Displays a brief signature with doc string\n", " - Tab> twice: Displays a larger frame to display more information\n", " - Tab> thrice: Displays the information for a longer duration\n", " - Tab> fourth time: The information takes almost half of your screen and you can resize it for longer usage\n" ] }, { "cell_type": "code", "execution_count": 2, "id": "2e203634", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Arif Butt'" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Note only the last command appears in output\n", "age = 50\n", "name = \"Arif Butt\"\n", "age\n", "name" ] }, { "cell_type": "code", "execution_count": 14, "id": "f01c99dd", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "50\n", "Arif Butt\n" ] } ], "source": [ "# Solution is to use print()\n", "print(age)\n", "print(name)" ] }, { "cell_type": "code", "execution_count": 15, "id": "4e8a7cf3", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Hello Mr. Arif Butt'" ] }, "execution_count": 15, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# You can use `+` operator to concatenage two or more strings\n", "'Hello Mr. ' + name" ] }, { "cell_type": "code", "execution_count": 17, "id": "8d34507e", "metadata": {}, "outputs": [ { "ename": "TypeError", "evalue": "can only concatenate str (not \"int\") to str", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m/var/folders/1t/g3ylw8h50cjdqmk5d6jh1qmm0000gn/T/ipykernel_9663/2630918959.py\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0;31m# However, you cannot use `+` operator on numbers\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 2\u001b[0;31m \u001b[0;34m\"Hello Mr. \"\u001b[0m \u001b[0;34m+\u001b[0m \u001b[0mname\u001b[0m \u001b[0;34m+\u001b[0m \u001b[0;34m', you are '\u001b[0m \u001b[0;34m+\u001b[0m \u001b[0mage\u001b[0m \u001b[0;34m+\u001b[0m \u001b[0;34m'years old'\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mTypeError\u001b[0m: can only concatenate str (not \"int\") to str" ] } ], "source": [ "# However, you cannot use `+` operator on numbers\n", "\"Hello Mr. \" + name + ', you are ' + age + 'years old'" ] }, { "cell_type": "markdown", "id": "71219144", "metadata": {}, "source": [ "### a. Using Format String in `print()` Function" ] }, { "cell_type": "markdown", "id": "56112182", "metadata": {}, "source": [ "- **Use Format String: (C Style)**\n", " - Use the **`%s`** symbol as a place holder for the value of a variable in the format string of the `print()` function. \n", " - Use `%s` inside the string where you want a value to appear. After the string, put a `%` operator and mention the identifiers in parenthesis." ] }, { "cell_type": "code", "execution_count": 4, "id": "28059871", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Hello Mr. Arif Butt, you are 50 years old.'" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "str = \"Hello Mr. %s, you are %s years old.\" %(name, age)\n", "str" ] }, { "cell_type": "code", "execution_count": 5, "id": "0c5297a0", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hello Mr. Arif Butt, you are 50 years old.\n" ] } ], "source": [ "# The format string can be used in `print()`\n", "print(\"Hello Mr. %s, you are %s years old.\" %(name, age))" ] }, { "cell_type": "markdown", "id": "a578f0c1", "metadata": {}, "source": [ "- **Use `string.format()` method:** (Python Style)\n", " - Place the index (0, 1, 2, ...) in curly braces inside the string where you want a value to appear. \n", " - Call the `format()` method on the string using the dot operator and mention the identifiers in parenthesis" ] }, { "cell_type": "code", "execution_count": 33, "id": "0c20c376", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hello Mr. Arif Butt, you are 50 years old.\n" ] } ], "source": [ "age = 50; name = \"Arif Butt\"\n", "print(\"Hello Mr. {}, you are {} years old.\" .format(name, age))" ] }, { "cell_type": "code", "execution_count": 35, "id": "10b9757a", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hello Mr. Arif Butt, you are 51 years old.\n" ] } ], "source": [ "# You can mention indices of variables passed to format() function, if you want a different \n", "# sequence as in following example\n", "age = 51; name = \"Arif Butt\"\n", "\n", "print(\"Hello Mr. {1}, you are {0} years old.\" .format(age, name))" ] }, { "cell_type": "code", "execution_count": 9, "id": "f913b8d4", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hello Mr. Kakamanna, you are 23 years old.\n" ] } ], "source": [ "# Another way of passing argument to format method\n", "print(\"Hello Mr. {name}, you are {age} years old.\" .format(name=\"Kakamanna\",age=23))" ] }, { "cell_type": "markdown", "id": "cf095e4a", "metadata": {}, "source": [ "### b. Using Escape Sequence in Format String\n", "- Escape sequences are special commands that tell Python to either\n", " - Suppress special meaning of some character or symbol in a string\n", " - Give an otherwise ordinary character a special meaning\n", "- For example, a single or double quote has special meanings, i.e., are used to define a string. To make them part of a string you have to suppress the special meaning by preceding the character by a back slash `\\`" ] }, { "cell_type": "code", "execution_count": 40, "id": "7bfe1f4b", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "It's my birthday\n" ] } ], "source": [ "#print('It's my birthday') # This will flag an error\n", "print('It\\'s my birthday')" ] }, { "cell_type": "code", "execution_count": 41, "id": "22cbd4c6", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hello\tWorld\n", "Hello\n", "World\n" ] } ], "source": [ "# Similarly, we can give an ordinary character 't' and 'n', special meanings by preceding them by a back slash\n", "print('Hello\\tWorld')\n", "print('Hello\\nWorld')" ] }, { "cell_type": "markdown", "id": "34cda13b", "metadata": {}, "source": [ "### c. Using `sep` parameter of `print()` Function\n", "- By default `print()` insert a space character between values.\n", "- You can change this default behavior using the `sep` parameter and assign it any character/string you want to used instead of space character" ] }, { "cell_type": "code", "execution_count": 25, "id": "de24c7c8", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Arif Butt 50\n" ] } ], "source": [ "age = 50\n", "name = \"Arif Butt\"\n", "print(name, age)\n" ] }, { "cell_type": "code", "execution_count": 37, "id": "b5669679", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Arif Butt hello 50\n" ] } ], "source": [ "age = 50\n", "name = \"Arif Butt\"\n", "print(name, age, sep=' : ')\n" ] }, { "cell_type": "markdown", "id": "eff8699d", "metadata": {}, "source": [ "### d. Using `end` parameter of `print()` function\n", "- By default when `print()` statement is done printing the output, it appends a newline character at the end. Hence, we get the output of each print statement in different line.\n", "- You can change this default behavior using the `end` parameter and assign it the character/string you want to use instead of newline character " ] }, { "cell_type": "code", "execution_count": 27, "id": "5ef6b0ca", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Arif Butt\n", "50\n" ] } ], "source": [ "age = 50\n", "name = \"Arif Butt\"\n", "print(name)\n", "print(age)\n" ] }, { "cell_type": "code", "execution_count": 39, "id": "0a0d6603", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Arif Butt 50\n" ] } ], "source": [ "age = 50\n", "name = \"Arif Butt\"\n", "print(name, end=' ')\n", "print(age)\n" ] }, { "cell_type": "markdown", "id": "08562aef", "metadata": {}, "source": [ "## 5. Getting Help in IPython\n", "Within IPython you have various way to access help:\n", "- `?` Introduction and overview of IPython's features (this screen).\n", "- `?object` Details about 'object'.\n", "- `help(object)` Access Python's own help system.\n", "- `help()` Interactive help utility" ] }, { "cell_type": "code", "execution_count": 17, "id": "bfa863b6", "metadata": {}, "outputs": [], "source": [ "?" ] }, { "cell_type": "code", "execution_count": 18, "id": "4293f426", "metadata": {}, "outputs": [], "source": [ "?print" ] }, { "cell_type": "code", "execution_count": 19, "id": "0517542e", "metadata": {}, "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": "code", "execution_count": 14, "id": "06381fb4", "metadata": { "scrolled": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "Welcome to Python 3.8's help utility!\n", "\n", "If this is your first time using Python, you should definitely check out\n", "the tutorial on the Internet at https://docs.python.org/3.8/tutorial/.\n", "\n", "Enter the name of any module, keyword, or topic to get help on writing\n", "Python programs and using Python modules. To quit this help utility and\n", "return to the interpreter, just type \"quit\".\n", "\n", "To get a list of available modules, keywords, symbols, or topics, type\n", "\"modules\", \"keywords\", \"symbols\", or \"topics\". Each module also comes\n", "with a one-line summary of what it does; to list the modules whose name\n", "or summary contain a given string such as \"spam\", type \"modules spam\".\n", "\n", "help> quit\n", "\n", "You are now leaving help and returning to the Python interpreter.\n", "If you want to ask for help on a particular object directly from the\n", "interpreter, you can type \"help(object)\". Executing \"help('string')\"\n", "has the same effect as typing a particular string at the help> prompt.\n" ] } ], "source": [ "# Get help about \"keywords\", \"symbols\", \"topics\", ...\n", "# Type \"quit\" to exit this interactive command\n", "help()" ] }, { "cell_type": "markdown", "id": "33375f96", "metadata": {}, "source": [ "## 6. Running bash shell commands\n", "- If you are using a Linux or Mac OS, you can use the powerfull bash shell commands by preceding the commands by a `!` sign" ] }, { "cell_type": "code", "execution_count": 42, "id": "b783dc85", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "/Users/arif/Documents/0-DS-522/Demo-Files-Repo/Section-2-Basics-of-Python-Programming/Lec-2.02-Anaconda-and-Jupyter-Notebook\n", "Thu Dec 2 09:01:35 PKT 2021\n", "01-hellojupyter.ipynb \u001b[34mddd\u001b[m\u001b[m \u001b[34mimages\u001b[m\u001b[m\n", "02-markdown-example.ipynb f1.txt newfile\n", "This is fun..\n", "#!/usr/bin/python\n", "ctr = 1\n", "while ctr <= 5 :\n", "\tprint(ctr)\n", "\tctr = ctr + 1\n" ] } ], "source": [ "!pwd\n", "!date\n", "!touch f1.txt\n", "! ls\n", "! echo \"This is fun..\"\n", "! cat ../Lec-2.01-Introduction-to-Python/first.py" ] }, { "cell_type": "markdown", "id": "77943be1", "metadata": {}, "source": [ "## 6. IPython Magic Commands\n", "- The Jupyter notebook has a set of predefined magic functions like cd, ls, ...... You can use them if you are good at working on command line shells\n", "- There are two kinds\n", " - **Line magics** are prefixed with the **`%`** character, and work much like OS command-line calls: they get as an argument the rest of the line, where arguments are passed without parentheses or quotes\n", " - **Cell magics** are prefixed with a double **`%%`** character, and they are functions that get as an argument not only the rest of the line, but also the lines below it in a separate argument. These magics are called with two arguments: the rest of the call line and the body of the cell, consisting of the lines below the first." ] }, { "cell_type": "markdown", "id": "248b4c16", "metadata": {}, "source": [ "### a. Line Magic Commands" ] }, { "cell_type": "code", "execution_count": 35, "id": "514ad6fc", "metadata": {}, "outputs": [ { "data": { "application/json": { "cell": { "!": "OSMagics", "HTML": "Other", "SVG": "Other", "bash": "Other", "capture": "ExecutionMagics", "debug": "ExecutionMagics", "file": "Other", "html": "DisplayMagics", "javascript": "DisplayMagics", "js": "DisplayMagics", "latex": "DisplayMagics", "markdown": "DisplayMagics", "perl": "Other", "prun": "ExecutionMagics", "pypy": "Other", "python": "Other", "python2": "Other", "python3": "Other", "ruby": "Other", "script": "ScriptMagics", "sh": "Other", "svg": "DisplayMagics", "sx": "OSMagics", "system": "OSMagics", "time": "ExecutionMagics", "timeit": "ExecutionMagics", "writefile": "OSMagics" }, "line": { "alias": "OSMagics", "alias_magic": "BasicMagics", "autoawait": "AsyncMagics", "autocall": "AutoMagics", "automagic": "AutoMagics", "autosave": "KernelMagics", "bookmark": "OSMagics", "cat": "Other", "cd": "OSMagics", "clear": "KernelMagics", "colors": "BasicMagics", "conda": "PackagingMagics", "config": "ConfigMagics", "connect_info": "KernelMagics", "cp": "Other", "debug": "ExecutionMagics", "dhist": "OSMagics", "dirs": "OSMagics", "doctest_mode": "BasicMagics", "ed": "Other", "edit": "KernelMagics", "env": "OSMagics", "gui": "BasicMagics", "hist": "Other", "history": "HistoryMagics", "killbgscripts": "ScriptMagics", "ldir": "Other", "less": "KernelMagics", "lf": "Other", "lk": "Other", "ll": "Other", "load": "CodeMagics", "load_ext": "ExtensionMagics", "loadpy": "CodeMagics", "logoff": "LoggingMagics", "logon": "LoggingMagics", "logstart": "LoggingMagics", "logstate": "LoggingMagics", "logstop": "LoggingMagics", "ls": "Other", "lsmagic": "BasicMagics", "lx": "Other", "macro": "ExecutionMagics", "magic": "BasicMagics", "man": "KernelMagics", "matplotlib": "PylabMagics", "mkdir": "Other", "more": "KernelMagics", "mv": "Other", "notebook": "BasicMagics", "page": "BasicMagics", "pastebin": "CodeMagics", "pdb": "ExecutionMagics", "pdef": "NamespaceMagics", "pdoc": "NamespaceMagics", "pfile": "NamespaceMagics", "pinfo": "NamespaceMagics", "pinfo2": "NamespaceMagics", "pip": "PackagingMagics", "popd": "OSMagics", "pprint": "BasicMagics", "precision": "BasicMagics", "prun": "ExecutionMagics", "psearch": "NamespaceMagics", "psource": "NamespaceMagics", "pushd": "OSMagics", "pwd": "OSMagics", "pycat": "OSMagics", "pylab": "PylabMagics", "qtconsole": "KernelMagics", "quickref": "BasicMagics", "recall": "HistoryMagics", "rehashx": "OSMagics", "reload_ext": "ExtensionMagics", "rep": "Other", "rerun": "HistoryMagics", "reset": "NamespaceMagics", "reset_selective": "NamespaceMagics", "rm": "Other", "rmdir": "Other", "run": "ExecutionMagics", "save": "CodeMagics", "sc": "OSMagics", "set_env": "OSMagics", "store": "StoreMagics", "sx": "OSMagics", "system": "OSMagics", "tb": "ExecutionMagics", "time": "ExecutionMagics", "timeit": "ExecutionMagics", "unalias": "OSMagics", "unload_ext": "ExtensionMagics", "who": "NamespaceMagics", "who_ls": "NamespaceMagics", "whos": "NamespaceMagics", "xdel": "NamespaceMagics", "xmode": "BasicMagics" } }, "text/plain": [ "Available line magics:\n", "%alias %alias_magic %autoawait %autocall %automagic %autosave %bookmark %cat %cd %clear %colors %conda %config %connect_info %cp %debug %dhist %dirs %doctest_mode %ed %edit %env %gui %hist %history %killbgscripts %ldir %less %lf %lk %ll %load %load_ext %loadpy %logoff %logon %logstart %logstate %logstop %ls %lsmagic %lx %macro %magic %man %matplotlib %mkdir %more %mv %notebook %page %pastebin %pdb %pdef %pdoc %pfile %pinfo %pinfo2 %pip %popd %pprint %precision %prun %psearch %psource %pushd %pwd %pycat %pylab %qtconsole %quickref %recall %rehashx %reload_ext %rep %rerun %reset %reset_selective %rm %rmdir %run %save %sc %set_env %store %sx %system %tb %time %timeit %unalias %unload_ext %who %who_ls %whos %xdel %xmode\n", "\n", "Available cell magics:\n", "%%! %%HTML %%SVG %%bash %%capture %%debug %%file %%html %%javascript %%js %%latex %%markdown %%perl %%prun %%pypy %%python %%python2 %%python3 %%ruby %%script %%sh %%svg %%sx %%system %%time %%timeit %%writefile\n", "\n", "Automagic is ON, % prefix IS NOT needed for line magics." ] }, "execution_count": 35, "metadata": {}, "output_type": "execute_result" } ], "source": [ "%lsmagic" ] }, { "cell_type": "code", "execution_count": 38, "id": "dc6dcfd8", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'/Users/arif/Documents/0-DS-522/Demo-Files-Repo/Section-2-Basics-of-Python-Programming/Lec-2.02-Anaconda-and-Jupyter-Notebook'" ] }, "execution_count": 38, "metadata": {}, "output_type": "execute_result" } ], "source": [ "%pwd" ] }, { "cell_type": "code", "execution_count": 39, "id": "7c9db7fd", "metadata": {}, "outputs": [], "source": [ "%mkdir ddd" ] }, { "cell_type": "code", "execution_count": 40, "id": "b6df2eec", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "01-hellojupyter.ipynb f1.txt\r\n", "02-markdown-example.ipynb \u001b[34mimages\u001b[m\u001b[m/\r\n", "\u001b[34mddd\u001b[m\u001b[m/\r\n" ] } ], "source": [ "%ls" ] }, { "cell_type": "code", "execution_count": 41, "id": "13150876", "metadata": {}, "outputs": [], "source": [ "%alias msg echo \"Learning is fun with Arif Butt\"" ] }, { "cell_type": "code", "execution_count": 42, "id": "664a6994", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Learning is fun with Arif Butt'" ] }, "execution_count": 42, "metadata": {}, "output_type": "execute_result" } ], "source": [ "msg" ] }, { "cell_type": "markdown", "id": "b112e056", "metadata": {}, "source": [ "- If you want to view a program file while you are inside Jupyter notebook,, use the **`%pycat`** line magic" ] }, { "cell_type": "code", "execution_count": 1, "id": "8bae0f0d", "metadata": {}, "outputs": [], "source": [ "%pycat ../Lec-2.01-Introduction-to-Python/fibo_series.py" ] }, { "cell_type": "markdown", "id": "dac34ec6", "metadata": {}, "source": [ "- If you want to run a python file inside Jupyter notebook and just want to see its output use the **`%run`** line magic" ] }, { "cell_type": "code", "execution_count": 71, "id": "ca44f7b2", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Fibonacci Series: 0 1 1 2 3 5 8 \n" ] } ], "source": [ "%run ../Lec-2.01-Introduction-to-Python/fibo_series" ] }, { "cell_type": "markdown", "id": "aaaf90cb", "metadata": {}, "source": [ "- If you want to load a python file in a cell of Jupyter notebook, use the **`%load`** line magic\n", "- The load magic command when executed will load the file contents in the cell and automatically comment itself :)\n", "- ```%load ../Lec-2.01-Introduction-to-Python/fibo_series.py```" ] }, { "cell_type": "code", "execution_count": 52, "id": "7f77264e", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Fibonacci Series: 0 1 1 2 3 5 8 \n" ] } ], "source": [ "# %load ../Lec-2.01-Introduction-to-Python/fibo_series.py\n", "#Iterative Fibonacci Series\n", "def fibo_series(n):\n", " a=1\n", " b=1\n", " print(\"Fibonacci Series: \", end=' ')\n", " if n<1:\n", " print(\"Incorrect input\")\n", " elif n==1:\n", " print('0', end=' ')\n", " elif n==2:\n", " print('0','1', end=' ')\n", " else:\n", " print('0',a,b,end=' ')\n", " for i in range(n-3):\n", " c = a + b\n", " print(c, end=' ')\n", " a = b \n", " b = c\n", " print() \n", " \n", "fibo_series(7)" ] }, { "cell_type": "code", "execution_count": 48, "id": "d91b5878", "metadata": { "collapsed": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "# Note only the last command appears in output\n", "age = 50\n", "msg = \"Arif Butt\"\n", "age\n", "msg\n", "# You can use `+` operator to concatenage things\n", "name + age\n", "# Note only the last command appears in output\n", "age = 50\n", "name = \"Arif Butt\"\n", "age\n", "name\n", "# You can use `+` operator to concatenage things\n", "name + age\n", "# You can use `+` operator to concatenage things\n", "name + $age\n", "# You can use `+` operator to concatenage things\n", "'Hello Mr. ' + name\n", "# You can use `+` operator to concatenage things\n", "\"Hello Mr. \" + name ', you are ' + age + 'years old'\n", "# You can use `+` operator to concatenage things\n", "\"Hello Mr. \" + name + ', you are ' + age + 'years old'\n", "\"Hello Mr. %s, you are %s years old.' %(name, age)\n", "\"Hello Mr. %s, you are %s years old.\"\" %(name, age)\n", "\"Hello Mr. %s, you are %s years old. %(name, age)\n", "\"Hello Mr. %s, you are %s years old.\" %(name, age)\n", "# Solution is to use print()\n", "print(name, age)\n", "b=a-5\n", "c=a+b\n", "print(\"a = \", a)\n", "print(\"b = \", b)\n", "print(\"c = \", c)\n", "# You can also fit in more than one statement on one line by separating them with a semicolon.\n", "d = 5 + 3; print('d = ', d)\n", "# Solution is to use print()\n", "print(age)\n", "print(name)\n", "# You can use `+` operator to concatenage two or more strings\n", "'Hello Mr. ' + name\n", "# You can use `+` operator to concatenage strings\n", "\"Hello Mr. \" + name + ', you are ' + age + 'years old'\n", "# However, you cannot use `+` operator on numbers\n", "\"Hello Mr. \" + name + ', you are ' + age + 'years old'\n", "# Solution is to use a format string with `%s` format specifier\n", "\"Hello Mr. %s, you are %s years old.\" %(name, age)\n", "# Solution is to use a format string with `%s` format specifier (C style)\n", "str = \"Hello Mr. %s, you are %s years old.\" %(name, age)\n", "# The format string can be used in `print()`\n", "print(str)\n", "# The format string can be used in `print()`\n", "print(\"Hello Mr. %s, you are %s years old.\" %(name, age))\n", "age = 50\n", "name = \"Arif Butt\"\n", "print(name, age)\n", "age = 50\n", "name = \"Arif Butt\"\n", "print(name, age, sep='\\n')\n", "age = 50\n", "name = \"Arif Butt\"\n", "print(name, age, sep=' : ')\n", "print(name, age, sep='\\n')\n", "age = 50\n", "name = \"Arif Butt\"\n", "print(name, age)\n", "age = 50\n", "name = \"Arif Butt\"\n", "print(name, age, sep=' : ')\n", "print(name, age, sep='\\n')\n", "age = 50\n", "name = \"Arif Butt\"\n", "print(name)\n", "print(age)\n", "age = 50\n", "name = \"Arif Butt\"\n", "print(name, end=' ')\n", "print(age)\n", "# Option 2: \n", "age = 50; name = \"Arif Butt\"\n", "print(\"Hello Mr. {}.\".format(name))\n", "print(\"Mr. {}, you are {} years old.\" .format(name, age))\n", "# Option 2: \n", "age = 50, name = \"Arif Butt\"\n", "print(\"Hello Mr. {}.\".format(name))\n", "print(\"Mr. {}, you are {} years old.\" .format(name, age))\n", "# Option 2: \n", "age = 50; name = \"Arif Butt\"\n", "print(\"Hello Mr. {}.\".format(name))\n", "print(\"Mr. {}, you are {} years old.\" .format(name, age))\n", "# Option 2: \n", "age = 50; name = \"Arif Butt\"\n", "print(\"Mr. {}, you are {} years old.\" .format(name, age))\n", "# Option 2: \n", "age = 50; name = \"Arif Butt\"\n", "print(\"Hello Mr. {}, you are {} years old.\" .format(name, age))\n", "# Option 2: You can mention indices of variables passed to format() function, if you want a different \n", "# sequence as in following example\n", "age = 51; name = \"Arif Butt\"\n", "\n", "print(\"Mr. {1}, you are {0} years old.\" .format(age, name))\n", "# Option 2: You can mention indices of variables passed to format() function, if you want a different \n", "# sequence as in following example\n", "age = 51; name = \"Arif Butt\"\n", "\n", "print(\"Hello Mr. {1}, you are {0} years old.\" .format(age, name))\n", "age = 50\n", "name = \"Arif Butt\"\n", "print(name, age, sep=' : ')\n", "age = 50\n", "name = \"Arif Butt\"\n", "print(name, age, sep=' hello ')\n", "age = 50\n", "name = \"Arif Butt\"\n", "print(name, end=' bbbb ')\n", "print(age)\n", "age = 50\n", "name = \"Arif Butt\"\n", "print(name, end=' ')\n", "print(age)\n", "#print('It's my birthday') # This will flag an error\n", "print('It\\'s my birthday')\n", "# Similarly, we can give an ordinary character 't' and 'n', special meanings by preceding them by a back slash\n", "print('Hello\\tWorld')\n", "print('Hello\\nWorld')\n", "!pwd\n", "!date\n", "!touch f1.txt\n", "! ls\n", "! echo \"This is fun..\"\n", "! cat ../Lec-2.01-Introduction-to-Python/first.py\n", "dir(__builtins__)\n", "import math\n", "??math\n", "import math\n", "?math\n", "dir(math)\n", "pow()\n", "%history\n" ] } ], "source": [ "%history" ] }, { "cell_type": "markdown", "id": "a9d741b2", "metadata": {}, "source": [ ">- If you want to check out the time taken by a Python command to execute , use the **%time** line magic\n", ">- The load magic command when executed will load the file contents in the cell and automatically comment itself :)\n", ">- ```%load ../Lec-2.01-Introduction-to-Python/fibo_series.py```" ] }, { "cell_type": "code", "execution_count": 64, "id": "ba55532b", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "hello jupyter\n", "CPU times: user 287 µs, sys: 136 µs, total: 423 µs\n", "Wall time: 357 µs\n" ] } ], "source": [ "%time print(\"hello jupyter\")" ] }, { "cell_type": "code", "execution_count": 55, "id": "7dd330ed", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "CPU times: user 345 ms, sys: 2.96 ms, total: 348 ms\n", "Wall time: 347 ms\n" ] } ], "source": [ "%time for i in range(10000000): pass" ] }, { "cell_type": "markdown", "id": "1da2adda", "metadata": {}, "source": [ "### b. Cell Magic Commands" ] }, { "cell_type": "code", "execution_count": 93, "id": "f7f66ed3", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "My shell is: /bin/bash\n", "Wed Dec 1 22:06:28 PKT 2021\n", "/Users/arif/Documents/0-DS-522/Demo-Files-Repo/Section-2-Basics-of-Python-Programming/Lec-2.02-Anaconda-and-Jupyter-Notebook\n", "Khurram,\n", "Idrees,\n", "Waheed,\n", "Nadeem\n" ] } ], "source": [ "%%bash\n", "echo \"My shell is:\" $SHELL\n", "touch newfile\n", "date\n", "pwd\n", "for friends in 'Khurram', 'Idrees', 'Waheed', 'Nadeem'\n", " do\n", " echo $friends\n", " done" ] }, { "cell_type": "code", "execution_count": 96, "id": "1c010bfb", "metadata": {}, "outputs": [ { "data": { "text/html": [ "

Students, there is no shortcut to hardwork

\n", "

This is text

\n" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "%%html\n", "

Students, there is no shortcut to hardwork

\n", "

This is text

" ] }, { "cell_type": "code", "execution_count": 84, "id": "3d3ebb3c", "metadata": { "scrolled": true }, "outputs": [ { "data": { "application/javascript": [ "let msg=\"Learning is fun with Arif\"\n", "alert(msg)\n" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "%%javascript\n", "let msg=\"Learning is fun with Arif\"\n", "alert(msg)" ] }, { "cell_type": "code", "execution_count": 6, "id": "b7dafc13", "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "%%HTML\n", "" ] }, { "cell_type": "code", "execution_count": null, "id": "47e7d923", "metadata": {}, "outputs": [], "source": [ "allowfullscreen" ] }, { "cell_type": "markdown", "id": "638dbd0b", "metadata": {}, "source": [ "## For more deatils check out `%quickref`" ] }, { "cell_type": "code", "execution_count": 57, "id": "eb27b46d", "metadata": {}, "outputs": [], "source": [ "%quickref" ] }, { "cell_type": "markdown", "id": "11f602ee", "metadata": {}, "source": [ "## Check your Concepts\n", "\n", "Try answering the following questions to test your understanding of the topics covered in this notebook:\n", "\n", "1. What is a Jupyter notebook? \n", "2. How do you add a new code cell below an existing cell?\n", "3. How do you add a new Markdown cell below an existing cell?\n", "4. How do you convert a code cell to a Markdown cell or vice versa?\n", "5. How do you execute a code cell within Jupyter?\n", "6. What is Markdown? Why is it useful?\n", "7. How do you create headings of different sizes using Markdown?\n", "8. How do you create bulleted and numbered lists using Markdown?\n", "9. How do you create bold or italic text using Markdown?\n", "10. How do you include links & images within Markdown cells?\n", "11. How do you include code blocks within Markdown cells?\n", "12. Is it possible to execute the code blocks within Markdown cells?\n", "13. How to run operating system commands from a notebook cell?\n", "14. Mention three different ways to get help about built-in Python functions from a notebook cell? \n", "15. What different arithmetic operators are available in Python?\n", "16. Explore different line and cell magic functions of IPython" ] }, { "cell_type": "code", "execution_count": null, "id": "ddc20b05", "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "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.9.7" } }, "nbformat": 4, "nbformat_minor": 5 }