{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "### Simple while loop" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "n = 23\n", "r = True\n", "\n", "while r:\n", " guess= int(input('Enter an integer: '))\n", " \n", " if guess == n:\n", " print('yes')\n", " r = False\n", " elif guess < n:\n", " print('no')\n", " else:\n", " print('no1')\n", "else:\n", " print('done')\n", " \n", "print('yes done') " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Simple backup" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "created today\n", "Zip command is:\n", "zip -r /home/akash/funny3zip/20200624/145038.zip / h o m e / a k a s h / f u n n y 3\n", "Running:\n", "Backup FAILED\n" ] } ], "source": [ "import os\n", "import time\n", "\n", "source = '/home/akash/funny3'\n", "\n", "target = '/home/akash/funny3zip'\n", "\n", "if not os.path.exists(target): \n", " os.mkdir(target)\n", " \n", "today = target + os.sep + time.strftime('%Y%m%d')\n", "\n", "now = time.strftime('%H%M%S')\n", "\n", "target = today+os.sep+now+'.zip'\n", "\n", "if not os.path.exists(today): \n", " os.mkdir(today)\n", " print('created today')\n", " \n", "zip_command = \"zip -r {0} {1}\".format(target, ' '.join(source)) \n", "# Run the backup \n", "print (\"Zip command is:\")\n", "print(zip_command)\n", "print(\"Running:\")\n", "if os.system(zip_command) == 0:\n", " print('Successful backup to', target)\n", "else:\n", " print('Backup FAILED')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## A simple class" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [], "source": [ "class Robot:\n", " \n", " # a class variable\n", " \n", " population = 0\n", " \n", " def __init__(self, name):\n", " # initialized the data\n", " self.name = name\n", " print(\"(Initializing {})\".format(self.name))\n", " \n", " Robot.population += 1\n", " \n", " def die(self):\n", " # Dying\n", " \n", " print(\"{} is being destroyed\".format(self.name))\n", " \n", " Robot.population -= 1\n", " \n", " if Robot.population == 0:\n", " print(\"{} was the last one\".format(self.name))\n", " else:\n", " print(\"There are still {:d} robots working\".format(Robot.population))\n", " \n", " def say_hi(self):\n", " # greeting\n", " \n", " print(\"Greetings, i am\".format(self.name))\n", " \n", " @classmethod\n", " def how_many(cls):\n", " ## prints current population\n", " print(\" we have {:d} robots. \". format(cls.population))" ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "(Initializing R2)\n", "Greetings, i am\n", " we have 1 robots. \n", "(Initializing R3)\n", "Greetings, i am\n", " we have 2 robots. \n", "they can work now\n", "destroyinnng...\n", "R2 is being destroyed\n", "There are still 1 robots working\n", "R3 is being destroyed\n", "R3 was the last one\n", " we have 0 robots. \n" ] } ], "source": [ "droid1 = Robot(\"R2\")\n", "droid1.say_hi()\n", "Robot.how_many()\n", "\n", "droid2 = Robot(\"R3\")\n", "droid2.say_hi()\n", "Robot.how_many()\n", "\n", "print(\"they can work now\")\n", "\n", "print(\"destroyinnng...\")\n", "\n", "droid1.die()\n", "droid2.die()\n", "\n", "Robot.how_many()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Inheritance" ] }, { "cell_type": "code", "execution_count": 42, "metadata": {}, "outputs": [], "source": [ "class SchoolMember:\n", " def __init__(self, name, age):\n", " self.name = name\n", " self.age = age\n", " print('Initialized SchoolMember: {})'.format(self.name))\n", " \n", " def tell(self):\n", " '''Tell my details.''' \n", " print('Name:\"{}\" Age:\"{}\"'.format(self.name, self.age))\n", " \n", " \n", "class Teacher(SchoolMember):\n", " \n", " def __init__(self, name, age, salary):\n", " SchoolMember.__init__(self, name, age)\n", " self.salary = salary\n", " print('Initialized Teacher: {})'.format(self.name))\n", " \n", " def tell(self):\n", " SchoolMember.tell(self)\n", " print('Salary: \"{:d}\"'.format(self.salary))\n", "\n", "class Student(SchoolMember):\n", " \n", " def __init__(self, name, age, marks):\n", " SchoolMember.__init__(self, name, age)\n", " self.marks = marks\n", " print('Initialized Student: {})'.format(self.name))\n", " \n", " def tell(self):\n", " \n", " SchoolMember.tell(self)\n", " print('Marks: \"{:d}\"'.format(self.marks)) " ] }, { "cell_type": "code", "execution_count": 44, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Initialized SchoolMember: A)\n", "Initialized Teacher: A)\n", "Initialized SchoolMember: me)\n", "Initialized Student: me)\n", "Name:\"A\" Age:\"40\"\n", "Salary: \"20000\"\n", "Name:\"me\" Age:\"25\"\n", "Marks: \"75\"\n" ] } ], "source": [ "t = Teacher('A', 40, 20000)\n", "\n", "s = Student('me', 25, 75)\n", "\n", "m = [t, s]\n", "\n", "for members in m:\n", " members.tell()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Exceptions" ] }, { "cell_type": "code", "execution_count": 47, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "enter-->sd\n", "you entered sd\n" ] } ], "source": [ "try:\n", " text = input(\"enter-->\")\n", "except EOFError:\n", " print('why eof')\n", "else:\n", " print(\"you entered {}\".format(text))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Finally" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import sys\n", "import time \n", "f = None\n", "\n", "try:\n", " f = open(\"poem.txt\") # Our usual file-reading idiom \n", " while True:\n", " line = f.readline()\n", " if len(line) == 0:\n", " break\n", " print line, sys.stdout.flush()\n", " print \"Press ctrl+c now\" # To make sure it runs for a while\n", " time.sleep(2) \n", "except IOError:\n", " print \"Could not find file poem.txt\" \n", "except KeyboardInterrupt:\n", " print \"!! You cancelled the reading from the file.\"\n", "finally: \n", " if f: f.close()\n", " print \"(Cleaning up: Closed the file)\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## With statement" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "with open('file.txt') as w:\n", " for line in w:\n", " print(line)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Standard Libraries" ] }, { "cell_type": "code", "execution_count": 49, "metadata": {}, "outputs": [], "source": [ "## sys module - system specific \n", "\n", "# print(sys.argv)" ] }, { "cell_type": "code", "execution_count": 50, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "sys.version_info(major=3, minor=7, micro=3, releaselevel='final', serial=0)" ] }, "execution_count": 50, "metadata": {}, "output_type": "execute_result" } ], "source": [ "sys.version_info" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "## Loggin module\n", "\n", "\n", "import os, platform, logging\n", "\n", "if platform.platform().startswith('Windows'):\n", " logging_file = os.path.join(os.getenv('HOMEDRIVE'), os.getenv('HOMEPATH'), 'test.log')\n", "else: logging_file = os.path.join(os.getenv('HOME'), 'test.log')\n", "\n", "print \"Logging to\", logging_file\n", "\n", "logging.basicConfig( level=logging.DEBUG, format='%(asctime)s : %(levelname)s : %(message)s', filename = logging_file, filemode = 'w', )\n", "\n", "logging.debug(\"Start of the program\")\n", "logging.info(\"Doing something\")\n", "logging.warning(\"Dying now\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Lambda Forms" ] }, { "cell_type": "code", "execution_count": 51, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[{'x': 4, 'y': 1}, {'x': 2, 'y': 3}]\n" ] } ], "source": [ "points = [ { 'x' : 2, 'y' : 3 }, { 'x' : 4, 'y' : 1 } ]\n", "points.sort(key=lambda i : i['y'])\n", "print(points)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### List Comprehensions" ] }, { "cell_type": "code", "execution_count": 52, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[6, 8]" ] }, "execution_count": 52, "metadata": {}, "output_type": "execute_result" } ], "source": [ "listone = [2, 3, 4]\n", "listtwo = [2*i for i in listone if i > 2]\n", "listtwo" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Assert" ] }, { "cell_type": "code", "execution_count": 53, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'item'" ] }, "execution_count": 53, "metadata": {}, "output_type": "execute_result" } ], "source": [ "mylist = ['item']\n", "assert len(mylist) >= 1\n", "mylist.pop()" ] }, { "cell_type": "code", "execution_count": 54, "metadata": {}, "outputs": [ { "ename": "AssertionError", "evalue": "", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mAssertionError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0;32massert\u001b[0m \u001b[0mlen\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mmylist\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;34m>=\u001b[0m \u001b[0;36m1\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mAssertionError\u001b[0m: " ] } ], "source": [ "assert len(mylist) >= 1" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Decorators" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from time import sleep\n", "from functools import wraps\n", "import logging\n", "logging.basicConfig()\n", "log = logging.getLogger(\"retry\")\n", "\n", "\n", "def retry(f):\n", " @wraps(f)\n", " def wrapped_f(*args, **kwargs):\n", " MAX_ATTEMPTS = 5\n", " for attempt in range(1, MAX_ATTEMPTS + 1):\n", " try:\n", " return f(*args, **kwargs)\n", " except:\n", " log.exception(\"Attempt %s/%s failed : %s\", attempt, MAX_ATTEMPTS, (args, kwargs))\n", " sleep(10 * attempt)\n", " log.critical(\"All %s attempts failed : %s\", MAX_ATTEMPTS, (args, kwargs))\n", " return wrapped_f\n", " counter = 0\n", "\n", "\n", " \n", "@retry\n", "def save_to_database(arg):\n", " print \"Write to a database or make a network call or etc.\"\n", " print \"This will be automatically retried if exception is thrown.\"\n", " global counter\n", " counter += 1 # This will throw an exception in the first call # And will work fine in the second call (i.e. a retry)\n", " if counter < 2:\n", " raise ValueError(arg)\n", " \n", "if __name__ == '__main__':\n", " save_to_database(\"Some bad value\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Command line arguments" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "#!/usr/bin/python\n", "\n", "import sys\n", "\n", "# it's easy to print this list of course:\n", "print(sys.argv)\n", "\n", "# or it can be iterated via a for loop:\n", "\n", "for i in range(len(sys.argv)):\n", " if i == 0:\n", " print(\"Function name: %s\" % sys.argv[0])\n", " else:\n", " print(\"%d. argument: %s\" % (i,sys.argv[i]))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "## OUTPUT \n", "\n", "$ python arguments.py arg1 arg2\n", "['arguments.py', 'arg1', 'arg2']\n", "Function name: arguments.py\n", "1. argument: arg1\n", "2. argument: arg2\n", "$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### System programming and Python" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "## Packages:\n", "\n", "os\n", "platform\n", "subprocess\n", "shutils\n", "glob\n", "sys" ] }, { "cell_type": "code", "execution_count": 55, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "posix\n" ] } ], "source": [ "import os\n", "\n", "print(os.name)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "These names define the following operating systems:\n", "\n", "posix\n", "Unix-like operating systems like Unix, Linux, BSD, Minix and others.\n", "nt\n", "Windows systems like \"Windows 10\", \"Windows 8.1\", \"Windows 8\", \"Windows 7\" and so on.\n", "java\n", "Java operating system." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "## Other common commands:\n", "\n", "print(os.getcwd())\n", "os.chdir(\"\") ## Changes to the path mentioned\n", "print(os.getcwd())\n", "\n", "print(os.listdir()) ## names of the files of directory" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "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.7.3" } }, "nbformat": 4, "nbformat_minor": 2 }