├── README.md ├── 1. Input, Output and For Loop.ipynb ├── 5. Date and Time.ipynb ├── 6. Files and Exception Handling.ipynb ├── 8. Python with Database.ipynb ├── 4. Collections and Sets.ipynb ├── 3. While, Modules and assert.ipynb └── 2. Data Types, Data Structures, Conditionals, Function and Operators.ipynb /README.md: -------------------------------------------------------------------------------- 1 | # Python Beginner to Intermediate 2 | This repository consists of all the required topics for someone who's starting Python from Scratch. 3 | Just follow the codes and the comments to understand the concepts 4 | -------------------------------------------------------------------------------- /1. Input, Output and For Loop.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "## Python | Output using print() function\n", 8 | "\n", 9 | "* The simplest way to produce output is using the print() function where you can pass zero or more expressions \n", 10 | "separated by commas. \n", 11 | "* This function converts the expressions you pass into a string before writing to the screen." 12 | ] 13 | }, 14 | { 15 | "cell_type": "code", 16 | "execution_count": null, 17 | "metadata": {}, 18 | "outputs": [], 19 | "source": [ 20 | "print('Hello World')" 21 | ] 22 | }, 23 | { 24 | "cell_type": "code", 25 | "execution_count": null, 26 | "metadata": {}, 27 | "outputs": [], 28 | "source": [ 29 | "a = 10\n", 30 | "b = 20\n", 31 | "x = a + b\n", 32 | "print(a)" 33 | ] 34 | }, 35 | { 36 | "cell_type": "code", 37 | "execution_count": null, 38 | "metadata": {}, 39 | "outputs": [], 40 | "source": [ 41 | "Case Sensitive Language\n", 42 | "print <> Print <> PRINT" 43 | ] 44 | }, 45 | { 46 | "cell_type": "code", 47 | "execution_count": null, 48 | "metadata": {}, 49 | "outputs": [], 50 | "source": [ 51 | "print(\"Hello World\") #quotations doesn't matter" 52 | ] 53 | }, 54 | { 55 | "cell_type": "code", 56 | "execution_count": null, 57 | "metadata": {}, 58 | "outputs": [], 59 | "source": [ 60 | "print('Hello world')\n", 61 | " print('Hello World')" 62 | ] 63 | }, 64 | { 65 | "cell_type": "markdown", 66 | "metadata": {}, 67 | "source": [ 68 | "## input ( )\n", 69 | "* This function first takes the input from the user and then evaluates the expression, which means Python automatically identifies whether user entered a string or a number or list. \n", 70 | "* If the input provided is not correct then either syntax error or exception is raised by python\n", 71 | "\n", 72 | "## eval ( )\n", 73 | "\n", 74 | "* The eval() method parses the expression passed to it and runs python expression(code) within the program." 75 | ] 76 | }, 77 | { 78 | "cell_type": "code", 79 | "execution_count": null, 80 | "metadata": {}, 81 | "outputs": [], 82 | "source": [ 83 | "# Write first Program\n", 84 | "\n", 85 | "num1 = eval(input('Enter your weight in kilograms:'))\n", 86 | "print('Your weight in Pounds is: ', num1*2.2)" 87 | ] 88 | }, 89 | { 90 | "cell_type": "code", 91 | "execution_count": null, 92 | "metadata": {}, 93 | "outputs": [], 94 | "source": [ 95 | "type(num1)" 96 | ] 97 | }, 98 | { 99 | "cell_type": "code", 100 | "execution_count": null, 101 | "metadata": {}, 102 | "outputs": [], 103 | "source": [ 104 | "# input function by default comes as a str" 105 | ] 106 | }, 107 | { 108 | "cell_type": "code", 109 | "execution_count": null, 110 | "metadata": {}, 111 | "outputs": [], 112 | "source": [ 113 | "a = input('Your age:')" 114 | ] 115 | }, 116 | { 117 | "cell_type": "code", 118 | "execution_count": null, 119 | "metadata": {}, 120 | "outputs": [], 121 | "source": [ 122 | "type(name)" 123 | ] 124 | }, 125 | { 126 | "cell_type": "code", 127 | "execution_count": null, 128 | "metadata": {}, 129 | "outputs": [], 130 | "source": [ 131 | "name = input('Please enter your name:')\n", 132 | "print('Hello',name,'!!!')" 133 | ] 134 | }, 135 | { 136 | "cell_type": "code", 137 | "execution_count": null, 138 | "metadata": {}, 139 | "outputs": [], 140 | "source": [ 141 | "num1 = eval(input('Enter your weight in kilograms:'))\n", 142 | "num2 = eval(input('Enter your Height in Cms:'))\n", 143 | "print('Your Height is {} and your weight in Pounds is:{}'.format(num2, num1*2.2))" 144 | ] 145 | }, 146 | { 147 | "cell_type": "code", 148 | "execution_count": null, 149 | "metadata": {}, 150 | "outputs": [], 151 | "source": [ 152 | "num1" 153 | ] 154 | }, 155 | { 156 | "cell_type": "code", 157 | "execution_count": null, 158 | "metadata": {}, 159 | "outputs": [], 160 | "source": [ 161 | "print('The avg weight of a product:',num1, sep = '---')" 162 | ] 163 | }, 164 | { 165 | "cell_type": "code", 166 | "execution_count": null, 167 | "metadata": {}, 168 | "outputs": [], 169 | "source": [ 170 | "num1 = eval(input('Enter your weight in kilograms:'))\n", 171 | "num2 = eval(input('Enter your Height in Cms:'))\n", 172 | "print('Your Height is {} and your weight in Pounds is:{}'.format(num2, num1*2.2))" 173 | ] 174 | }, 175 | { 176 | "cell_type": "code", 177 | "execution_count": null, 178 | "metadata": {}, 179 | "outputs": [], 180 | "source": [ 181 | "print(num1, 'is the Random number generated', sep = '---')" 182 | ] 183 | }, 184 | { 185 | "cell_type": "code", 186 | "execution_count": null, 187 | "metadata": {}, 188 | "outputs": [], 189 | "source": [ 190 | "print('The first line is', end = '---')\n", 191 | "print('And the second line is')" 192 | ] 193 | }, 194 | { 195 | "cell_type": "code", 196 | "execution_count": null, 197 | "metadata": {}, 198 | "outputs": [], 199 | "source": [ 200 | "num = range(5,10)\n", 201 | "num" 202 | ] 203 | }, 204 | { 205 | "cell_type": "code", 206 | "execution_count": null, 207 | "metadata": {}, 208 | "outputs": [], 209 | "source": [ 210 | "range(100,50, -2)" 211 | ] 212 | }, 213 | { 214 | "cell_type": "code", 215 | "execution_count": null, 216 | "metadata": {}, 217 | "outputs": [], 218 | "source": [ 219 | "range(10)" 220 | ] 221 | }, 222 | { 223 | "cell_type": "markdown", 224 | "metadata": {}, 225 | "source": [ 226 | "## loops\n", 227 | "\n", 228 | "* Python programming language provides following types of loops to handle looping requirements. \n", 229 | "* Python provides three ways for executing the loops. While all the ways provide similar basic functionality, \n", 230 | "they differ in their syntax and condition checking time.\n", 231 | "\n", 232 | "### for Loop:\n", 233 | " \n", 234 | "* For loops are used for sequential traversal. For example: traversing a list or string or array etc.\n", 235 | "* In Python, there is no C style for loop, i.e., for (i=0; i \n" 240 | ] 241 | }, 242 | { 243 | "cell_type": "code", 244 | "execution_count": null, 245 | "metadata": {}, 246 | "outputs": [], 247 | "source": [ 248 | "for i in range(10):\n", 249 | " print(i)" 250 | ] 251 | }, 252 | { 253 | "cell_type": "code", 254 | "execution_count": null, 255 | "metadata": {}, 256 | "outputs": [], 257 | "source": [ 258 | "for i in range(10):\n", 259 | " print(i, end = ' ')" 260 | ] 261 | }, 262 | { 263 | "cell_type": "code", 264 | "execution_count": null, 265 | "metadata": {}, 266 | "outputs": [], 267 | "source": [ 268 | "for i in range(2,5):\n", 269 | " print(i)" 270 | ] 271 | }, 272 | { 273 | "cell_type": "code", 274 | "execution_count": null, 275 | "metadata": {}, 276 | "outputs": [], 277 | "source": [ 278 | "for i in range(2,11,2):\n", 279 | " print(i)" 280 | ] 281 | }, 282 | { 283 | "cell_type": "code", 284 | "execution_count": null, 285 | "metadata": {}, 286 | "outputs": [], 287 | "source": [ 288 | "Range = eval(input('Please enter a range: '))\n", 289 | "for i in range(Range):\n", 290 | " num = eval(input('Please specify a number to be squared: '))\n", 291 | " print(\"The Squared Value of the given number is:\", num*num)\n", 292 | "print('The Loop is done now!!')" 293 | ] 294 | }, 295 | { 296 | "cell_type": "markdown", 297 | "metadata": {}, 298 | "source": [ 299 | "## Random Numbers in Python\n", 300 | "\n", 301 | "* Python defines a set of functions that are used to generate or manipulate random numbers. \n", 302 | "* This particular type of functions are used in a lot of games,\n", 303 | "lotteries or any application requiring random number generation." 304 | ] 305 | }, 306 | { 307 | "cell_type": "code", 308 | "execution_count": null, 309 | "metadata": {}, 310 | "outputs": [], 311 | "source": [ 312 | "from random import randint " 313 | ] 314 | }, 315 | { 316 | "cell_type": "code", 317 | "execution_count": null, 318 | "metadata": {}, 319 | "outputs": [], 320 | "source": [ 321 | "import random" 322 | ] 323 | }, 324 | { 325 | "cell_type": "code", 326 | "execution_count": null, 327 | "metadata": {}, 328 | "outputs": [], 329 | "source": [ 330 | "a = randint(1,10)\n", 331 | "Guess = eval(input('Please Guess a number:'))\n", 332 | "if a == Guess:\n", 333 | " print('You are a Genius')\n", 334 | "else:\n", 335 | " print('Try again!')" 336 | ] 337 | }, 338 | { 339 | "cell_type": "code", 340 | "execution_count": null, 341 | "metadata": {}, 342 | "outputs": [], 343 | "source": [ 344 | "Guess = eval(input('Please provide your Temperature:'))\n", 345 | "if Guess<10:\n", 346 | " print('Very Cold, get a jacket!')\n", 347 | "elif Guess >10:\n", 348 | " print('You are in a better place')\n", 349 | "else:\n", 350 | " print('Good Job!')" 351 | ] 352 | }, 353 | { 354 | "cell_type": "code", 355 | "execution_count": null, 356 | "metadata": {}, 357 | "outputs": [], 358 | "source": [ 359 | "print('*************')\n", 360 | "print('*************')\n", 361 | "print('*************')\n", 362 | "print('*************')" 363 | ] 364 | }, 365 | { 366 | "cell_type": "code", 367 | "execution_count": null, 368 | "metadata": {}, 369 | "outputs": [], 370 | "source": [ 371 | "print('*************')\n", 372 | "print('* *')\n", 373 | "print('* *')\n", 374 | "print('*************')" 375 | ] 376 | } 377 | ], 378 | "metadata": { 379 | "kernelspec": { 380 | "display_name": "Python 3", 381 | "language": "python", 382 | "name": "python3" 383 | }, 384 | "language_info": { 385 | "codemirror_mode": { 386 | "name": "ipython", 387 | "version": 3 388 | }, 389 | "file_extension": ".py", 390 | "mimetype": "text/x-python", 391 | "name": "python", 392 | "nbconvert_exporter": "python", 393 | "pygments_lexer": "ipython3", 394 | "version": "3.7.4" 395 | } 396 | }, 397 | "nbformat": 4, 398 | "nbformat_minor": 2 399 | } 400 | -------------------------------------------------------------------------------- /5. Date and Time.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "### Python has a module named datetime to work with dates and times. \n", 8 | "### Let's create a few simple programs related to date and time before we dig deeper." 9 | ] 10 | }, 11 | { 12 | "cell_type": "code", 13 | "execution_count": null, 14 | "metadata": {}, 15 | "outputs": [], 16 | "source": [ 17 | "# Example 1: Get Current Date and Time\n", 18 | "\n", 19 | "import datetime\n", 20 | "\n", 21 | "datetime_object = datetime.datetime.now()\n", 22 | "print(datetime_object)" 23 | ] 24 | }, 25 | { 26 | "cell_type": "code", 27 | "execution_count": null, 28 | "metadata": {}, 29 | "outputs": [], 30 | "source": [ 31 | "# Example 2: Get Current Date\n", 32 | "\n", 33 | "import datetime\n", 34 | "\n", 35 | "date_object = datetime.date.today()\n", 36 | "print(date_object)" 37 | ] 38 | }, 39 | { 40 | "cell_type": "code", 41 | "execution_count": null, 42 | "metadata": {}, 43 | "outputs": [], 44 | "source": [ 45 | "# What's inside datetime?\n", 46 | "import datetime\n", 47 | "\n", 48 | "print(dir(datetime))" 49 | ] 50 | }, 51 | { 52 | "cell_type": "markdown", 53 | "metadata": {}, 54 | "source": [ 55 | "### datetime.date Class\n", 56 | "* You can instantiate date objects from the date class. A date object represents a date (year, month and day)." 57 | ] 58 | }, 59 | { 60 | "cell_type": "code", 61 | "execution_count": null, 62 | "metadata": {}, 63 | "outputs": [], 64 | "source": [ 65 | "# Example 3: Date object to represent a date\n", 66 | "\n", 67 | "import datetime\n", 68 | "\n", 69 | "d = datetime.date(2019, 4, 13)\n", 70 | "print(d)" 71 | ] 72 | }, 73 | { 74 | "cell_type": "code", 75 | "execution_count": null, 76 | "metadata": {}, 77 | "outputs": [], 78 | "source": [ 79 | "from datetime import date\n", 80 | "\n", 81 | "a = date(2019, 4, 13)\n", 82 | "print(a)" 83 | ] 84 | }, 85 | { 86 | "cell_type": "code", 87 | "execution_count": null, 88 | "metadata": {}, 89 | "outputs": [], 90 | "source": [ 91 | "# Example 4: Get current date\n", 92 | "\n", 93 | "from datetime import date\n", 94 | "\n", 95 | "today = date.today()\n", 96 | "\n", 97 | "print(\"Current date =\", today)" 98 | ] 99 | }, 100 | { 101 | "cell_type": "code", 102 | "execution_count": null, 103 | "metadata": {}, 104 | "outputs": [], 105 | "source": [ 106 | "# Example 6: Print today's year, month and day\n", 107 | "\n", 108 | "\n", 109 | "from datetime import date\n", 110 | "\n", 111 | "# date object of today's date\n", 112 | "today = date.today() \n", 113 | "\n", 114 | "print(\"Current year:\", today.year)\n", 115 | "print(\"Current month:\", today.month)\n", 116 | "print(\"Current day:\", today.day)" 117 | ] 118 | }, 119 | { 120 | "cell_type": "markdown", 121 | "metadata": {}, 122 | "source": [ 123 | "### datetime.time\n", 124 | "* A time object instantiated from the time class represents the local time." 125 | ] 126 | }, 127 | { 128 | "cell_type": "code", 129 | "execution_count": null, 130 | "metadata": {}, 131 | "outputs": [], 132 | "source": [ 133 | "from datetime import time\n", 134 | "\n", 135 | "# time(hour = 0, minute = 0, second = 0)\n", 136 | "a = time()\n", 137 | "print(\"a =\", a)\n", 138 | "\n", 139 | "# time(hour, minute and second)\n", 140 | "b = time(11, 34, 56)\n", 141 | "print(\"b =\", b)\n", 142 | "\n", 143 | "# time(hour, minute and second)\n", 144 | "c = time(hour = 11, minute = 34, second = 56)\n", 145 | "print(\"c =\", c)\n", 146 | "\n", 147 | "# time(hour, minute, second, microsecond)\n", 148 | "d = time(11, 34, 56, 234566)\n", 149 | "print(\"d =\", d)" 150 | ] 151 | }, 152 | { 153 | "cell_type": "code", 154 | "execution_count": null, 155 | "metadata": {}, 156 | "outputs": [], 157 | "source": [ 158 | "# Example 8: Print hour, minute, second and microsecond\n", 159 | "\n", 160 | "\n", 161 | "from datetime import time\n", 162 | "\n", 163 | "a = time(11, 34, 56)\n", 164 | "\n", 165 | "print(\"hour =\", a.hour)\n", 166 | "print(\"minute =\", a.minute)\n", 167 | "print(\"second =\", a.second)\n", 168 | "print(\"microsecond =\", a.microsecond)" 169 | ] 170 | }, 171 | { 172 | "cell_type": "markdown", 173 | "metadata": {}, 174 | "source": [ 175 | "### datetime.datetime\n", 176 | "* The datetime module has a class named dateclass that can contain information from both date and time objects." 177 | ] 178 | }, 179 | { 180 | "cell_type": "code", 181 | "execution_count": null, 182 | "metadata": {}, 183 | "outputs": [], 184 | "source": [ 185 | "# Python datetime object\n", 186 | "\n", 187 | "from datetime import datetime\n", 188 | "\n", 189 | "#datetime(year, month, day)\n", 190 | "a = datetime(2018, 11, 28)\n", 191 | "print(a)\n", 192 | "\n", 193 | "# datetime(year, month, day, hour, minute, second, microsecond)\n", 194 | "b = datetime(2017, 11, 28, 23, 55, 59, 342380)\n", 195 | "print(b)" 196 | ] 197 | }, 198 | { 199 | "cell_type": "code", 200 | "execution_count": null, 201 | "metadata": {}, 202 | "outputs": [], 203 | "source": [ 204 | "# Example 10: Print year, month, hour, minute and timestamp\n", 205 | "\n", 206 | "\n", 207 | "from datetime import datetime\n", 208 | "\n", 209 | "a = datetime(2017, 11, 28, 23, 55, 59, 342380)\n", 210 | "print(\"year =\", a.year)\n", 211 | "print(\"month =\", a.month)\n", 212 | "print(\"hour =\", a.hour)\n", 213 | "print(\"minute =\", a.minute)\n", 214 | "print(\"timestamp =\", a.timestamp())" 215 | ] 216 | }, 217 | { 218 | "cell_type": "markdown", 219 | "metadata": {}, 220 | "source": [ 221 | "### datetime.timedelta\n", 222 | "* A timedelta object represents the difference between two dates or times." 223 | ] 224 | }, 225 | { 226 | "cell_type": "code", 227 | "execution_count": null, 228 | "metadata": {}, 229 | "outputs": [], 230 | "source": [ 231 | "# Difference between two dates and times\n", 232 | "\n", 233 | "from datetime import datetime, date\n", 234 | "\n", 235 | "t1 = date(year = 2018, month = 7, day = 12)\n", 236 | "t2 = date(year = 2017, month = 12, day = 23)\n", 237 | "t3 = t1 - t2\n", 238 | "print(\"t3 =\", t3)\n", 239 | "\n", 240 | "t4 = datetime(year = 2018, month = 7, day = 12, hour = 7, minute = 9, second = 33)\n", 241 | "t5 = datetime(year = 2019, month = 6, day = 10, hour = 5, minute = 55, second = 13)\n", 242 | "t6 = t4 - t5\n", 243 | "print(\"t6 =\", t6)\n", 244 | "\n", 245 | "print(\"type of t3 =\", type(t3)) \n", 246 | "print(\"type of t6 =\", type(t6))" 247 | ] 248 | }, 249 | { 250 | "cell_type": "code", 251 | "execution_count": null, 252 | "metadata": {}, 253 | "outputs": [], 254 | "source": [ 255 | "# Example 12: Difference between two timedelta objects\n", 256 | "\n", 257 | "from datetime import timedelta\n", 258 | "\n", 259 | "t1 = timedelta(weeks = 2, days = 5, hours = 1, seconds = 33)\n", 260 | "t2 = timedelta(days = 4, hours = 11, minutes = 4, seconds = 54)\n", 261 | "t3 = t1 - t2\n", 262 | "\n", 263 | "print(\"t3 =\", t3)" 264 | ] 265 | }, 266 | { 267 | "cell_type": "code", 268 | "execution_count": null, 269 | "metadata": {}, 270 | "outputs": [], 271 | "source": [ 272 | "# Printing negative timedelta object\n", 273 | "\n", 274 | "from datetime import timedelta\n", 275 | "\n", 276 | "t1 = timedelta(seconds = 33)\n", 277 | "t2 = timedelta(seconds = 54)\n", 278 | "t3 = t1 - t2\n", 279 | "\n", 280 | "print(\"t3 =\", t3)\n", 281 | "print(\"t3 =\", abs(t3))" 282 | ] 283 | }, 284 | { 285 | "cell_type": "code", 286 | "execution_count": null, 287 | "metadata": {}, 288 | "outputs": [], 289 | "source": [ 290 | "# Time duration in seconds\n", 291 | "# You can get the total number of seconds in a timedelta object using total_seconds() method.\n", 292 | "\n", 293 | "from datetime import timedelta\n", 294 | "\n", 295 | "t = timedelta(days = 5, hours = 1, seconds = 33, microseconds = 233423)\n", 296 | "print(\"total seconds =\", t.total_seconds())" 297 | ] 298 | }, 299 | { 300 | "cell_type": "markdown", 301 | "metadata": {}, 302 | "source": [ 303 | "### Python format datetime\n", 304 | "\n", 305 | "* Python strftime() - datetime object to string\n", 306 | "* The strftime() method is defined under classes date, datetime and time.\n", 307 | "* The method creates a formatted string from a given date, datetime or time object." 308 | ] 309 | }, 310 | { 311 | "cell_type": "code", 312 | "execution_count": null, 313 | "metadata": {}, 314 | "outputs": [], 315 | "source": [ 316 | "# Format date using strftime()\n", 317 | "\n", 318 | "from datetime import datetime\n", 319 | "\n", 320 | "# current date and time\n", 321 | "now = datetime.now()\n", 322 | "\n", 323 | "t = now.strftime(\"%H:%M:%S\")\n", 324 | "print(\"time:\", t)\n", 325 | "\n", 326 | "s1 = now.strftime(\"%m/%d/%Y, %H:%M:%S\")\n", 327 | "# mm/dd/YY H:M:S format\n", 328 | "print(\"s1:\", s1)\n", 329 | "\n", 330 | "s2 = now.strftime(\"%d/%m/%Y, %H:%M:%S\")\n", 331 | "# dd/mm/YY H:M:S format\n", 332 | "print(\"s2:\", s2)" 333 | ] 334 | }, 335 | { 336 | "cell_type": "markdown", 337 | "metadata": {}, 338 | "source": [ 339 | "### Python strptime() - string to datetime\n", 340 | "* The strptime() method creates a datetime object from a given string (representing date and time)." 341 | ] 342 | }, 343 | { 344 | "cell_type": "code", 345 | "execution_count": null, 346 | "metadata": {}, 347 | "outputs": [], 348 | "source": [ 349 | "from datetime import datetime\n", 350 | "\n", 351 | "date_string = \"21 June, 2018\"\n", 352 | "print(\"date_string =\", date_string)\n", 353 | "\n", 354 | "date_object = datetime.strptime(date_string, \"%d %B, %Y\")\n", 355 | "print(\"date_object =\", date_object)" 356 | ] 357 | }, 358 | { 359 | "cell_type": "markdown", 360 | "metadata": {}, 361 | "source": [ 362 | "### Handling timezone in Python\n", 363 | "* Suppose, you are working on a project and need to display date and time based on their timezone.\n", 364 | "* Rather than trying to handle timezone yourself, we suggest you to use a third-party pytZ module." 365 | ] 366 | }, 367 | { 368 | "cell_type": "code", 369 | "execution_count": null, 370 | "metadata": {}, 371 | "outputs": [], 372 | "source": [ 373 | "from datetime import datetime\n", 374 | "import pytz\n", 375 | "\n", 376 | "local = datetime.now()\n", 377 | "print(\"Local:\", local.strftime(\"%m/%d/%Y, %H:%M:%S\"))\n", 378 | "\n", 379 | "\n", 380 | "tz_NY = pytz.timezone('America/New_York') \n", 381 | "datetime_NY = datetime.now(tz_NY)\n", 382 | "print(\"NY:\", datetime_NY.strftime(\"%m/%d/%Y, %H:%M:%S\"))\n", 383 | "\n", 384 | "tz_London = pytz.timezone('Europe/London')\n", 385 | "datetime_London = datetime.now(tz_London)\n", 386 | "print(\"London:\", datetime_London.strftime(\"%m/%d/%Y, %H:%M:%S\"))" 387 | ] 388 | }, 389 | { 390 | "cell_type": "markdown", 391 | "metadata": {}, 392 | "source": [ 393 | "### datetime to string using strftime()\n", 394 | "\n", 395 | "* The program below converts a datetime object containing current date and time to different string formats." 396 | ] 397 | }, 398 | { 399 | "cell_type": "code", 400 | "execution_count": null, 401 | "metadata": {}, 402 | "outputs": [], 403 | "source": [ 404 | "from datetime import datetime\n", 405 | "\n", 406 | "now = datetime.now() # current date and time\n", 407 | "\n", 408 | "year = now.strftime(\"%Y\")\n", 409 | "print(\"year:\", year)\n", 410 | "\n", 411 | "month = now.strftime(\"%m\")\n", 412 | "print(\"month:\", month)\n", 413 | "\n", 414 | "day = now.strftime(\"%d\")\n", 415 | "print(\"day:\", day)\n", 416 | "\n", 417 | "time = now.strftime(\"%H:%M:%S\")\n", 418 | "print(\"time:\", time)\n", 419 | "\n", 420 | "date_time = now.strftime(\"%m/%d/%Y, %H:%M:%S\")\n", 421 | "print(\"date and time:\",date_time)" 422 | ] 423 | }, 424 | { 425 | "cell_type": "code", 426 | "execution_count": null, 427 | "metadata": {}, 428 | "outputs": [], 429 | "source": [ 430 | "# Creating string from a timestamp\n", 431 | "\n", 432 | "from datetime import datetime\n", 433 | "\n", 434 | "timestamp = 1528797322\n", 435 | "date_time = datetime.fromtimestamp(timestamp)\n", 436 | "\n", 437 | "print(\"Date time object:\", date_time)\n", 438 | "\n", 439 | "d = date_time.strftime(\"%m/%d/%Y, %H:%M:%S\")\n", 440 | "print(\"Output 2:\", d)\n", 441 | "\n", 442 | "d = date_time.strftime(\"%d %b, %Y\")\n", 443 | "print(\"Output 3:\", d)\n", 444 | "\n", 445 | "d = date_time.strftime(\"%d %B, %Y\")\n", 446 | "print(\"Output 4:\", d)\n", 447 | "\n", 448 | "d = date_time.strftime(\"%I%p\")\n", 449 | "print(\"Output 5:\", d)" 450 | ] 451 | }, 452 | { 453 | "cell_type": "code", 454 | "execution_count": null, 455 | "metadata": {}, 456 | "outputs": [], 457 | "source": [ 458 | "# Locale's appropriate date and time\n", 459 | "\n", 460 | "from datetime import datetime\n", 461 | "\n", 462 | "timestamp = 1528797322\n", 463 | "date_time = datetime.fromtimestamp(timestamp)\n", 464 | "\n", 465 | "d = date_time.strftime(\"%c\")\n", 466 | "print(\"Output 1:\", d)\n", 467 | "\n", 468 | "d = date_time.strftime(\"%x\")\n", 469 | "print(\"Output 2:\", d)\n", 470 | "\n", 471 | "d = date_time.strftime(\"%X\")\n", 472 | "print(\"Output 3:\", d)" 473 | ] 474 | }, 475 | { 476 | "cell_type": "code", 477 | "execution_count": null, 478 | "metadata": {}, 479 | "outputs": [], 480 | "source": [ 481 | "# Example 1: Python get today's date\n", 482 | "from datetime import date\n", 483 | "\n", 484 | "today = date.today()\n", 485 | "print(\"Today's date:\", today)" 486 | ] 487 | }, 488 | { 489 | "cell_type": "code", 490 | "execution_count": null, 491 | "metadata": {}, 492 | "outputs": [], 493 | "source": [ 494 | "# Example 2: Current date in different formats\n", 495 | "from datetime import date\n", 496 | "\n", 497 | "today = date.today()\n", 498 | "\n", 499 | "# dd/mm/YY\n", 500 | "d1 = today.strftime(\"%d/%m/%Y\")\n", 501 | "print(\"d1 =\", d1)\n", 502 | "\n", 503 | "# Textual month, day and year\n", 504 | "d2 = today.strftime(\"%B %d, %Y\")\n", 505 | "print(\"d2 =\", d2)\n", 506 | "\n", 507 | "# mm/dd/y\n", 508 | "d3 = today.strftime(\"%m/%d/%y\")\n", 509 | "print(\"d3 =\", d3)\n", 510 | "\n", 511 | "# Month abbreviation, day and year\n", 512 | "d4 = today.strftime(\"%b-%d-%Y\")\n", 513 | "print(\"d4 =\", d4)" 514 | ] 515 | }, 516 | { 517 | "cell_type": "code", 518 | "execution_count": null, 519 | "metadata": {}, 520 | "outputs": [], 521 | "source": [ 522 | "# Get the current date and time\n", 523 | "from datetime import datetime\n", 524 | "\n", 525 | "# datetime object containing current date and time\n", 526 | "now = datetime.now()\n", 527 | " \n", 528 | "print(\"now =\", now)\n", 529 | "\n", 530 | "# dd/mm/YY H:M:S\n", 531 | "dt_string = now.strftime(\"%d/%m/%Y %H:%M:%S\")\n", 532 | "print(\"date and time =\", dt_string)\t" 533 | ] 534 | }, 535 | { 536 | "cell_type": "code", 537 | "execution_count": null, 538 | "metadata": {}, 539 | "outputs": [], 540 | "source": [ 541 | "# The sleep() function suspends (delays) execution of the current thread for the given number of seconds.\n", 542 | "\n", 543 | "import time\n", 544 | "\n", 545 | "print(\"This is printed immediately.\")\n", 546 | "time.sleep(2.4)\n", 547 | "print(\"This is printed after 2.4 seconds.\")" 548 | ] 549 | }, 550 | { 551 | "cell_type": "code", 552 | "execution_count": null, 553 | "metadata": {}, 554 | "outputs": [], 555 | "source": [ 556 | "# Python create a digital clock\n", 557 | "import time\n", 558 | "\n", 559 | "while True:\n", 560 | " localtime = time.localtime()\n", 561 | " result = time.strftime(\"%H:%M:%S %p\", localtime)\n", 562 | " print(result)\n", 563 | " time.sleep(1)" 564 | ] 565 | }, 566 | { 567 | "cell_type": "code", 568 | "execution_count": null, 569 | "metadata": {}, 570 | "outputs": [], 571 | "source": [ 572 | "# Python create a digital clock\n", 573 | "import time\n", 574 | "\n", 575 | "while True:\n", 576 | " localtime = time.localtime()\n", 577 | " result = time.strftime(\"%H:%M:%S %p\", localtime)\n", 578 | " print(result)\n", 579 | " time.sleep(1)" 580 | ] 581 | }, 582 | { 583 | "cell_type": "code", 584 | "execution_count": null, 585 | "metadata": {}, 586 | "outputs": [], 587 | "source": [ 588 | "# Python create a digital clock\n", 589 | "import time\n", 590 | "\n", 591 | "while True:\n", 592 | " localtime = time.localtime()\n", 593 | " result = time.strftime(\"%H:%M:%S %p\", localtime)\n", 594 | " print(result)\n", 595 | " time.sleep(1)" 596 | ] 597 | }, 598 | { 599 | "cell_type": "code", 600 | "execution_count": null, 601 | "metadata": {}, 602 | "outputs": [], 603 | "source": [ 604 | "import time\n", 605 | "\n", 606 | "while True:\n", 607 | " localtime = time.localtime()\n", 608 | " result = time.strftime(\"%H:%M:%S %p\", localtime)\n", 609 | " print(result, end=\"\", flush=True)\n", 610 | " print(\"\\r\", end=\"\", flush=True)\n", 611 | " time.sleep(1)" 612 | ] 613 | } 614 | ], 615 | "metadata": { 616 | "kernelspec": { 617 | "display_name": "Python 3", 618 | "language": "python", 619 | "name": "python3" 620 | }, 621 | "language_info": { 622 | "codemirror_mode": { 623 | "name": "ipython", 624 | "version": 3 625 | }, 626 | "file_extension": ".py", 627 | "mimetype": "text/x-python", 628 | "name": "python", 629 | "nbconvert_exporter": "python", 630 | "pygments_lexer": "ipython3", 631 | "version": "3.7.4" 632 | } 633 | }, 634 | "nbformat": 4, 635 | "nbformat_minor": 2 636 | } 637 | -------------------------------------------------------------------------------- /6. Files and Exception Handling.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "## File Handling in Python\n", 8 | "\n", 9 | "* Python too supports file handling and allows users to handle files i.e., to read and write files, along with many other \n", 10 | "file handling options, to operate on files. \n", 11 | "\n", 12 | "* The concept of file handling has stretched over various other languages, but the implementation is either complicated \n", 13 | "or lengthy, but alike other concepts of Python, this concept here is also easy and short. \n", 14 | "\n", 15 | "* Python treats file differently as text or binary and this is important. Each line of code includes a sequence of \n", 16 | "characters and they form text file.\n", 17 | "\n", 18 | "* Each line of a file is terminated with a special character, called the EOL or End of Line characters like comma {,} or \n", 19 | "newline character. \n", 20 | "\n", 21 | "* It ends the current line and tells the interpreter a new one has begun. Let’s start with Reading and Writing files.\n", 22 | "\n", 23 | "\n", 24 | "\n", 25 | "### Working of open() function\n", 26 | "\n", 27 | "* We use open () function in Python to open a file in read or write mode. \n", 28 | "\n", 29 | "* As explained above, open ( ) will return a file object. \n", 30 | "* To return a file object we use open() function along with two arguments, that accepts file name and the mode, \n", 31 | "whether to read or write. So, the syntax being: open(filename, mode). \n", 32 | "* There are three kinds of mode, that Python provides and how files can be opened:\n", 33 | " * “ r “, for reading.\n", 34 | " * “ w “, for writing.\n", 35 | " * “ a “, for appending.\n", 36 | " * “ r+ “, for both reading and writing" 37 | ] 38 | }, 39 | { 40 | "cell_type": "code", 41 | "execution_count": null, 42 | "metadata": {}, 43 | "outputs": [], 44 | "source": [ 45 | "f = open(\"test.txt\", 'r') # open file in current directory\n", 46 | "f" 47 | ] 48 | }, 49 | { 50 | "cell_type": "code", 51 | "execution_count": null, 52 | "metadata": {}, 53 | "outputs": [], 54 | "source": [ 55 | "f = open('Test.txt')\n", 56 | "f" 57 | ] 58 | }, 59 | { 60 | "cell_type": "code", 61 | "execution_count": null, 62 | "metadata": {}, 63 | "outputs": [], 64 | "source": [ 65 | "f1 = open(\"C:/Test.txt\") # specifying full path" 66 | ] 67 | }, 68 | { 69 | "cell_type": "code", 70 | "execution_count": null, 71 | "metadata": {}, 72 | "outputs": [], 73 | "source": [ 74 | "f1" 75 | ] 76 | }, 77 | { 78 | "cell_type": "code", 79 | "execution_count": null, 80 | "metadata": {}, 81 | "outputs": [], 82 | "source": [ 83 | "import os\n", 84 | "os.getcwd()" 85 | ] 86 | }, 87 | { 88 | "cell_type": "code", 89 | "execution_count": null, 90 | "metadata": {}, 91 | "outputs": [], 92 | "source": [ 93 | "# f = open(\"test.txt\") # equivalent to 'r' or 'rt'\n", 94 | "f = open(\"testnow.txt\",'w') # write in text mode" 95 | ] 96 | }, 97 | { 98 | "cell_type": "code", 99 | "execution_count": null, 100 | "metadata": {}, 101 | "outputs": [], 102 | "source": [ 103 | "f = open('Test2.txt', 'w')" 104 | ] 105 | }, 106 | { 107 | "cell_type": "code", 108 | "execution_count": null, 109 | "metadata": {}, 110 | "outputs": [], 111 | "source": [ 112 | "# Closing the file\n", 113 | "f.close()" 114 | ] 115 | }, 116 | { 117 | "cell_type": "code", 118 | "execution_count": null, 119 | "metadata": {}, 120 | "outputs": [], 121 | "source": [ 122 | "#Exceptions\n", 123 | "try:\n", 124 | " f = open(\"testnow.txt\",'w')\n", 125 | " f.write('This is my first line\\n')\n", 126 | " f.write('This is my second line\\n')\n", 127 | "finally:\n", 128 | " f.close()" 129 | ] 130 | }, 131 | { 132 | "cell_type": "code", 133 | "execution_count": null, 134 | "metadata": {}, 135 | "outputs": [], 136 | "source": [ 137 | "# Using With Method\n", 138 | "with open(\"test.txt\") as f:\n", 139 | " print(f.readlines())" 140 | ] 141 | }, 142 | { 143 | "cell_type": "code", 144 | "execution_count": null, 145 | "metadata": {}, 146 | "outputs": [], 147 | "source": [ 148 | "# Writing contents inside the file\n", 149 | "\n", 150 | "with open(\"testnew.txt\",'w') as f:\n", 151 | " f.write(\"my first file\\n\")\n", 152 | " f.write(\"This file\\n\")\n", 153 | " f.write(\"contains three lines\\n\")" 154 | ] 155 | }, 156 | { 157 | "cell_type": "code", 158 | "execution_count": null, 159 | "metadata": {}, 160 | "outputs": [], 161 | "source": [ 162 | "f = open('testnew.txt')\n", 163 | "f.readlines()" 164 | ] 165 | }, 166 | { 167 | "cell_type": "code", 168 | "execution_count": null, 169 | "metadata": {}, 170 | "outputs": [], 171 | "source": [ 172 | "f = open(\"Test.txt\",'r')\n", 173 | "f.read(4) # read the first 4 data" 174 | ] 175 | }, 176 | { 177 | "cell_type": "code", 178 | "execution_count": null, 179 | "metadata": {}, 180 | "outputs": [], 181 | "source": [ 182 | "f.read(10)" 183 | ] 184 | }, 185 | { 186 | "cell_type": "code", 187 | "execution_count": null, 188 | "metadata": {}, 189 | "outputs": [], 190 | "source": [ 191 | "f = open(\"test.txt\",'r')\n", 192 | "\n", 193 | "x = f.readlines()\n", 194 | "x" 195 | ] 196 | }, 197 | { 198 | "cell_type": "code", 199 | "execution_count": null, 200 | "metadata": {}, 201 | "outputs": [], 202 | "source": [ 203 | "f.read(4) # read the next 4 data" 204 | ] 205 | }, 206 | { 207 | "cell_type": "code", 208 | "execution_count": null, 209 | "metadata": {}, 210 | "outputs": [], 211 | "source": [ 212 | "f.read(10) # read in the rest till end of file" 213 | ] 214 | }, 215 | { 216 | "cell_type": "code", 217 | "execution_count": null, 218 | "metadata": {}, 219 | "outputs": [], 220 | "source": [ 221 | "f.read() # further reading returns empty sting" 222 | ] 223 | }, 224 | { 225 | "cell_type": "code", 226 | "execution_count": null, 227 | "metadata": {}, 228 | "outputs": [], 229 | "source": [ 230 | "f.tell() # get the current file position" 231 | ] 232 | }, 233 | { 234 | "cell_type": "code", 235 | "execution_count": null, 236 | "metadata": {}, 237 | "outputs": [], 238 | "source": [ 239 | "f.seek(0) # bring file cursor to initial position" 240 | ] 241 | }, 242 | { 243 | "cell_type": "code", 244 | "execution_count": null, 245 | "metadata": {}, 246 | "outputs": [], 247 | "source": [ 248 | "f.read(5)" 249 | ] 250 | }, 251 | { 252 | "cell_type": "code", 253 | "execution_count": null, 254 | "metadata": {}, 255 | "outputs": [], 256 | "source": [ 257 | "print(f.read()) # read the entire file" 258 | ] 259 | }, 260 | { 261 | "cell_type": "code", 262 | "execution_count": null, 263 | "metadata": {}, 264 | "outputs": [], 265 | "source": [ 266 | "for line in f:\n", 267 | " print(line, end = '')" 268 | ] 269 | }, 270 | { 271 | "cell_type": "code", 272 | "execution_count": null, 273 | "metadata": {}, 274 | "outputs": [], 275 | "source": [ 276 | "f.readline()" 277 | ] 278 | }, 279 | { 280 | "cell_type": "code", 281 | "execution_count": null, 282 | "metadata": {}, 283 | "outputs": [], 284 | "source": [ 285 | "f.readline()" 286 | ] 287 | }, 288 | { 289 | "cell_type": "code", 290 | "execution_count": null, 291 | "metadata": {}, 292 | "outputs": [], 293 | "source": [ 294 | "f.readline()" 295 | ] 296 | }, 297 | { 298 | "cell_type": "code", 299 | "execution_count": null, 300 | "metadata": {}, 301 | "outputs": [], 302 | "source": [ 303 | "f.readline()" 304 | ] 305 | }, 306 | { 307 | "cell_type": "code", 308 | "execution_count": null, 309 | "metadata": {}, 310 | "outputs": [], 311 | "source": [ 312 | "f.readlines()" 313 | ] 314 | }, 315 | { 316 | "cell_type": "code", 317 | "execution_count": null, 318 | "metadata": {}, 319 | "outputs": [], 320 | "source": [ 321 | "f = open(\"myfile1.txt\", \"x\")" 322 | ] 323 | }, 324 | { 325 | "cell_type": "code", 326 | "execution_count": null, 327 | "metadata": {}, 328 | "outputs": [], 329 | "source": [ 330 | "f.write(\"my first file\\n\")\n", 331 | "f.write(\"This file\\n\")\n", 332 | "f.write(\"contains three lines\\n\")" 333 | ] 334 | }, 335 | { 336 | "cell_type": "code", 337 | "execution_count": null, 338 | "metadata": {}, 339 | "outputs": [], 340 | "source": [ 341 | "f=open('myfile1.txt','r')" 342 | ] 343 | }, 344 | { 345 | "cell_type": "code", 346 | "execution_count": null, 347 | "metadata": {}, 348 | "outputs": [], 349 | "source": [ 350 | "f.readlines()" 351 | ] 352 | }, 353 | { 354 | "cell_type": "code", 355 | "execution_count": null, 356 | "metadata": {}, 357 | "outputs": [], 358 | "source": [ 359 | "import os\n", 360 | "os.chdir('..')\n", 361 | "os.remove(\"myfile1.txt\")" 362 | ] 363 | }, 364 | { 365 | "cell_type": "code", 366 | "execution_count": null, 367 | "metadata": {}, 368 | "outputs": [], 369 | "source": [ 370 | "import os\n", 371 | "if os.path.exists(\"myfile.txt\"):\n", 372 | " os.remove(\"myfile.txt\")\n", 373 | "else:\n", 374 | " print(\"The file does not exist\")" 375 | ] 376 | }, 377 | { 378 | "cell_type": "code", 379 | "execution_count": null, 380 | "metadata": {}, 381 | "outputs": [], 382 | "source": [ 383 | "f = open('Test.txt')" 384 | ] 385 | }, 386 | { 387 | "cell_type": "code", 388 | "execution_count": null, 389 | "metadata": {}, 390 | "outputs": [], 391 | "source": [ 392 | "f" 393 | ] 394 | }, 395 | { 396 | "cell_type": "code", 397 | "execution_count": null, 398 | "metadata": {}, 399 | "outputs": [], 400 | "source": [ 401 | "f = open('Test.txt','a+')" 402 | ] 403 | }, 404 | { 405 | "cell_type": "markdown", 406 | "metadata": {}, 407 | "source": [ 408 | "## Exceptions Handling\n", 409 | "\n", 410 | "* Like other languages, python also provides the runtime errors via exception handling method with the help of try-except. \n", 411 | "* Some of the standard exceptions which are most frequent include IndexError, ImportError, IOError, ZeroDivisionError, TypeError.\n", 412 | "\n", 413 | "### Try and Except\n", 414 | "* A try statement can have more than one except clause, to specify handlers for different exceptions. \n", 415 | "* Please note that at most one handler will be executed.\n", 416 | "\n", 417 | "### Else Clause:\n", 418 | "* In python, you can also use else clause on try-except block which must be present after all the except clauses.\n", 419 | "* The code enters the else block only if the try clause does not raise an exception.\n", 420 | "\n", 421 | "### Raising Exception:\n", 422 | "* The raise statement allows the programmer to force a specific exception to occur. \n", 423 | "* The sole argument in raise indicates the exception to be raised. This must be either an exception instance or an exception class (a class that derives from Exception).\n", 424 | "\n", 425 | "### try...finally\n", 426 | "* The try statement in Python can have an optional finally clause. This clause is executed no matter what, and is generally used to release external resources.\n", 427 | "\n", 428 | "* For example, we may be connected to a remote data center through the network or working with a file or working with a Graphical User Interface (GUI).\n", 429 | "\n", 430 | "* In all these circumstances, we must clean up the resource once used, whether it was successful or not. \n", 431 | "* These actions (closing a file, GUI or disconnecting from network) are performed in the finally clause to guarantee execution." 432 | ] 433 | }, 434 | { 435 | "cell_type": "code", 436 | "execution_count": null, 437 | "metadata": {}, 438 | "outputs": [], 439 | "source": [ 440 | "if a < 3" 441 | ] 442 | }, 443 | { 444 | "cell_type": "code", 445 | "execution_count": null, 446 | "metadata": {}, 447 | "outputs": [], 448 | "source": [ 449 | "a = 10" 450 | ] 451 | }, 452 | { 453 | "cell_type": "code", 454 | "execution_count": null, 455 | "metadata": {}, 456 | "outputs": [], 457 | "source": [ 458 | "1 / 0" 459 | ] 460 | }, 461 | { 462 | "cell_type": "code", 463 | "execution_count": null, 464 | "metadata": {}, 465 | "outputs": [], 466 | "source": [ 467 | "open(\"imaginary.txt\")" 468 | ] 469 | }, 470 | { 471 | "cell_type": "code", 472 | "execution_count": null, 473 | "metadata": {}, 474 | "outputs": [], 475 | "source": [ 476 | "try:\n", 477 | " print(1/0)\n", 478 | "except NameError:\n", 479 | " print(\"Variable x is not defined\")\n", 480 | "except:\n", 481 | " print(\"Something else went wrong\")" 482 | ] 483 | }, 484 | { 485 | "cell_type": "code", 486 | "execution_count": null, 487 | "metadata": {}, 488 | "outputs": [], 489 | "source": [ 490 | "X = 'New'\n", 491 | "x = 'new'" 492 | ] 493 | }, 494 | { 495 | "cell_type": "code", 496 | "execution_count": null, 497 | "metadata": {}, 498 | "outputs": [], 499 | "source": [ 500 | "try:\n", 501 | " print(X*x)\n", 502 | "except:\n", 503 | " print(\"Something went wrong\")\n", 504 | "else:\n", 505 | " print(\"Nothing went wrong\")" 506 | ] 507 | }, 508 | { 509 | "cell_type": "code", 510 | "execution_count": null, 511 | "metadata": {}, 512 | "outputs": [], 513 | "source": [ 514 | "try:\n", 515 | " print(Y)\n", 516 | "except:\n", 517 | " print(\"Something went wrong\")\n", 518 | "finally:\n", 519 | " print(\"The 'try except' is finished\")" 520 | ] 521 | }, 522 | { 523 | "cell_type": "code", 524 | "execution_count": null, 525 | "metadata": {}, 526 | "outputs": [], 527 | "source": [ 528 | "a = [1, 2, 3] \n", 529 | "try: \n", 530 | " print (\"Second element = %d\" %(a[1])) \n", 531 | " print (\"Fourth element = %d\" %(a[3]))\n", 532 | "except IndexError: \n", 533 | " print (\"An error occurred\")" 534 | ] 535 | }, 536 | { 537 | "cell_type": "code", 538 | "execution_count": null, 539 | "metadata": {}, 540 | "outputs": [], 541 | "source": [ 542 | "# to handle multiple errors with one except statement \n", 543 | "try : \n", 544 | " a = 3\n", 545 | " if a < 4 : \n", 546 | " b = a/(a-3) # throws ZeroDivisionError for a = 3 \n", 547 | " print (\"Value of b = \", b) # throws NameError if a >= 4\n", 548 | " \n", 549 | "# note that braces () are necessary here for multiple exceptions \n", 550 | "except(ZeroDivisionError, NameError): \n", 551 | " print (\"Error Occurred and Handled\")" 552 | ] 553 | }, 554 | { 555 | "cell_type": "code", 556 | "execution_count": null, 557 | "metadata": {}, 558 | "outputs": [], 559 | "source": [ 560 | "# to depict else clause with try-except \n", 561 | " \n", 562 | "# Function which returns a/b \n", 563 | "def AbyB(a , b): \n", 564 | " try: \n", 565 | " c = ((a+b) / (a-b)) \n", 566 | " except ZeroDivisionError: \n", 567 | " print (\"a/b result in 0\")\n", 568 | " else: \n", 569 | " print(c) \n", 570 | " \n", 571 | "# Driver program to test above function \n", 572 | "AbyB(2, 3) \n", 573 | "AbyB(3, 3)" 574 | ] 575 | }, 576 | { 577 | "cell_type": "code", 578 | "execution_count": null, 579 | "metadata": {}, 580 | "outputs": [], 581 | "source": [ 582 | "try: \n", 583 | " f = open('missing') \n", 584 | "except FileNotFoundError: \n", 585 | " print('File not Found') \n", 586 | "except OSError: \n", 587 | " print('OS Failed')" 588 | ] 589 | }, 590 | { 591 | "cell_type": "code", 592 | "execution_count": null, 593 | "metadata": {}, 594 | "outputs": [], 595 | "source": [ 596 | "f = open('missing')" 597 | ] 598 | }, 599 | { 600 | "cell_type": "code", 601 | "execution_count": null, 602 | "metadata": {}, 603 | "outputs": [], 604 | "source": [ 605 | "try: \n", 606 | " a = 10/0\n", 607 | " print(a)\n", 608 | "except ArithmeticError: \n", 609 | " print (\"This statement is raising an arithmetic exception\")\n", 610 | "else: \n", 611 | " print (\"Success\")" 612 | ] 613 | }, 614 | { 615 | "cell_type": "code", 616 | "execution_count": null, 617 | "metadata": {}, 618 | "outputs": [], 619 | "source": [ 620 | "# import module sys to get the type of exception\n", 621 | "import sys\n", 622 | "\n", 623 | "randomList = ['a', 0, 2]\n", 624 | "\n", 625 | "for entry in randomList:\n", 626 | " try:\n", 627 | " print(\"The entry is\", entry)\n", 628 | " r = 1/int(entry)\n", 629 | " break\n", 630 | " except:\n", 631 | " print(\"Oops!\",sys.exc_info()[0],\"occured.\")\n", 632 | " print(\"Next entry.\")\n", 633 | " print()\n", 634 | "print(\"The reciprocal of\",entry,\"is\",r)" 635 | ] 636 | }, 637 | { 638 | "cell_type": "code", 639 | "execution_count": null, 640 | "metadata": {}, 641 | "outputs": [], 642 | "source": [ 643 | "try:\n", 644 | " a = int(input(\"Enter a positive integer: \"))\n", 645 | " print(a)\n", 646 | " if a <= 0:\n", 647 | " raise ValueError(\"That is not a positive number!\")\n", 648 | " else:\n", 649 | " print(a*25)\n", 650 | "except ValueError as ve:\n", 651 | " print(ve)" 652 | ] 653 | }, 654 | { 655 | "cell_type": "code", 656 | "execution_count": null, 657 | "metadata": {}, 658 | "outputs": [], 659 | "source": [ 660 | "try:\n", 661 | " f = open(\"test.txt\",'w', encoding = 'utf-8')\n", 662 | " f.write('gutyjbkj')\n", 663 | " f.write('gjhguytuytufuty')\n", 664 | " # perform file operations\n", 665 | "finally:\n", 666 | " f.close()" 667 | ] 668 | } 669 | ], 670 | "metadata": { 671 | "kernelspec": { 672 | "display_name": "Python 3", 673 | "language": "python", 674 | "name": "python3" 675 | }, 676 | "language_info": { 677 | "codemirror_mode": { 678 | "name": "ipython", 679 | "version": 3 680 | }, 681 | "file_extension": ".py", 682 | "mimetype": "text/x-python", 683 | "name": "python", 684 | "nbconvert_exporter": "python", 685 | "pygments_lexer": "ipython3", 686 | "version": "3.7.4" 687 | } 688 | }, 689 | "nbformat": 4, 690 | "nbformat_minor": 2 691 | } 692 | -------------------------------------------------------------------------------- /8. Python with Database.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# SQL with Python\n", 8 | "* To use SQL, we must import sqlite3.\n", 9 | "\n", 10 | " * Then create a connection using connect() method and pass the name of the database \n", 11 | " you want to access if there is a file with that name, it will open that file. \n", 12 | " Otherwise Python will create a file with the given name.\n", 13 | " \n", 14 | "\n", 15 | "* After this, a cursor object is called to be capable to send commands to the SQL. \n", 16 | "\n", 17 | "* Cursor is a control structure used to traverse and fetch the records of the database. \n", 18 | "* Cursor has a major role in working with Python. \n", 19 | "\n", 20 | " * All the commands will be executed using cursor object only.\n", 21 | " * To create a table in the database, create an object and write the SQL command in it with being commented.\n", 22 | " * Example:- sql_comm = ”SQL statement”\n", 23 | "\n", 24 | "\n", 25 | "* And executing the command is very easy. Call the cursor method execute and pass the name of the sql \n", 26 | "command as a parameter in it. Save a number of commands as the sql_comm and execute them. \n", 27 | "\n", 28 | "* After you perform all your activities, save the changes in the file by committing those changes and then lose the connection." 29 | ] 30 | }, 31 | { 32 | "cell_type": "code", 33 | "execution_count": null, 34 | "metadata": {}, 35 | "outputs": [], 36 | "source": [ 37 | "# Python code to demonstrate table creation and \n", 38 | "# insertions with SQL \n", 39 | " \n", 40 | "# importing module \n", 41 | "import sqlite3\n", 42 | " \n", 43 | "# connecting to the database \n", 44 | "connection = sqlite3.connect(\"myTable.db\") \n", 45 | " \n", 46 | "# cursor \n", 47 | "crsr = connection.cursor() \n", 48 | " \n", 49 | "# SQL command to create a table in the database \n", 50 | "sql_command = \"\"\"CREATE TABLE emp ( \n", 51 | "staff_number INTEGER PRIMARY KEY, \n", 52 | "fname VARCHAR(20), \n", 53 | "lname VARCHAR(30), \n", 54 | "gender CHAR(1), \n", 55 | "joining DATE);\"\"\"\n", 56 | " \n", 57 | "# execute the statement \n", 58 | "crsr.execute(sql_command) \n", 59 | " \n", 60 | "# SQL command to insert the data in the table \n", 61 | "sql_command = \"\"\"INSERT INTO emp VALUES (23, \"Rishabh\", \"Bansal\", \"M\", \"2014-03-28\");\"\"\"\n", 62 | "crsr.execute(sql_command) \n", 63 | " \n", 64 | "# another SQL command to insert the data in the table \n", 65 | "sql_command = \"\"\"INSERT INTO emp VALUES (1, \"Bill\", \"Gates\", \"M\", \"1980-10-28\");\"\"\"\n", 66 | "crsr.execute(sql_command) \n", 67 | " \n", 68 | "# To save the changes in the files. Never skip this. \n", 69 | "# If we skip this, nothing will be saved in the database. \n", 70 | "connection.commit() \n", 71 | " \n", 72 | "# close the connection \n", 73 | "connection.close() " 74 | ] 75 | }, 76 | { 77 | "cell_type": "markdown", 78 | "metadata": {}, 79 | "source": [ 80 | "### Fetching the data from record is simple as the inserting them" 81 | ] 82 | }, 83 | { 84 | "cell_type": "code", 85 | "execution_count": null, 86 | "metadata": {}, 87 | "outputs": [], 88 | "source": [ 89 | "# connect withe the myTable database \n", 90 | "connection = sqlite3.connect(\"myTable.db\") \n", 91 | " \n", 92 | "# cursor object \n", 93 | "crsr = connection.cursor() \n", 94 | " \n", 95 | "# execute the command to fetch all the data from the table emp \n", 96 | "crsr.execute(\"SELECT * FROM emp\") \n", 97 | " \n", 98 | "# store all the fetched data in the ans variable \n", 99 | "ans= crsr.fetchall() \n", 100 | " \n", 101 | "# loop to print all the data \n", 102 | "for i in ans: \n", 103 | " print(i)" 104 | ] 105 | }, 106 | { 107 | "cell_type": "code", 108 | "execution_count": null, 109 | "metadata": {}, 110 | "outputs": [], 111 | "source": [ 112 | "# Updation and Deletion Operation\n", 113 | "\n", 114 | "conn = sqlite3.connect('myTable.db') \n", 115 | " \n", 116 | "# update the student record \n", 117 | "conn.execute(\"UPDATE emp SET fname = 'Sam' where fname='Rishabh'\") \n", 118 | "conn.commit() \n", 119 | " \n", 120 | "print (\"Total number of rows updated :\", conn.total_changes )\n", 121 | " \n", 122 | "cursor = conn.execute(\"SELECT * FROM emp\") \n", 123 | "for row in cursor: \n", 124 | " print (row)\n", 125 | "\n", 126 | "conn.close()" 127 | ] 128 | }, 129 | { 130 | "cell_type": "code", 131 | "execution_count": null, 132 | "metadata": {}, 133 | "outputs": [], 134 | "source": [ 135 | "# database name to be passed as parameter \n", 136 | "conn = sqlite3.connect('myTable.db') \n", 137 | " \n", 138 | "# delete student record from database \n", 139 | "conn.execute(\"DELETE from emp where fname='Sam'\") \n", 140 | "conn.commit() \n", 141 | "print (\"Total number of rows deleted :\", conn.total_changes)\n", 142 | " \n", 143 | "cursor = conn.execute(\"SELECT * FROM emp\") \n", 144 | "for row in cursor: \n", 145 | " print (row) \n", 146 | " \n", 147 | "conn.close()" 148 | ] 149 | }, 150 | { 151 | "cell_type": "markdown", 152 | "metadata": {}, 153 | "source": [ 154 | "### Data input by User" 155 | ] 156 | }, 157 | { 158 | "cell_type": "code", 159 | "execution_count": null, 160 | "metadata": {}, 161 | "outputs": [], 162 | "source": [ 163 | "# creates a database in RAM \n", 164 | "con = sqlite3.connect(\":memory:\") \n", 165 | "cur = con.cursor() \n", 166 | "cur.execute(\"create table person (name, age, id)\") \n", 167 | " \n", 168 | "print (\"Enter 5 students names:\") \n", 169 | "who = [input() for i in range(5)] \n", 170 | "print (\"Enter their ages respectively:\") \n", 171 | "age = [int(input()) for i in range(5)] \n", 172 | "print (\"Enter their ids respectively:\") \n", 173 | "p_id = [int(input()) for i in range(5)] \n", 174 | "n = len(who) \n", 175 | " \n", 176 | "for i in range(n): \n", 177 | " \n", 178 | " # This is the q-mark style: \n", 179 | " cur.execute(\"insert into person values (?, ?, ?)\", (who[i], age[i], p_id[i])) \n", 180 | " \n", 181 | " # And this is the named style: \n", 182 | " cur.execute(\"select * from person\") \n", 183 | " \n", 184 | " # Fetches all entries from table \n", 185 | " print (cur.fetchall())" 186 | ] 187 | }, 188 | { 189 | "cell_type": "markdown", 190 | "metadata": {}, 191 | "source": [ 192 | "## Graphing with SQLite" 193 | ] 194 | }, 195 | { 196 | "cell_type": "code", 197 | "execution_count": null, 198 | "metadata": {}, 199 | "outputs": [], 200 | "source": [ 201 | "import matplotlib.pyplot as plt \n", 202 | " \n", 203 | "def graph_data(p_id,age): \n", 204 | " \n", 205 | " # plotting the points \n", 206 | " plt.plot(p_id, age, color='yellow', linestyle='dashed', linewidth = 3, \n", 207 | " marker='*', markerfacecolor='blue', markersize=12) \n", 208 | " \n", 209 | " # naming the x axis \n", 210 | " plt.xlabel('Persons Id') \n", 211 | " \n", 212 | " # naming the y axis \n", 213 | " plt.ylabel('Ages') \n", 214 | " \n", 215 | " # plt.plot(p_id,age) \n", 216 | " plt.show() \n", 217 | " \n", 218 | "print (\"Enter 5 students names:\") \n", 219 | "who = [input() for i in range(5)] \n", 220 | "print (\"Enter their ages respectively:\") \n", 221 | "age = [int(input()) for i in range(5)] \n", 222 | "print (\"Enter their ids respectively:\") \n", 223 | "p_id = [int(input()) for i in range(5)] \n", 224 | " \n", 225 | "# calling graph function \n", 226 | "graph_data(p_id,age)" 227 | ] 228 | }, 229 | { 230 | "cell_type": "markdown", 231 | "metadata": {}, 232 | "source": [ 233 | "## executescript()\n", 234 | "* This is a convenience method for executing multiple SQL statements at once. \n", 235 | "It executes the SQL script it gets as a parameter." 236 | ] 237 | }, 238 | { 239 | "cell_type": "code", 240 | "execution_count": null, 241 | "metadata": {}, 242 | "outputs": [], 243 | "source": [ 244 | "# Connection with the DataBase \n", 245 | "# 'library.db' \n", 246 | "connection = sqlite3.connect(\"library.db\") \n", 247 | "cursor = connection.cursor() \n", 248 | " \n", 249 | "# SQL piece of code Executed \n", 250 | "# SQL piece of code Executed \n", 251 | "cursor.executescript(\"\"\" \n", 252 | " CREATE TABLE people( \n", 253 | " firstname, \n", 254 | " lastname, \n", 255 | " age \n", 256 | " ); \n", 257 | " \n", 258 | " CREATE TABLE book( \n", 259 | " title, \n", 260 | " author, \n", 261 | " published \n", 262 | " ); \n", 263 | " \n", 264 | " INSERT INTO \n", 265 | " book(title, author, published) \n", 266 | " VALUES ( \n", 267 | " 'Dan Clarke''s GFG Detective Agency', \n", 268 | " 'Sean Simpsons', \n", 269 | " 1987 \n", 270 | " ); \n", 271 | " \"\"\") \n", 272 | " \n", 273 | "sql = \"\"\" \n", 274 | "SELECT COUNT(*) FROM book;\"\"\"\n", 275 | " \n", 276 | "cursor.execute(sql) \n", 277 | " \n", 278 | "# The output in fetched and returned \n", 279 | "# as a List by fetchall() \n", 280 | "result = cursor.fetchall() \n", 281 | "print(result) \n", 282 | " \n", 283 | "sql = \"\"\" \n", 284 | "SELECT * FROM book;\"\"\"\n", 285 | " \n", 286 | "cursor.execute(sql) \n", 287 | " \n", 288 | "result = cursor.fetchall() \n", 289 | "print(result) \n", 290 | " \n", 291 | "# Changes saved into database \n", 292 | "connection.commit() \n", 293 | " \n", 294 | "# Connection closed(broken) \n", 295 | "# with DataBase \n", 296 | "connection.close() " 297 | ] 298 | }, 299 | { 300 | "cell_type": "markdown", 301 | "metadata": {}, 302 | "source": [ 303 | "## executemany()\n", 304 | "\n", 305 | "* It is often the case when, large amount of data has to be inserted into database from \n", 306 | "Data Files(for simpler case take Lists, arrays). \n", 307 | "* It would be simple to iterate the code many a times than write every time, each line into database." 308 | ] 309 | }, 310 | { 311 | "cell_type": "code", 312 | "execution_count": null, 313 | "metadata": {}, 314 | "outputs": [], 315 | "source": [ 316 | "# Connection with the DataBase \n", 317 | "# 'library.db' \n", 318 | "connection = sqlite3.connect(\"library.db\") \n", 319 | "cursor = connection.cursor() \n", 320 | " \n", 321 | "# SQL piece of code Executed \n", 322 | "cursor.execute(\"\"\" \n", 323 | " \n", 324 | " CREATE TABLE books( \n", 325 | " title, \n", 326 | " author, \n", 327 | " published);\"\"\") \n", 328 | " \n", 329 | "List = [('A', 'B', 2008), ('C', 'D', 2008), \n", 330 | " ('E', 'F', 2010)] \n", 331 | " \n", 332 | "connection. executemany(\"\"\" \n", 333 | " \n", 334 | " INSERT INTO \n", 335 | " books(title, author, published) \n", 336 | " VALUES (?, ?, ?)\"\"\", List) \n", 337 | " \n", 338 | "sql = \"\"\" \n", 339 | " SELECT * FROM books;\"\"\"\n", 340 | "cursor.execute(sql) \n", 341 | "result = cursor.fetchall() \n", 342 | "for x in result: \n", 343 | " print(x) \n", 344 | " \n", 345 | "# Changes saved into database \n", 346 | "connection.commit() \n", 347 | " \n", 348 | "# Connection closed(broken) \n", 349 | "# with DataBase \n", 350 | "connection.close() " 351 | ] 352 | }, 353 | { 354 | "cell_type": "code", 355 | "execution_count": null, 356 | "metadata": {}, 357 | "outputs": [], 358 | "source": [ 359 | "# Connection created with the \n", 360 | "# database using sqlite3.connect() \n", 361 | "connection = sqlite3.connect(\"company.db\") \n", 362 | "cursor = connection.cursor() \n", 363 | " \n", 364 | "# Create Table command executed \n", 365 | "sql = \"\"\" \n", 366 | " CREATE TABLE employee ( \n", 367 | " ID INTEGER PRIMARY KEY, \n", 368 | " fname VARCHAR(20), \n", 369 | " lname VARCHAR(30), \n", 370 | " gender CHAR(1), \n", 371 | " dob DATE);\"\"\"\n", 372 | "cursor.execute(sql) \n", 373 | " \n", 374 | "# Single Tuple inserted \n", 375 | "sql = \"\"\" \n", 376 | " INSERT INTO employee \n", 377 | " VALUES (1007, \"Will\", \"Olsen\", \"M\", \"24-SEP-1865\");\"\"\"\n", 378 | "cursor.execute(sql) \n", 379 | " \n", 380 | "# Multiple Rows inserted \n", 381 | "List = [(1008, 'Rkb', 'Boss', 'M', \"27-NOV-1864\"), \n", 382 | " (1098, 'Sak', 'Rose', 'F', \"27-DEC-1864\"), \n", 383 | " (1908, 'Royal', 'Bassen', \"F\", \"17-NOV-1894\")] \n", 384 | " \n", 385 | "connection.executemany( \n", 386 | " \"INSERT INTO employee VALUES (?, ?, ?, ?, ?)\", List) \n", 387 | " \n", 388 | "print(\"Method-1\\n\") \n", 389 | " \n", 390 | "# Multiple Rows fetched from \n", 391 | "# the Database \n", 392 | "for row in connection.execute('SELECT * FROM employee ORDER BY ID'): \n", 393 | " print (row) \n", 394 | " \n", 395 | "print(\"\\nMethod-2\\n\") \n", 396 | " \n", 397 | "# Method-2 to fetch multiple \n", 398 | "# rows \n", 399 | "sql = \"\"\" \n", 400 | " SELECT * FROM employee ORDER BY ID;\"\"\"\n", 401 | " \n", 402 | "cursor.execute(sql) \n", 403 | "result = cursor.fetchall() \n", 404 | " \n", 405 | "for x in result: \n", 406 | " print(x) \n", 407 | " \n", 408 | "connection.commit() \n", 409 | "connection.close()" 410 | ] 411 | }, 412 | { 413 | "cell_type": "code", 414 | "execution_count": null, 415 | "metadata": {}, 416 | "outputs": [], 417 | "source": [ 418 | "#How to Connect Python and SQL Server\n", 419 | "import pyodbc\n", 420 | "conn = pyodbc.connect(\"Driver={SQL Server Native Client 11.0};\"\n", 421 | " \"Server=LAPTOP-LFBVI1JS\\SQLEXPRESS;\"\n", 422 | " \"Database=master;\"\n", 423 | " \"Trusted_Connection=yes;\")\n", 424 | "\n", 425 | "cursor = conn.cursor()\n", 426 | "cursor.execute('SELECT * FROM blood_pressure')\n", 427 | "\n", 428 | "for row in cursor:\n", 429 | " print('row = %r' % (row,))" 430 | ] 431 | }, 432 | { 433 | "cell_type": "code", 434 | "execution_count": null, 435 | "metadata": {}, 436 | "outputs": [], 437 | "source": [ 438 | "# Python SQL Create DB Example\n", 439 | "cursor = conn.cursor()\n", 440 | "cursor.execute(\"SELECT name FROM master.dbo.sysdatabases\")\n", 441 | "\n", 442 | "for x in cursor:\n", 443 | " print('Database = %r' %x)" 444 | ] 445 | }, 446 | { 447 | "cell_type": "code", 448 | "execution_count": null, 449 | "metadata": {}, 450 | "outputs": [], 451 | "source": [ 452 | "conn.autocommit = True\n", 453 | "cursor = conn.cursor()\n", 454 | "cursor.execute(\"CREATE DATABASE [PythonDatabase1]\")" 455 | ] 456 | }, 457 | { 458 | "cell_type": "code", 459 | "execution_count": null, 460 | "metadata": {}, 461 | "outputs": [], 462 | "source": [ 463 | "cursor = conn.cursor()\n", 464 | "cursor.execute(\"SELECT name FROM master.dbo.sysdatabases\")\n", 465 | "\n", 466 | "for x in cursor:\n", 467 | " print('Database = %r' %x)" 468 | ] 469 | }, 470 | { 471 | "cell_type": "code", 472 | "execution_count": null, 473 | "metadata": {}, 474 | "outputs": [], 475 | "source": [ 476 | "# Using the Select Statement\n", 477 | "cursor = conn.cursor()\n", 478 | "cursor.execute('SELECT patient, sex, agegrp, bp_before from blood_pressure')\n", 479 | "\n", 480 | "for row in cursor:\n", 481 | " print('row = %r' % (row,))" 482 | ] 483 | }, 484 | { 485 | "cell_type": "code", 486 | "execution_count": null, 487 | "metadata": {}, 488 | "outputs": [], 489 | "source": [ 490 | "#Another Select Statement\n", 491 | "cursor = conn.cursor()\n", 492 | "cursor.execute('SELECT * FROM blood_pressure')\n", 493 | "result = cursor.fetchone()\n", 494 | "print(result)" 495 | ] 496 | }, 497 | { 498 | "cell_type": "code", 499 | "execution_count": null, 500 | "metadata": {}, 501 | "outputs": [], 502 | "source": [ 503 | "# Order By Statement\n", 504 | "cursor = conn.cursor()\n", 505 | "cursor.execute('SELECT * FROM blood_pressure ORDER BY agegrp')\n", 506 | "\n", 507 | "for row in cursor:\n", 508 | " print('row = %r' % (row,))" 509 | ] 510 | }, 511 | { 512 | "cell_type": "code", 513 | "execution_count": null, 514 | "metadata": {}, 515 | "outputs": [], 516 | "source": [ 517 | "# Order By Statement - Descending Order\n", 518 | "cursor = conn.cursor()\n", 519 | "cursor.execute('SELECT * FROM blood_pressure ORDER BY agegrp desc')\n", 520 | "\n", 521 | "for row in cursor:\n", 522 | " print('row = %r' % (row,))" 523 | ] 524 | }, 525 | { 526 | "cell_type": "code", 527 | "execution_count": null, 528 | "metadata": {}, 529 | "outputs": [], 530 | "source": [ 531 | "#Selection Top N items\n", 532 | "cursor = conn.cursor()\n", 533 | "cursor.execute('SELECT Top 1 * FROM blood_pressure')\n", 534 | "for row in cursor:\n", 535 | " print('row = %r' % (row,))" 536 | ] 537 | }, 538 | { 539 | "cell_type": "code", 540 | "execution_count": null, 541 | "metadata": {}, 542 | "outputs": [], 543 | "source": [ 544 | "#Selection Top N items and Ordering by\n", 545 | "cursor = conn.cursor()\n", 546 | "cursor.execute('SELECT Top 10 * FROM blood_pressure ORDER BY agegrp desc')\n", 547 | "for row in cursor:\n", 548 | " print('row = %r' % (row,))" 549 | ] 550 | }, 551 | { 552 | "cell_type": "code", 553 | "execution_count": null, 554 | "metadata": {}, 555 | "outputs": [], 556 | "source": [ 557 | "#Selection Top N items by Percentage and Ordering by\n", 558 | "cursor = conn.cursor()\n", 559 | "cursor.execute('SELECT Top 40 Percent * FROM blood_pressure ORDER BY agegrp desc')\n", 560 | "for row in cursor:\n", 561 | " print('row = %r' % (row,))" 562 | ] 563 | }, 564 | { 565 | "cell_type": "code", 566 | "execution_count": null, 567 | "metadata": {}, 568 | "outputs": [], 569 | "source": [ 570 | "#Selecting Data by Where Clause\n", 571 | "cursor = conn.cursor()\n", 572 | "cursor.execute(\"SELECT * FROM blood_pressure where sex = 'Male' ORDER BY agegrp desc\")\n", 573 | "for row in cursor:\n", 574 | " print('row = %r' % (row,))" 575 | ] 576 | }, 577 | { 578 | "cell_type": "code", 579 | "execution_count": null, 580 | "metadata": {}, 581 | "outputs": [], 582 | "source": [ 583 | "#Selecting Data by Where Clause\n", 584 | "cursor = conn.cursor()\n", 585 | "cursor.execute(\"SELECT * FROM blood_pressure where bp_before >= 130 ORDER BY agegrp desc\")\n", 586 | "for row in cursor:\n", 587 | " print('row = %r' % (row,))" 588 | ] 589 | } 590 | ], 591 | "metadata": { 592 | "kernelspec": { 593 | "display_name": "Python 3", 594 | "language": "python", 595 | "name": "python3" 596 | }, 597 | "language_info": { 598 | "codemirror_mode": { 599 | "name": "ipython", 600 | "version": 3 601 | }, 602 | "file_extension": ".py", 603 | "mimetype": "text/x-python", 604 | "name": "python", 605 | "nbconvert_exporter": "python", 606 | "pygments_lexer": "ipython3", 607 | "version": "3.7.4" 608 | } 609 | }, 610 | "nbformat": 4, 611 | "nbformat_minor": 2 612 | } 613 | -------------------------------------------------------------------------------- /4. Collections and Sets.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "## namedtuple( )\n", 8 | "* It returns a tuple with a named entry, which means there will be a name assigned to each value in the tuple. \n", 9 | "* It overcomes the problem of accessing the elements using the index values. With namedtuple( )" 10 | ] 11 | }, 12 | { 13 | "cell_type": "code", 14 | "execution_count": null, 15 | "metadata": {}, 16 | "outputs": [], 17 | "source": [ 18 | "from collections import namedtuple" 19 | ] 20 | }, 21 | { 22 | "cell_type": "code", 23 | "execution_count": null, 24 | "metadata": {}, 25 | "outputs": [], 26 | "source": [ 27 | "a = 'Gowtham', 'State Street'\n", 28 | "print(type(a))\n", 29 | "print(a)" 30 | ] 31 | }, 32 | { 33 | "cell_type": "code", 34 | "execution_count": null, 35 | "metadata": {}, 36 | "outputs": [], 37 | "source": [ 38 | "a = namedtuple('courses' , 'name, tech, year')\n", 39 | "s = a('data science' , 'python', 2020)\n", 40 | "print(s)" 41 | ] 42 | }, 43 | { 44 | "cell_type": "code", 45 | "execution_count": null, 46 | "metadata": {}, 47 | "outputs": [], 48 | "source": [ 49 | "# How To Create A namedtuple Using A List?\n", 50 | "s._make(['data science' , 'python',2020])" 51 | ] 52 | }, 53 | { 54 | "cell_type": "code", 55 | "execution_count": null, 56 | "metadata": {}, 57 | "outputs": [], 58 | "source": [ 59 | "# Accessing the values\n", 60 | "Student = namedtuple('Student', 'fname, lname, age')\n", 61 | "s1 = Student('John', 'Clarke', '13')\n", 62 | "print(s1.fname)\n", 63 | "print(s1.lname)\n", 64 | "print(s1.age)" 65 | ] 66 | }, 67 | { 68 | "cell_type": "code", 69 | "execution_count": null, 70 | "metadata": {}, 71 | "outputs": [], 72 | "source": [ 73 | "# With List\n", 74 | "s2 = Student._make(['Adam','joe','18'])\n", 75 | "print(s2)" 76 | ] 77 | }, 78 | { 79 | "cell_type": "code", 80 | "execution_count": null, 81 | "metadata": {}, 82 | "outputs": [], 83 | "source": [ 84 | "# Create a New Instance Using Existing Instance\n", 85 | "\n", 86 | "s2 = s1._asdict()\n", 87 | "print(s2)" 88 | ] 89 | }, 90 | { 91 | "cell_type": "code", 92 | "execution_count": null, 93 | "metadata": {}, 94 | "outputs": [], 95 | "source": [ 96 | "# Changing Field Values with _replace() Function\n", 97 | "\n", 98 | "s2 = s1._replace(age='14')\n", 99 | "print(s1)\n", 100 | "print(s2)" 101 | ] 102 | }, 103 | { 104 | "cell_type": "markdown", 105 | "metadata": {}, 106 | "source": [ 107 | "## deque\n", 108 | "* deque pronounced as ‘deck’ is an optimized list to perform insertion and deletion easily." 109 | ] 110 | }, 111 | { 112 | "cell_type": "code", 113 | "execution_count": null, 114 | "metadata": {}, 115 | "outputs": [], 116 | "source": [ 117 | "#creating a deque\n", 118 | "from collections import deque\n", 119 | " \n", 120 | "a = ['S' , 'T' , 'A' , 'T' , 'E']\n", 121 | "a1 = deque(a)\n", 122 | "print(a1)" 123 | ] 124 | }, 125 | { 126 | "cell_type": "code", 127 | "execution_count": null, 128 | "metadata": {}, 129 | "outputs": [], 130 | "source": [ 131 | "a = [\"a\",\"b\",\"c\"]\n", 132 | "deq = deque(a)\n", 133 | "print(deq)" 134 | ] 135 | }, 136 | { 137 | "cell_type": "code", 138 | "execution_count": null, 139 | "metadata": {}, 140 | "outputs": [], 141 | "source": [ 142 | "b = [\"a\",'a',\"b\",\"c\",'a', 'b']\n", 143 | "deq = deque(b)\n", 144 | "print(deq.count(\"a\"))" 145 | ] 146 | }, 147 | { 148 | "cell_type": "code", 149 | "execution_count": null, 150 | "metadata": {}, 151 | "outputs": [], 152 | "source": [ 153 | "# Now lets take a look at how we will insert and remove items from deque.\n", 154 | "\n", 155 | "a1.append('a')\n", 156 | "print(a1)\n", 157 | "\n", 158 | "a1.appendleft('e')\n", 159 | "print(a1)\n" 160 | ] 161 | }, 162 | { 163 | "cell_type": "code", 164 | "execution_count": null, 165 | "metadata": {}, 166 | "outputs": [], 167 | "source": [ 168 | "# inserting a component is enhanced utilizing deque, also you can remove components as well\n", 169 | "\n", 170 | "a1.pop()\n", 171 | "print(a1)\n", 172 | "\n", 173 | "\n", 174 | "a1.popleft()\n", 175 | "print(a1)" 176 | ] 177 | }, 178 | { 179 | "cell_type": "markdown", 180 | "metadata": {}, 181 | "source": [ 182 | "## ChainMap\n", 183 | "* It is a dictionary like class which is able to make a single view of multiple mappings. \n", 184 | "* It basically returns a list of several other dictionaries. Suppose you have two dictionaries with several key value pairs, \n", 185 | "* in this case ChainMap will make a single list with both the dictionaries in it." 186 | ] 187 | }, 188 | { 189 | "cell_type": "code", 190 | "execution_count": null, 191 | "metadata": {}, 192 | "outputs": [], 193 | "source": [ 194 | "from collections import ChainMap\n", 195 | "a = {1: 'Programming' , 2: 'python'}\n", 196 | "b = {3: 'data science', 4: 'Machine learning'}\n", 197 | "c = ChainMap(a,b)\n", 198 | "print(c)" 199 | ] 200 | }, 201 | { 202 | "cell_type": "code", 203 | "execution_count": null, 204 | "metadata": { 205 | "scrolled": true 206 | }, 207 | "outputs": [], 208 | "source": [ 209 | "dict1 = { 'a' : 1, 'b' : 2 }\n", 210 | "dict2 = { 'c' : 3, 'b' : 4 }\n", 211 | "chain_map = ChainMap(dict1, dict2)\n", 212 | "print(chain_map.maps)" 213 | ] 214 | }, 215 | { 216 | "cell_type": "code", 217 | "execution_count": null, 218 | "metadata": {}, 219 | "outputs": [], 220 | "source": [ 221 | "print(chain_map['a'])" 222 | ] 223 | }, 224 | { 225 | "cell_type": "code", 226 | "execution_count": null, 227 | "metadata": {}, 228 | "outputs": [], 229 | "source": [ 230 | "dict2['c'] = 5\n", 231 | "print(chain_map.maps)" 232 | ] 233 | }, 234 | { 235 | "cell_type": "code", 236 | "execution_count": null, 237 | "metadata": {}, 238 | "outputs": [], 239 | "source": [ 240 | "import collections\n", 241 | "\n", 242 | "# initializing dictionaries \n", 243 | "dic1 = { 'a' : 1, 'b' : 2 } \n", 244 | "dic2 = { 'b' : 3, 'c' : 4 } \n", 245 | " \n", 246 | "# initializing ChainMap \n", 247 | "chain = collections.ChainMap(dic1, dic2) \n", 248 | " \n", 249 | "# printing chainMap using maps \n", 250 | "print (\"All the ChainMap contents are : \") \n", 251 | "print (chain.maps) \n", 252 | "\n", 253 | "dic3 = { 'f' : 5 } \n", 254 | "\n", 255 | "# using new_child() to add new dictionary \n", 256 | "chain1 = chain.new_child(dic3) \n", 257 | "\n", 258 | "# printing chainMap using map \n", 259 | "print (\"Displaying new ChainMap : \") \n", 260 | "print (chain1.maps)" 261 | ] 262 | }, 263 | { 264 | "cell_type": "code", 265 | "execution_count": null, 266 | "metadata": {}, 267 | "outputs": [], 268 | "source": [ 269 | "dict3 = {'e' : 5, 'f' : 6}#Adding a New Dictionary to ChainMap\n", 270 | "new_chain_map = chain_map.new_child(dict3)\n", 271 | "print(new_chain_map)" 272 | ] 273 | }, 274 | { 275 | "cell_type": "markdown", 276 | "metadata": {}, 277 | "source": [ 278 | "* To access or insert elements we use the keys as index. \n", 279 | "* But to add a new dictionary in the ChainMap we use the following approach." 280 | ] 281 | }, 282 | { 283 | "cell_type": "code", 284 | "execution_count": null, 285 | "metadata": {}, 286 | "outputs": [], 287 | "source": [ 288 | "a1 = { 5: 'AI' , 6: 'neural networks'}\n", 289 | "c1 = c.new_child(a1)\n", 290 | "print(c1)" 291 | ] 292 | }, 293 | { 294 | "cell_type": "markdown", 295 | "metadata": {}, 296 | "source": [ 297 | "## Counter\n", 298 | "* It is a dictionary subclass which is used to count objects." 299 | ] 300 | }, 301 | { 302 | "cell_type": "code", 303 | "execution_count": null, 304 | "metadata": {}, 305 | "outputs": [], 306 | "source": [ 307 | "from collections import Counter" 308 | ] 309 | }, 310 | { 311 | "cell_type": "code", 312 | "execution_count": null, 313 | "metadata": {}, 314 | "outputs": [], 315 | "source": [ 316 | "a = [1,1,1,1,2,3,3,4,3,3,4]\n", 317 | "c = Counter(a)\n", 318 | "print(c)" 319 | ] 320 | }, 321 | { 322 | "cell_type": "code", 323 | "execution_count": null, 324 | "metadata": {}, 325 | "outputs": [], 326 | "source": [ 327 | "a = [1,2,3,4,1,2,6,7,3,8,1]\n", 328 | "Counter(a)" 329 | ] 330 | }, 331 | { 332 | "cell_type": "code", 333 | "execution_count": null, 334 | "metadata": {}, 335 | "outputs": [], 336 | "source": [ 337 | "Counter({1:3,2:4}) #the Counter() function can take a dictionary as an argument. \n", 338 | "# In this dictionary, the value of a key should be the 'count' of that key." 339 | ] 340 | }, 341 | { 342 | "cell_type": "code", 343 | "execution_count": null, 344 | "metadata": {}, 345 | "outputs": [], 346 | "source": [ 347 | "list = [1,2,3,4,1,2,6,7,3,8,1]\n", 348 | "cnt = Counter(list)\n", 349 | "print(cnt[1])" 350 | ] 351 | }, 352 | { 353 | "cell_type": "markdown", 354 | "metadata": {}, 355 | "source": [ 356 | "#### Apart from that, Counter has three additional functions:\n", 357 | "\n", 358 | "* Elements\n", 359 | "* Most_common([n])\n", 360 | "* Subtract([interable-or-mapping])" 361 | ] 362 | }, 363 | { 364 | "cell_type": "code", 365 | "execution_count": null, 366 | "metadata": {}, 367 | "outputs": [], 368 | "source": [ 369 | "# The element() Function - returns an iterator object for the values in the Counter.\n", 370 | "\n", 371 | "x = Counter(\"State Street\") \n", 372 | " \n", 373 | "# printing the elements of counter object \n", 374 | "for i in x.elements(): \n", 375 | " print( i, end = \" \")" 376 | ] 377 | }, 378 | { 379 | "cell_type": "code", 380 | "execution_count": null, 381 | "metadata": {}, 382 | "outputs": [], 383 | "source": [ 384 | "# Example - 2 \n", 385 | "b = Counter({'State' : 4, 'Street' : 1, \n", 386 | " 'Bellandur' : 2, 'python' : 3}) \n", 387 | " \n", 388 | "for i in b.elements(): \n", 389 | " print ( i, end = \" \") \n", 390 | "print() \n", 391 | " \n", 392 | "# Example - 3 \n", 393 | "c = Counter([1, 2, 21, 12, 2, 44, 5, 13, 15, 5, 19, 21, 5]) \n", 394 | " \n", 395 | "for i in c.elements(): \n", 396 | " print ( i, end = \" \") \n", 397 | "print() \n", 398 | " \n", 399 | "# Example - 4 \n", 400 | "d = Counter( a = 2, b = 3, c = 6, d = 1, e = 5) \n", 401 | " \n", 402 | "for i in d.elements(): \n", 403 | " print ( i, end = \" \") " 404 | ] 405 | }, 406 | { 407 | "cell_type": "code", 408 | "execution_count": null, 409 | "metadata": {}, 410 | "outputs": [], 411 | "source": [ 412 | "# The most_common() Function\n", 413 | "\n", 414 | "list = [1,2,3,4,1,2,6,7,3,8,1]\n", 415 | "cnt = Counter(list)\n", 416 | "print(cnt.most_common())" 417 | ] 418 | }, 419 | { 420 | "cell_type": "code", 421 | "execution_count": null, 422 | "metadata": {}, 423 | "outputs": [], 424 | "source": [ 425 | "coun = Counter(a=1, b=2, c=3, d=120, e=1, f=219) \n", 426 | " \n", 427 | "# This prints 3 most frequent characters \n", 428 | "for letter, count in coun.most_common(3): \n", 429 | " print('%s: %d' % (letter, count))" 430 | ] 431 | }, 432 | { 433 | "cell_type": "code", 434 | "execution_count": null, 435 | "metadata": {}, 436 | "outputs": [], 437 | "source": [ 438 | "# Arithmetic operations in counter\n", 439 | "import collections\n", 440 | "\n", 441 | "c1 = collections.Counter(['a', 'b', 'c', 'a', 'b', 'b'])\n", 442 | "c2 = collections.Counter('alphabet')\n", 443 | "\n", 444 | "print ('C1:', c1)\n", 445 | "print ('C2:', c2)\n", 446 | "\n", 447 | "print ('\\nCombined counts:')\n", 448 | "print (c1 + c2)\n", 449 | "\n", 450 | "print ('\\nSubtraction:')\n", 451 | "print (c1 - c2)\n", 452 | "\n", 453 | "print ('\\nIntersection (taking positive minimums):')\n", 454 | "print (c1 & c2)\n", 455 | "\n", 456 | "print ('\\nUnion (taking maximums):')\n", 457 | "print (c1 | c2)" 458 | ] 459 | }, 460 | { 461 | "cell_type": "markdown", 462 | "metadata": {}, 463 | "source": [ 464 | "## OrderedDict\n", 465 | "\n", 466 | "* It is a dictionary subclass which remembers the order in which the entries were added. \n", 467 | "* Basically, even if you change the value of the key, \n", 468 | "* the position will not be changed because of the order in which it was inserted in the dictionary." 469 | ] 470 | }, 471 | { 472 | "cell_type": "code", 473 | "execution_count": null, 474 | "metadata": {}, 475 | "outputs": [], 476 | "source": [ 477 | "from collections import OrderedDict\n", 478 | "od = OrderedDict()\n", 479 | "od[1] = 's'\n", 480 | "od[2] = 't'\n", 481 | "od[3] = 'a'\n", 482 | "od[4] = 't'\n", 483 | "od[5] = 'e'\n", 484 | "print(od)" 485 | ] 486 | }, 487 | { 488 | "cell_type": "code", 489 | "execution_count": null, 490 | "metadata": {}, 491 | "outputs": [], 492 | "source": [ 493 | "od = OrderedDict()\n", 494 | "od['a'] = 1\n", 495 | "od['b'] = 2\n", 496 | "od['c'] = 3\n", 497 | "print(od)" 498 | ] 499 | }, 500 | { 501 | "cell_type": "code", 502 | "execution_count": null, 503 | "metadata": {}, 504 | "outputs": [], 505 | "source": [ 506 | "od.keys()" 507 | ] 508 | }, 509 | { 510 | "cell_type": "code", 511 | "execution_count": null, 512 | "metadata": {}, 513 | "outputs": [], 514 | "source": [ 515 | "od.values()" 516 | ] 517 | }, 518 | { 519 | "cell_type": "code", 520 | "execution_count": null, 521 | "metadata": {}, 522 | "outputs": [], 523 | "source": [ 524 | "for key, value in od.items():\n", 525 | " print(key, value)" 526 | ] 527 | }, 528 | { 529 | "cell_type": "code", 530 | "execution_count": null, 531 | "metadata": {}, 532 | "outputs": [], 533 | "source": [ 534 | "q = [\"a\",\"c\",\"c\",\"a\",\"b\",\"a\",\"a\",\"b\",\"c\"]\n", 535 | "cnt = Counter(q)\n", 536 | "od = OrderedDict(cnt.most_common())\n", 537 | "for key, value in od.items():\n", 538 | " print(key, value)" 539 | ] 540 | }, 541 | { 542 | "cell_type": "markdown", 543 | "metadata": {}, 544 | "source": [ 545 | "## Defaultdict\n", 546 | "\n", 547 | "* Defaultdict is a sub-class of the dict class that returns a dictionary-like object. \n", 548 | "* The functionality of both dictionaries and defualtdict are almost same except for the fact that \n", 549 | "defualtdict never raises a KeyError. \n", 550 | "* It provides a default value for the key that does not exists." 551 | ] 552 | }, 553 | { 554 | "cell_type": "code", 555 | "execution_count": null, 556 | "metadata": {}, 557 | "outputs": [], 558 | "source": [ 559 | "from collections import defaultdict\n", 560 | "d = defaultdict(int)\n", 561 | "#we have to specify a type as well.\n", 562 | "d[1] = 'State'\n", 563 | "d[2] = 'python'\n", 564 | "print(d[3])\n", 565 | "#it will give the output as 0 instead of keyerror." 566 | ] 567 | }, 568 | { 569 | "cell_type": "code", 570 | "execution_count": null, 571 | "metadata": {}, 572 | "outputs": [], 573 | "source": [ 574 | "nums = defaultdict(int)\n", 575 | "nums['one'] = 1\n", 576 | "nums['two'] = 2\n", 577 | "print(nums['three'])" 578 | ] 579 | }, 580 | { 581 | "cell_type": "code", 582 | "execution_count": null, 583 | "metadata": {}, 584 | "outputs": [], 585 | "source": [ 586 | "from collections import defaultdict\n", 587 | "\n", 588 | "count = defaultdict(int)\n", 589 | "names_list = \"Mike John Mike Anna Mike John John Mike Mike Britney Smith Anna Smith\".split()\n", 590 | "for names in names_list:\n", 591 | " count[names] +=1\n", 592 | "print(count)" 593 | ] 594 | }, 595 | { 596 | "cell_type": "code", 597 | "execution_count": null, 598 | "metadata": {}, 599 | "outputs": [], 600 | "source": [ 601 | "# Function to return a default values for keys that is not present \n", 602 | "def def_value(): \n", 603 | " return \"Not Present\"\n", 604 | " \n", 605 | "# Defining the dict \n", 606 | "d = defaultdict(def_value) \n", 607 | "d[\"a\"] = 1\n", 608 | "d[\"b\"] = 2\n", 609 | "\n", 610 | "print(d[\"a\"]) \n", 611 | "print(d[\"b\"]) \n", 612 | "print(d[\"c\"])" 613 | ] 614 | }, 615 | { 616 | "cell_type": "code", 617 | "execution_count": null, 618 | "metadata": {}, 619 | "outputs": [], 620 | "source": [ 621 | "# Defining the dict and passing \n", 622 | "# lambda as default_factory argument \n", 623 | "d = defaultdict(lambda: \"Not Present\") \n", 624 | "d[\"a\"] = 1\n", 625 | "d[\"b\"] = 2\n", 626 | " \n", 627 | "print(d[\"a\"]) \n", 628 | "print(d[\"b\"]) \n", 629 | "print(d[\"c\"])" 630 | ] 631 | }, 632 | { 633 | "cell_type": "markdown", 634 | "metadata": {}, 635 | "source": [ 636 | "## Sets\n", 637 | "\n", 638 | "* A Set is an unordered collection data type that is iterable, mutable and has no duplicate elements.\n", 639 | "* The major advantage of using a set, as opposed to \n", 640 | "* a list, is that it has a highly optimized method for checking whether a specific element is contained in the set." 641 | ] 642 | }, 643 | { 644 | "cell_type": "code", 645 | "execution_count": null, 646 | "metadata": {}, 647 | "outputs": [], 648 | "source": [ 649 | "Set = set([\"a\", \"b\", \"c\"]) \n", 650 | " \n", 651 | "print(\"Set: \") \n", 652 | "print(Set) \n", 653 | " \n", 654 | "# Adding element to the set \n", 655 | "Set.add(\"d\") \n", 656 | " \n", 657 | "print(\"\\nSet after adding: \") \n", 658 | "print(Set) " 659 | ] 660 | }, 661 | { 662 | "cell_type": "markdown", 663 | "metadata": {}, 664 | "source": [ 665 | "#### Frozen sets in Python are immutable objects that only support methods and operators that produce a result without affecting the frozen set or sets to which they are applied." 666 | ] 667 | }, 668 | { 669 | "cell_type": "code", 670 | "execution_count": null, 671 | "metadata": {}, 672 | "outputs": [], 673 | "source": [ 674 | "normal_set = set([\"a\", \"b\",\"c\"]) \n", 675 | " \n", 676 | "print(\"Normal Set\") \n", 677 | "print(normal_set) \n", 678 | " \n", 679 | "# A frozen set \n", 680 | "frozen_set = frozenset([\"e\", \"f\", \"g\"]) \n", 681 | " \n", 682 | "print(\"\\nFrozen Set\") \n", 683 | "print(frozen_set) \n", 684 | " \n", 685 | "# we are trying to add element to a frozen set \n", 686 | "# frozen_set.add(\"h\")" 687 | ] 688 | }, 689 | { 690 | "cell_type": "code", 691 | "execution_count": null, 692 | "metadata": {}, 693 | "outputs": [], 694 | "source": [ 695 | "# Adding Elements\n", 696 | "people = {\"Jay\", \"Idrish\", \"Archi\"} \n", 697 | " \n", 698 | "print(\"People:\", end = \" \") \n", 699 | "print(people) \n", 700 | " \n", 701 | "# This will add Daxit in the set \n", 702 | "people.add(\"Daxit\") \n", 703 | " \n", 704 | "# Adding elements to the set using iterator \n", 705 | "for i in range(1, 6): \n", 706 | " people.add(i) \n", 707 | " \n", 708 | "print(\"\\nSet after adding element:\", end = \" \") \n", 709 | "print(people)" 710 | ] 711 | }, 712 | { 713 | "cell_type": "code", 714 | "execution_count": null, 715 | "metadata": {}, 716 | "outputs": [], 717 | "source": [ 718 | "# initialize my_set\n", 719 | "my_set = {1,3}\n", 720 | "print(my_set)\n", 721 | "\n", 722 | "# my_set[0] # you will get an error TypeError: 'set' object does not support indexing\n", 723 | "\n", 724 | "# add an element\n", 725 | "my_set.add(2)\n", 726 | "print(my_set)\n", 727 | "\n", 728 | "# add multiple elements\n", 729 | "my_set.update([2,3,4])\n", 730 | "print(my_set)\n", 731 | "\n", 732 | "# add list and set\n", 733 | "my_set.update([4,5], {1,6,8})\n", 734 | "print(my_set)" 735 | ] 736 | }, 737 | { 738 | "cell_type": "code", 739 | "execution_count": null, 740 | "metadata": {}, 741 | "outputs": [], 742 | "source": [ 743 | "# Union\n", 744 | "\n", 745 | "people = {\"Jay\", \"Idrish\", \"Archil\"} \n", 746 | "vampires = {\"Karan\", \"Arjun\"} \n", 747 | "dracula = {\"Deepanshu\", \"Raju\"} \n", 748 | " \n", 749 | "# Union using union() function \n", 750 | "population = people.union(vampires) \n", 751 | " \n", 752 | "print(\"Union using union() function\") \n", 753 | "print(population) \n", 754 | " \n", 755 | "# Union using \"|\" operator \n", 756 | "population = people|dracula \n", 757 | " \n", 758 | "print(\"\\nUnion using '|' operator\") \n", 759 | "print(population)" 760 | ] 761 | }, 762 | { 763 | "cell_type": "code", 764 | "execution_count": null, 765 | "metadata": {}, 766 | "outputs": [], 767 | "source": [ 768 | "# Intersection\n", 769 | "\n", 770 | "set1 = set() \n", 771 | "set2 = set() \n", 772 | " \n", 773 | "for i in range(5): \n", 774 | " set1.add(i) \n", 775 | " \n", 776 | "for i in range(3,9): \n", 777 | " set2.add(i) \n", 778 | " \n", 779 | "# Intersection using \n", 780 | "# intersection() function \n", 781 | "set3 = set1.intersection(set2) \n", 782 | " \n", 783 | "print(\"Intersection using intersection() function\") \n", 784 | "print(set3) \n", 785 | " \n", 786 | "# Intersection using \"&\" operator \n", 787 | "set3 = set1 & set2 \n", 788 | " \n", 789 | "print(\"\\nIntersection using '&' operator\") \n", 790 | "print(set3) " 791 | ] 792 | }, 793 | { 794 | "cell_type": "code", 795 | "execution_count": null, 796 | "metadata": {}, 797 | "outputs": [], 798 | "source": [ 799 | "# Difference\n", 800 | "\n", 801 | "set1 = set() \n", 802 | "set2 = set() \n", 803 | " \n", 804 | "for i in range(5): \n", 805 | " set1.add(i) \n", 806 | " \n", 807 | "for i in range(3,9): \n", 808 | " set2.add(i) \n", 809 | " \n", 810 | "# Difference of two sets \n", 811 | "# using difference() function \n", 812 | "set3 = set1.difference(set2) \n", 813 | " \n", 814 | "print(\" Difference of two sets using difference() function\") \n", 815 | "print(set3) \n", 816 | " \n", 817 | "# Difference of two sets \n", 818 | "# using '-' operator \n", 819 | "set3 = set1 - set2 \n", 820 | "\n", 821 | "print(\"\\nDifference of two sets using '-' operator\") \n", 822 | "print(set3) " 823 | ] 824 | }, 825 | { 826 | "cell_type": "code", 827 | "execution_count": null, 828 | "metadata": {}, 829 | "outputs": [], 830 | "source": [ 831 | "# Clear() method empties the whole set.\n", 832 | "\n", 833 | "set1 = {1,2,3,4,5,6} \n", 834 | " \n", 835 | "print(\"Initial set\") \n", 836 | "print(set1) \n", 837 | " \n", 838 | "# This method will remove all the elements of the set \n", 839 | "set1.clear() \n", 840 | " \n", 841 | "print(\"\\nSet after using clear() function\") \n", 842 | "print(set1)" 843 | ] 844 | }, 845 | { 846 | "cell_type": "code", 847 | "execution_count": null, 848 | "metadata": {}, 849 | "outputs": [], 850 | "source": [ 851 | "# Operations in set\n", 852 | "\n", 853 | "# Creating two sets \n", 854 | "set1 = set() \n", 855 | "set2 = set() \n", 856 | " \n", 857 | "# Adding elements to set1 \n", 858 | "for i in range(1, 6): \n", 859 | " set1.add(i) \n", 860 | " \n", 861 | "# Adding elements to set2 \n", 862 | "for i in range(3, 8): \n", 863 | " set2.add(i) \n", 864 | " \n", 865 | "print(\"Set1 = \", set1) \n", 866 | "print(\"Set2 = \", set2) \n", 867 | "print(\"\\n\") \n", 868 | " \n", 869 | "# Union of set1 and set2 \n", 870 | "set3 = set1 | set2# set1.union(set2) \n", 871 | "print(\"Union of Set1 & Set2: Set3 = \", set3) \n", 872 | " \n", 873 | "# Intersection of set1 and set2 \n", 874 | "set4 = set1 & set2# set1.intersection(set2) \n", 875 | "print(\"Intersection of Set1 & Set2: Set4 = \", set4) \n", 876 | "print(\"\\n\") \n", 877 | " \n", 878 | "# Checking relation between set3 and set4 \n", 879 | "if set3 > set4: # set3.issuperset(set4) \n", 880 | " print(\"Set3 is superset of Set4\") \n", 881 | "elif set3 < set4: # set3.issubset(set4) \n", 882 | " print(\"Set3 is subset of Set4\") \n", 883 | "else : # set3 == set4 \n", 884 | " print(\"Set3 is same as Set4\") \n", 885 | " \n", 886 | "# displaying relation between set4 and set3 \n", 887 | "if set4 < set3: # set4.issubset(set3) \n", 888 | " print(\"Set4 is subset of Set3\") \n", 889 | " print(\"\\n\") \n", 890 | " \n", 891 | "# difference between set3 and set4 \n", 892 | "set5 = set3 - set4 \n", 893 | "print(\"Elements in Set3 and not in Set4: Set5 = \", set5) \n", 894 | "print(\"\\n\") \n", 895 | " \n", 896 | "# checkv if set4 and set5 are disjoint sets \n", 897 | "if set4.isdisjoint(set5): \n", 898 | " print(\"Set4 and Set5 have nothing in common\\n\") \n", 899 | " \n", 900 | "# Removing all the values of set5 \n", 901 | "set5.clear() \n", 902 | " \n", 903 | "print(\"After applying clear on sets Set5: \") \n", 904 | "print(\"Set5 = \", set5) \n", 905 | "\n", 906 | "# initialize A and B\n", 907 | "A = {1, 2, 3, 4, 5}\n", 908 | "B = {4, 5, 6, 7, 8}\n", 909 | "\n", 910 | "# use ^ operator for symmetric difference\n", 911 | "print('\\nThe elements from both the sets without anything in common', A ^ B)" 912 | ] 913 | }, 914 | { 915 | "cell_type": "code", 916 | "execution_count": null, 917 | "metadata": {}, 918 | "outputs": [], 919 | "source": [ 920 | "# initialize my_set\n", 921 | "my_set = {1, 3, 4, 5, 6}\n", 922 | "print(my_set)\n", 923 | "\n", 924 | "# discard an element\n", 925 | "my_set.discard(4)\n", 926 | "print(my_set)\n", 927 | "\n", 928 | "# remove an element\n", 929 | "my_set.remove(6)\n", 930 | "print(my_set)\n", 931 | "\n", 932 | "# discard an element\n", 933 | "# not present in my_set\n", 934 | "my_set.discard(2)\n", 935 | "print(my_set)\n", 936 | "\n", 937 | "# remove an element not present in my_set you will get an error Output: KeyError: 2\n", 938 | "\n", 939 | "# my_set.remove(2)" 940 | ] 941 | }, 942 | { 943 | "cell_type": "markdown", 944 | "metadata": {}, 945 | "source": [ 946 | "## Global and Local Variables in Python\n", 947 | "* Global variables are the one that are defined and declared outside a function and we need to use them inside a function." 948 | ] 949 | }, 950 | { 951 | "cell_type": "code", 952 | "execution_count": null, 953 | "metadata": {}, 954 | "outputs": [], 955 | "source": [ 956 | "# This function uses global variable s \n", 957 | "def f():\n", 958 | " print(s) \n", 959 | "\n", 960 | "# Global scope \n", 961 | "s = \"State Street\"\n", 962 | "f()" 963 | ] 964 | }, 965 | { 966 | "cell_type": "markdown", 967 | "metadata": {}, 968 | "source": [ 969 | "#### If a variable with same name is defined inside the scope of function as well then it will print the value given inside the function only and not the global value." 970 | ] 971 | }, 972 | { 973 | "cell_type": "code", 974 | "execution_count": null, 975 | "metadata": {}, 976 | "outputs": [], 977 | "source": [ 978 | "# This function has a variable with name same as s. \n", 979 | "def f(): \n", 980 | " s = \"Bellandur\"\n", 981 | " print(s) \n", 982 | " \n", 983 | "# Global scope \n", 984 | "s = \"State Street\" \n", 985 | "f()\n", 986 | "print(s)" 987 | ] 988 | }, 989 | { 990 | "cell_type": "code", 991 | "execution_count": null, 992 | "metadata": {}, 993 | "outputs": [], 994 | "source": [ 995 | "def f(): \n", 996 | " print(s) \n", 997 | " s = \"State Street\"\n", 998 | "\n", 999 | " \n", 1000 | "# Global scope \n", 1001 | "s = \"Bellandur\"\n", 1002 | "f() \n", 1003 | "print(s)" 1004 | ] 1005 | }, 1006 | { 1007 | "cell_type": "code", 1008 | "execution_count": null, 1009 | "metadata": {}, 1010 | "outputs": [], 1011 | "source": [ 1012 | "a = 1 # a global Variable\n", 1013 | " \n", 1014 | "# Uses global because there is no local 'a' \n", 1015 | "def f(): \n", 1016 | " print ('Inside f() : ', a)\n", 1017 | " \n", 1018 | "# Variable 'a' is redefined as a local \n", 1019 | "def g(): \n", 1020 | " a = 2\n", 1021 | " print ('Inside g() : ',a)\n", 1022 | " \n", 1023 | "# Uses global keyword to modify global 'a' \n", 1024 | "def h(): \n", 1025 | " global a \n", 1026 | " a = 3\n", 1027 | " print ('Inside h() : ',a)\n", 1028 | " \n", 1029 | "# Global scope \n", 1030 | "print ('global : ',a)\n", 1031 | "f() \n", 1032 | "print ('global : ',a)\n", 1033 | "g() \n", 1034 | "print ('global : ',a)\n", 1035 | "h() \n", 1036 | "print ('global : ',a) \n", 1037 | "print('\\nThe new value of a is', a)" 1038 | ] 1039 | } 1040 | ], 1041 | "metadata": { 1042 | "kernelspec": { 1043 | "display_name": "Python 3", 1044 | "language": "python", 1045 | "name": "python3" 1046 | }, 1047 | "language_info": { 1048 | "codemirror_mode": { 1049 | "name": "ipython", 1050 | "version": 3 1051 | }, 1052 | "file_extension": ".py", 1053 | "mimetype": "text/x-python", 1054 | "name": "python", 1055 | "nbconvert_exporter": "python", 1056 | "pygments_lexer": "ipython3", 1057 | "version": "3.7.4" 1058 | } 1059 | }, 1060 | "nbformat": 4, 1061 | "nbformat_minor": 2 1062 | } 1063 | -------------------------------------------------------------------------------- /3. While, Modules and assert.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "## Python While Loops\n", 8 | "\n", 9 | "* In Python, While Loops is used to execute a block of statements repeatedly until a given condition is satisfied.\n", 10 | "* And when the condition becomes false, the line immediately after the loop in the program is executed. \n", 11 | "* While loop falls under the category of indefinite iteration.\n", 12 | "* Indefinite iteration means that the number of times the loop is executed isn’t specified explicitly in advance.\n", 13 | "\n", 14 | "" 15 | ] 16 | }, 17 | { 18 | "cell_type": "code", 19 | "execution_count": null, 20 | "metadata": {}, 21 | "outputs": [], 22 | "source": [ 23 | "# While Loops\n", 24 | "\n", 25 | "temp = 0 \n", 26 | "while temp!=-1000:\n", 27 | " temp = eval(input('Enter a temperature (-1000 to quit): ')) \n", 28 | " print('In Fahrenheit that is', 9/5*temp+32)\n", 29 | "print('The loop is over now')" 30 | ] 31 | }, 32 | { 33 | "cell_type": "code", 34 | "execution_count": null, 35 | "metadata": {}, 36 | "outputs": [], 37 | "source": [ 38 | "i = 0\n", 39 | "while i !=10:\n", 40 | " i+= 1\n", 41 | " print(i) " 42 | ] 43 | }, 44 | { 45 | "cell_type": "code", 46 | "execution_count": null, 47 | "metadata": {}, 48 | "outputs": [], 49 | "source": [ 50 | "i = 0\n", 51 | "while i!=10:\n", 52 | " print(i)\n", 53 | " i+= 1" 54 | ] 55 | }, 56 | { 57 | "cell_type": "code", 58 | "execution_count": null, 59 | "metadata": {}, 60 | "outputs": [], 61 | "source": [ 62 | "for i in range(10):\n", 63 | " print(i)" 64 | ] 65 | }, 66 | { 67 | "cell_type": "code", 68 | "execution_count": null, 69 | "metadata": {}, 70 | "outputs": [], 71 | "source": [ 72 | "temp = 0 \n", 73 | "while temp!=-1000:\n", 74 | " temp = eval(input('Enter a temperature (-1000 to quit): ')) \n", 75 | " if temp!=-1000:\n", 76 | " print('In Fahrenheit that is', 9/5*temp+32)\n", 77 | " else:\n", 78 | " print('Bye!')" 79 | ] 80 | }, 81 | { 82 | "cell_type": "code", 83 | "execution_count": null, 84 | "metadata": {}, 85 | "outputs": [], 86 | "source": [ 87 | "from random import randint \n", 88 | "secret_num = randint(1,5) \n", 89 | "guess = 0 \n", 90 | "while guess != secret_num:\n", 91 | " guess = eval(input('Guess the secret number: '))\n", 92 | "print('You finally got it!')" 93 | ] 94 | }, 95 | { 96 | "cell_type": "code", 97 | "execution_count": null, 98 | "metadata": {}, 99 | "outputs": [], 100 | "source": [ 101 | "for i in range(10):\n", 102 | " print(i)" 103 | ] 104 | }, 105 | { 106 | "cell_type": "code", 107 | "execution_count": null, 108 | "metadata": {}, 109 | "outputs": [], 110 | "source": [ 111 | "i = 0\n", 112 | "while i < 10:\n", 113 | " print(i)\n", 114 | " i = i + 1" 115 | ] 116 | }, 117 | { 118 | "cell_type": "code", 119 | "execution_count": null, 120 | "metadata": {}, 121 | "outputs": [], 122 | "source": [ 123 | "temp = eval(input('Enter a temperature in Celsius: '))\n", 124 | "if temp<-273.15:\n", 125 | " print('That temperature is not possible.')\n", 126 | "else:\n", 127 | " print('In Fahrenheit, that is', 9/5*temp+32)" 128 | ] 129 | }, 130 | { 131 | "cell_type": "code", 132 | "execution_count": null, 133 | "metadata": {}, 134 | "outputs": [], 135 | "source": [ 136 | "temp = eval(input('Enter a temperature in Celsius: ')) \n", 137 | "while temp<-273.15: \n", 138 | " temp = eval(input('Impossible. Enter a valid temperature: ')) \n", 139 | "print('In Fahrenheit, that is', 9/5*temp+32)" 140 | ] 141 | }, 142 | { 143 | "cell_type": "code", 144 | "execution_count": null, 145 | "metadata": {}, 146 | "outputs": [], 147 | "source": [ 148 | "i = 0 \n", 149 | "while i<20: \n", 150 | " print(i, end = ' ') \n", 151 | " i=i+2 \n", 152 | "print('Bye!')" 153 | ] 154 | }, 155 | { 156 | "cell_type": "code", 157 | "execution_count": null, 158 | "metadata": {}, 159 | "outputs": [], 160 | "source": [ 161 | "# Infinte Loops\n", 162 | "i=0 \n", 163 | "while i<10: \n", 164 | " print(i)" 165 | ] 166 | }, 167 | { 168 | "cell_type": "markdown", 169 | "metadata": {}, 170 | "source": [ 171 | "## Break statement\n", 172 | "\n", 173 | "* The break statement is used to terminate the loop or statement in which it is present. \n", 174 | "* After that, the control will pass to the statements that are present after the break statement, if available. \n", 175 | "* If the break statement is present in the nested loop, then it terminates only those loops which contains break statement.\n", 176 | "\n", 177 | "" 178 | ] 179 | }, 180 | { 181 | "cell_type": "code", 182 | "execution_count": null, 183 | "metadata": {}, 184 | "outputs": [], 185 | "source": [ 186 | "# The break statement\n", 187 | "\n", 188 | "for i in range(10):\n", 189 | " num = eval(input('Enter number: ')) \n", 190 | " if num<0: \n", 191 | " break" 192 | ] 193 | }, 194 | { 195 | "cell_type": "code", 196 | "execution_count": null, 197 | "metadata": {}, 198 | "outputs": [], 199 | "source": [ 200 | "# Same in While Loop\n", 201 | "\n", 202 | "i=0 \n", 203 | "num=1 \n", 204 | "while i<10 and num>0: \n", 205 | " num = eval(input('Enter a number: '))" 206 | ] 207 | }, 208 | { 209 | "cell_type": "code", 210 | "execution_count": null, 211 | "metadata": {}, 212 | "outputs": [], 213 | "source": [ 214 | "temp = 0 \n", 215 | "while temp!=-1000: \n", 216 | " temp = eval(input('Please give a temp: '))\n", 217 | " if temp!=-1000:\n", 218 | " print(9/5*temp+32)\n", 219 | " else:\n", 220 | " print('Bye!')" 221 | ] 222 | }, 223 | { 224 | "cell_type": "code", 225 | "execution_count": null, 226 | "metadata": {}, 227 | "outputs": [], 228 | "source": [ 229 | "while True:\n", 230 | " temp = eval(input('Please give a temp: ')) \n", 231 | " if temp==-1000:\n", 232 | " print('Bye')\n", 233 | " break\n", 234 | " print(9/5*temp+32) " 235 | ] 236 | }, 237 | { 238 | "cell_type": "code", 239 | "execution_count": null, 240 | "metadata": {}, 241 | "outputs": [], 242 | "source": [ 243 | "# Using Else with For Loop\n", 244 | "\n", 245 | "for i in range(10): \n", 246 | " num = eval(input('Enter number: ')) \n", 247 | " if num<0: \n", 248 | " print('Stopped early') \n", 249 | " break \n", 250 | " else:\n", 251 | " print(num*num)\n", 252 | "else:\n", 253 | " print('User entered all ten values')" 254 | ] 255 | }, 256 | { 257 | "cell_type": "code", 258 | "execution_count": null, 259 | "metadata": {}, 260 | "outputs": [], 261 | "source": [ 262 | "# to check if an integer num is prime\n", 263 | "\n", 264 | "num = eval(input('Please enter a number to see if the given input is Prime or not: '))\n", 265 | "for i in range(2, num): \n", 266 | " if num%i==0:\n", 267 | " print('Not prime')\n", 268 | " break\n", 269 | "else: \n", 270 | " print('Prime')" 271 | ] 272 | }, 273 | { 274 | "cell_type": "code", 275 | "execution_count": null, 276 | "metadata": {}, 277 | "outputs": [], 278 | "source": [ 279 | "num = eval(input('Please enter a number to see if the given input is Prime or not: '))\n", 280 | "i = 2\n", 281 | "while i secret_num: \n", 324 | " print('LOWER.', 5-num_guesses, 'guesses left.\\n') \n", 325 | " else:\n", 326 | " print('You got it!')\n", 327 | "\n", 328 | "if num_guesses==5 and guess != secret_num: \n", 329 | " print('You lose. The correct number is', secret_num)" 330 | ] 331 | }, 332 | { 333 | "cell_type": "code", 334 | "execution_count": null, 335 | "metadata": {}, 336 | "outputs": [], 337 | "source": [ 338 | "for num_guesses in range(5):\n", 339 | " guess = eval(input('Enter your guess (1-100): ')) \n", 340 | " if guess < secret_num: \n", 341 | " print('HIGHER.', 5-num_guesses, 'guesses left.\\n') \n", 342 | " elif guess > secret_num: \n", 343 | " print('LOWER.', 5-num_guesses, 'guesses left.\\n') \n", 344 | " else: \n", 345 | " print('You got it!') \n", 346 | " break \n", 347 | "else:\n", 348 | " print('You lose. The correct number is', secret_num)" 349 | ] 350 | }, 351 | { 352 | "cell_type": "code", 353 | "execution_count": null, 354 | "metadata": {}, 355 | "outputs": [], 356 | "source": [ 357 | "# Exercises\n", 358 | "\n", 359 | "#1 Print 2, 5, 8, 11, 14, 17, 20 with a while loop.\n", 360 | "\n", 361 | "i = 2\n", 362 | "while i < 21:\n", 363 | " print(i, end =' ')\n", 364 | " i = i + 3" 365 | ] 366 | }, 367 | { 368 | "cell_type": "code", 369 | "execution_count": null, 370 | "metadata": {}, 371 | "outputs": [], 372 | "source": [ 373 | "#2 Print 100, 99, 98, ... 1 with a while loop.\n", 374 | "\n", 375 | "i = 100\n", 376 | "while i != 0:\n", 377 | " print(i, end =' ')\n", 378 | " i= i - 1" 379 | ] 380 | }, 381 | { 382 | "cell_type": "code", 383 | "execution_count": null, 384 | "metadata": {}, 385 | "outputs": [], 386 | "source": [ 387 | "#3 User enters numbers until a negative. Then sum is printed, excluding negative.\n", 388 | "\n", 389 | "num = 0\n", 390 | "total = 0\n", 391 | "while num >= 0:\n", 392 | " num = eval(input('Please enter a Positive number, (enter a negative number to break): '))\n", 393 | " if num >=0:\n", 394 | " total = num + total\n", 395 | "print(total)" 396 | ] 397 | }, 398 | { 399 | "cell_type": "code", 400 | "execution_count": null, 401 | "metadata": {}, 402 | "outputs": [], 403 | "source": [ 404 | "#4 User enters numbers from 1 to 10, stopping with a 5. Print out how many numbers and whether a 3 was entered.\n", 405 | "num = 0\n", 406 | "count = 0\n", 407 | "flag = False\n", 408 | "while num != 5:\n", 409 | " num = eval(input('Enter a number (5 to stop): '))\n", 410 | " count += 1\n", 411 | " if num == 3:\n", 412 | " flag = True\n", 413 | "print('The number of numbers given is:', count)\n", 414 | "\n", 415 | "if flag:\n", 416 | " print('Yes, A 3 has been entered')\n", 417 | "else:\n", 418 | " print('No, A 3 has not been entered')" 419 | ] 420 | }, 421 | { 422 | "cell_type": "markdown", 423 | "metadata": {}, 424 | "source": [ 425 | "## Continue statement\n", 426 | "* Continue is also a loop control statement just like the break statement. \n", 427 | "* continue statement is opposite to that of break statement, instead of terminating the loop, it forces to execute the \n", 428 | "next iteration of the loop.\n", 429 | "* As the name suggests the continue statement forces the loop to continue or execute the next iteration. \n", 430 | "* When the continue statement is executed in the loop, the code inside the loop following the \n", 431 | "continue statement will be skipped and the next iteration of the loop will begin.\n", 432 | "\n", 433 | "" 434 | ] 435 | }, 436 | { 437 | "cell_type": "code", 438 | "execution_count": null, 439 | "metadata": {}, 440 | "outputs": [], 441 | "source": [ 442 | "# loop from 1 to 10 - Continue Statement\n", 443 | "for i in range(1, 11): \n", 444 | " if i == 6: \n", 445 | " continue\n", 446 | " else:\n", 447 | " print(i, end = \" \")" 448 | ] 449 | }, 450 | { 451 | "cell_type": "code", 452 | "execution_count": null, 453 | "metadata": {}, 454 | "outputs": [], 455 | "source": [ 456 | "for letter in 'Python':\n", 457 | " if letter == 'h':\n", 458 | " continue\n", 459 | " print ('Current Letter :', letter)" 460 | ] 461 | }, 462 | { 463 | "cell_type": "code", 464 | "execution_count": null, 465 | "metadata": {}, 466 | "outputs": [], 467 | "source": [ 468 | "var = 10\n", 469 | "while var > 0: \n", 470 | " var = var -1\n", 471 | " if var == 5:\n", 472 | " continue\n", 473 | " print ('Current variable value :', var)\n", 474 | "print(\"Good bye!\")" 475 | ] 476 | }, 477 | { 478 | "cell_type": "code", 479 | "execution_count": null, 480 | "metadata": {}, 481 | "outputs": [], 482 | "source": [ 483 | "# program to display only odd numbers\n", 484 | "for num in [20, 11, 9, 66, 4, 89, 44]:\n", 485 | " if num%2 == 0:\n", 486 | " continue\n", 487 | " print(num, end =' ')" 488 | ] 489 | }, 490 | { 491 | "cell_type": "markdown", 492 | "metadata": {}, 493 | "source": [ 494 | "## Pass Statements\n", 495 | "* As the name suggests pass statement simply does nothing. \n", 496 | "* The pass statement in Python is used when a statement is required syntactically but you do not want any \n", 497 | "command or code to execute. It is like null operation, as nothing will happen is it is executed. \n", 498 | "* Pass statement can also be used for writing empty loops. \n", 499 | "* Pass is also used for empty control statement, function and classes." 500 | ] 501 | }, 502 | { 503 | "cell_type": "code", 504 | "execution_count": null, 505 | "metadata": {}, 506 | "outputs": [], 507 | "source": [ 508 | "# Pass Statements\n", 509 | "\n", 510 | "for letter in 'Python': \n", 511 | " if letter == 'h':\n", 512 | " pass\n", 513 | " print('This is pass block')\n", 514 | " print('Current Letter :', letter)\n", 515 | "\n", 516 | "print(\"Good bye!\")" 517 | ] 518 | }, 519 | { 520 | "cell_type": "markdown", 521 | "metadata": {}, 522 | "source": [ 523 | "## Python | assert keyword\n", 524 | "\n", 525 | "* Assertions in any programming language are the debugging tools which help in smooth flow of code.\n", 526 | "* Assertions are mainly assumptions that a programmer knows always wants to be true and hence puts them in code so \n", 527 | "that failure of them doesn’t allow the code to execute further.\n", 528 | "\n", 529 | "* In python assert keyword helps in achieving this task. \n", 530 | "* This statement simply takes input a boolean condition, which when returns true doesn’t return anything, but if it is \n", 531 | "computed to be false, then it raises an AssertionError along with the optional message provided." 532 | ] 533 | }, 534 | { 535 | "cell_type": "code", 536 | "execution_count": null, 537 | "metadata": {}, 538 | "outputs": [], 539 | "source": [ 540 | "# Assert\n", 541 | "\n", 542 | "x = \"hello\"\n", 543 | "\n", 544 | "#if condition returns True, then nothing happens:\n", 545 | "assert x == \"hello\"\n", 546 | "\n", 547 | "#if condition returns False, AssertionError is raised:\n", 548 | "assert x == \"goodbye\"" 549 | ] 550 | }, 551 | { 552 | "cell_type": "code", 553 | "execution_count": null, 554 | "metadata": {}, 555 | "outputs": [], 556 | "source": [ 557 | "x = \"hello\"\n", 558 | "\n", 559 | "#if condition returns False, AssertionError is raised:\n", 560 | "assert x == \"goodbye\", \"X should be 'hello'\"" 561 | ] 562 | }, 563 | { 564 | "cell_type": "code", 565 | "execution_count": null, 566 | "metadata": {}, 567 | "outputs": [], 568 | "source": [ 569 | "x = input('Please enter the right string: ')\n", 570 | "guess = input('Please guess a right string: ')\n", 571 | "\n", 572 | "#if condition returns False, AssertionError is raised:\n", 573 | "assert x == \"goodbye\", \"X should be {}\".format(x)" 574 | ] 575 | }, 576 | { 577 | "cell_type": "markdown", 578 | "metadata": {}, 579 | "source": [ 580 | "## Lamda Function\n", 581 | "\n", 582 | "* As we already know that def keyword is used to define the normal functions \n", 583 | "and the lambda keyword is used to create anonymous functions. It has the following syntax:\n", 584 | "\n", 585 | "### lambda arguments:\n", 586 | "* This function can have any number of arguments but only one expression, which is evaluated and returned.\n", 587 | " * One is free to use lambda functions wherever function objects are required.\n", 588 | " * You need to keep in your knowledge that lambda functions are syntactically restricted to a single expression.\n", 589 | " * It has various uses in particular fields of programming besides other types of expressions in functions.\n", 590 | " \n", 591 | "### Use of lambda() with filter()\n", 592 | "\n", 593 | "* The filter() function in Python takes in a function and a list as arguments.\n", 594 | "* This offers an elegant way to filter out all the elements of a sequence “sequence”, for which the function returns True. \n", 595 | "\n", 596 | "### Use of lambda() with map()\n", 597 | "\n", 598 | "* The map() function in Python takes in a function and a list as argument. \n", 599 | "* The function is called with a lambda function and a list and a new list is returned which contains all the \n", 600 | "lambda modified items returned by that function for each item.\n", 601 | "\n", 602 | "### Use of lambda() with reduce()\n", 603 | "\n", 604 | "* The reduce() function in Python takes in a function and a list as argument. \n", 605 | "* The function is called with a lambda function and a list and a new reduced result is returned. \n", 606 | "* This performs a repetitive operation over the pairs of the list. " 607 | ] 608 | }, 609 | { 610 | "cell_type": "code", 611 | "execution_count": null, 612 | "metadata": {}, 613 | "outputs": [], 614 | "source": [ 615 | "# Lambda Function\n", 616 | "\n", 617 | "adder = lambda x, y: x + y\n", 618 | "print (adder (1, 2))" 619 | ] 620 | }, 621 | { 622 | "cell_type": "code", 623 | "execution_count": null, 624 | "metadata": {}, 625 | "outputs": [], 626 | "source": [ 627 | "x = lambda x,y : x + y\n", 628 | "print(x(5,10))" 629 | ] 630 | }, 631 | { 632 | "cell_type": "code", 633 | "execution_count": null, 634 | "metadata": {}, 635 | "outputs": [], 636 | "source": [ 637 | "x = lambda a, b, c : a + b + c\n", 638 | "print(x(5, 6, 2))" 639 | ] 640 | }, 641 | { 642 | "cell_type": "code", 643 | "execution_count": null, 644 | "metadata": {}, 645 | "outputs": [], 646 | "source": [ 647 | "(lambda x: x + 1)(2)" 648 | ] 649 | }, 650 | { 651 | "cell_type": "code", 652 | "execution_count": null, 653 | "metadata": {}, 654 | "outputs": [], 655 | "source": [ 656 | "def myfunc(n):\n", 657 | " return lambda a : a * n" 658 | ] 659 | }, 660 | { 661 | "cell_type": "code", 662 | "execution_count": null, 663 | "metadata": {}, 664 | "outputs": [], 665 | "source": [ 666 | "def myfunc(n):\n", 667 | " return lambda a : a * n\n", 668 | "\n", 669 | "mydoubler = myfunc(2)\n", 670 | "\n", 671 | "print(mydoubler(22))" 672 | ] 673 | }, 674 | { 675 | "cell_type": "code", 676 | "execution_count": null, 677 | "metadata": {}, 678 | "outputs": [], 679 | "source": [ 680 | "def myfunc(n):\n", 681 | " return lambda a : a * n\n", 682 | "\n", 683 | "mydoubler = myfunc(2)\n", 684 | "mytripler = myfunc(3)\n", 685 | "\n", 686 | "print(mydoubler(11))\n", 687 | "print(mytripler(11))" 688 | ] 689 | }, 690 | { 691 | "cell_type": "code", 692 | "execution_count": null, 693 | "metadata": {}, 694 | "outputs": [], 695 | "source": [ 696 | "# Lambda with a Filter\n", 697 | "\n", 698 | "sequences = [10,2,8,7,5,4,3,11,0, 1]\n", 699 | "filtered_result = filter (lambda x: x > 4, sequences) \n", 700 | "print(list(filtered_result))" 701 | ] 702 | }, 703 | { 704 | "cell_type": "code", 705 | "execution_count": null, 706 | "metadata": {}, 707 | "outputs": [], 708 | "source": [ 709 | "my_list = [1, 5, 4, 6, 8, 11, 3, 12]\n", 710 | "\n", 711 | "new_list = list(filter(lambda x: (x%2 == 0) , my_list))\n", 712 | "\n", 713 | "print(new_list)" 714 | ] 715 | }, 716 | { 717 | "cell_type": "code", 718 | "execution_count": null, 719 | "metadata": {}, 720 | "outputs": [], 721 | "source": [ 722 | "sequences = 10,15\n", 723 | "filtered_result = (lambda x: x*x)(sequences)\n", 724 | "print(tuple(filtered_result))" 725 | ] 726 | }, 727 | { 728 | "cell_type": "code", 729 | "execution_count": null, 730 | "metadata": {}, 731 | "outputs": [], 732 | "source": [ 733 | "# lambdas in map()\n", 734 | "\n", 735 | "sequences = [10,2,8,7,5,4,3,11,0, 1]\n", 736 | "filtered_result = map (lambda x: x*x, sequences) \n", 737 | "print(list(filtered_result))" 738 | ] 739 | }, 740 | { 741 | "cell_type": "code", 742 | "execution_count": 6, 743 | "metadata": {}, 744 | "outputs": [ 745 | { 746 | "name": "stdout", 747 | "output_type": "stream", 748 | "text": [ 749 | "193\n" 750 | ] 751 | } 752 | ], 753 | "source": [ 754 | "# Python code to illustrate \n", 755 | "# reduce() with lambda() \n", 756 | "# to get sum of a list \n", 757 | "from functools import reduce\n", 758 | "li = [5, 8, 10, 20, 50, 100] \n", 759 | "sum = reduce((lambda x, y: x + y), li) \n", 760 | "print (sum)" 761 | ] 762 | }, 763 | { 764 | "cell_type": "markdown", 765 | "metadata": {}, 766 | "source": [ 767 | "## Python Modules\n", 768 | "\n", 769 | "* A module is a file containing Python definitions and statements. \n", 770 | "* A module can define functions, classes and variables. A module can also include runnable code.\n", 771 | "* Grouping related code into a module makes the code easier to understand and use." 772 | ] 773 | }, 774 | { 775 | "cell_type": "code", 776 | "execution_count": null, 777 | "metadata": {}, 778 | "outputs": [], 779 | "source": [ 780 | "import Testmodule as tm" 781 | ] 782 | }, 783 | { 784 | "cell_type": "code", 785 | "execution_count": null, 786 | "metadata": {}, 787 | "outputs": [], 788 | "source": [ 789 | "print(tm.add(5,4))\n", 790 | "print(tm.mul(5,4))" 791 | ] 792 | }, 793 | { 794 | "cell_type": "code", 795 | "execution_count": null, 796 | "metadata": {}, 797 | "outputs": [], 798 | "source": [ 799 | "print(tm.greeting(\"Jonathan\"))" 800 | ] 801 | }, 802 | { 803 | "cell_type": "code", 804 | "execution_count": null, 805 | "metadata": {}, 806 | "outputs": [], 807 | "source": [ 808 | "a = tm.person1[\"age\"]\n", 809 | "print(a)" 810 | ] 811 | }, 812 | { 813 | "cell_type": "code", 814 | "execution_count": null, 815 | "metadata": {}, 816 | "outputs": [], 817 | "source": [ 818 | "# Using the dir function\n", 819 | "\n", 820 | "dir(Testmodule)" 821 | ] 822 | }, 823 | { 824 | "cell_type": "code", 825 | "execution_count": null, 826 | "metadata": {}, 827 | "outputs": [], 828 | "source": [ 829 | "# Important Standard Modules\n", 830 | "# OS Module\n", 831 | "# Creating a New Directory\n", 832 | "\n", 833 | "import os\n", 834 | "os.mkdir(\"c:\\\\tempdir\")" 835 | ] 836 | }, 837 | { 838 | "cell_type": "code", 839 | "execution_count": null, 840 | "metadata": {}, 841 | "outputs": [], 842 | "source": [ 843 | "# Changing the current working directory\n", 844 | "os.chdir(\"c:\\\\tempdir\")" 845 | ] 846 | }, 847 | { 848 | "cell_type": "code", 849 | "execution_count": null, 850 | "metadata": {}, 851 | "outputs": [], 852 | "source": [ 853 | "# to access the current working directory\n", 854 | "os.getcwd()" 855 | ] 856 | }, 857 | { 858 | "cell_type": "code", 859 | "execution_count": null, 860 | "metadata": {}, 861 | "outputs": [], 862 | "source": [ 863 | "# Other way of Changing to directory\n", 864 | "os.chdir(\"c:\\\\\")\n", 865 | "os.getcwd()\n", 866 | "os.chdir(\"tempdir\")\n", 867 | "os.getcwd()" 868 | ] 869 | }, 870 | { 871 | "cell_type": "code", 872 | "execution_count": null, 873 | "metadata": {}, 874 | "outputs": [], 875 | "source": [ 876 | "# Trying to remove the working directory\n", 877 | "os.rmdir(\"c:\\\\tempdir\")" 878 | ] 879 | }, 880 | { 881 | "cell_type": "code", 882 | "execution_count": null, 883 | "metadata": {}, 884 | "outputs": [], 885 | "source": [ 886 | "# Come back to the parent directory and remove any directory inside it\n", 887 | "os.chdir(\"..\")\n", 888 | "os.rmdir(\"tempdir\")" 889 | ] 890 | }, 891 | { 892 | "cell_type": "code", 893 | "execution_count": null, 894 | "metadata": {}, 895 | "outputs": [], 896 | "source": [ 897 | "os.listdir('Program Files')" 898 | ] 899 | }, 900 | { 901 | "cell_type": "code", 902 | "execution_count": null, 903 | "metadata": {}, 904 | "outputs": [], 905 | "source": [ 906 | "import sys\n", 907 | "sys.version" 908 | ] 909 | }, 910 | { 911 | "cell_type": "code", 912 | "execution_count": null, 913 | "metadata": {}, 914 | "outputs": [], 915 | "source": [ 916 | "sys.path" 917 | ] 918 | }, 919 | { 920 | "cell_type": "code", 921 | "execution_count": null, 922 | "metadata": {}, 923 | "outputs": [], 924 | "source": [ 925 | "import math\n", 926 | "math.pi" 927 | ] 928 | }, 929 | { 930 | "cell_type": "code", 931 | "execution_count": null, 932 | "metadata": {}, 933 | "outputs": [], 934 | "source": [ 935 | "math.e" 936 | ] 937 | }, 938 | { 939 | "cell_type": "code", 940 | "execution_count": null, 941 | "metadata": {}, 942 | "outputs": [], 943 | "source": [ 944 | "math.radians(30)" 945 | ] 946 | }, 947 | { 948 | "cell_type": "code", 949 | "execution_count": null, 950 | "metadata": {}, 951 | "outputs": [], 952 | "source": [ 953 | "math.degrees(math.pi/6)" 954 | ] 955 | }, 956 | { 957 | "cell_type": "code", 958 | "execution_count": null, 959 | "metadata": {}, 960 | "outputs": [], 961 | "source": [ 962 | "math.sin(0.5235987755982988)" 963 | ] 964 | }, 965 | { 966 | "cell_type": "code", 967 | "execution_count": null, 968 | "metadata": {}, 969 | "outputs": [], 970 | "source": [ 971 | "math.cos(0.5235987755982988)" 972 | ] 973 | }, 974 | { 975 | "cell_type": "code", 976 | "execution_count": null, 977 | "metadata": {}, 978 | "outputs": [], 979 | "source": [ 980 | "math.log(10)" 981 | ] 982 | }, 983 | { 984 | "cell_type": "code", 985 | "execution_count": null, 986 | "metadata": {}, 987 | "outputs": [], 988 | "source": [ 989 | "math.log10(10)" 990 | ] 991 | }, 992 | { 993 | "cell_type": "code", 994 | "execution_count": null, 995 | "metadata": {}, 996 | "outputs": [], 997 | "source": [ 998 | "math.exp(10)" 999 | ] 1000 | }, 1001 | { 1002 | "cell_type": "code", 1003 | "execution_count": null, 1004 | "metadata": {}, 1005 | "outputs": [], 1006 | "source": [ 1007 | "math.e**10" 1008 | ] 1009 | }, 1010 | { 1011 | "cell_type": "code", 1012 | "execution_count": null, 1013 | "metadata": {}, 1014 | "outputs": [], 1015 | "source": [ 1016 | "math.pow(2,4)" 1017 | ] 1018 | }, 1019 | { 1020 | "cell_type": "code", 1021 | "execution_count": null, 1022 | "metadata": {}, 1023 | "outputs": [], 1024 | "source": [ 1025 | "math.sqrt(100)" 1026 | ] 1027 | }, 1028 | { 1029 | "cell_type": "code", 1030 | "execution_count": null, 1031 | "metadata": {}, 1032 | "outputs": [], 1033 | "source": [ 1034 | "math.ceil(4.5867)" 1035 | ] 1036 | }, 1037 | { 1038 | "cell_type": "code", 1039 | "execution_count": null, 1040 | "metadata": {}, 1041 | "outputs": [], 1042 | "source": [ 1043 | "math.floor(4.5687)" 1044 | ] 1045 | }, 1046 | { 1047 | "cell_type": "code", 1048 | "execution_count": null, 1049 | "metadata": {}, 1050 | "outputs": [], 1051 | "source": [ 1052 | "import statistics\n", 1053 | "statistics.mean([2,5,6,9])" 1054 | ] 1055 | }, 1056 | { 1057 | "cell_type": "code", 1058 | "execution_count": null, 1059 | "metadata": {}, 1060 | "outputs": [], 1061 | "source": [ 1062 | "statistics.median([1,2,3,8,9])" 1063 | ] 1064 | }, 1065 | { 1066 | "cell_type": "code", 1067 | "execution_count": null, 1068 | "metadata": {}, 1069 | "outputs": [], 1070 | "source": [ 1071 | "statistics.mode([2,5,3,2,8,3,9,4,2,5,6])" 1072 | ] 1073 | }, 1074 | { 1075 | "cell_type": "code", 1076 | "execution_count": null, 1077 | "metadata": {}, 1078 | "outputs": [], 1079 | "source": [ 1080 | "statistics.stdev([1,1.5,2,2.5,3,3.5,4,4.5,5])" 1081 | ] 1082 | } 1083 | ], 1084 | "metadata": { 1085 | "kernelspec": { 1086 | "display_name": "Python 3", 1087 | "language": "python", 1088 | "name": "python3" 1089 | }, 1090 | "language_info": { 1091 | "codemirror_mode": { 1092 | "name": "ipython", 1093 | "version": 3 1094 | }, 1095 | "file_extension": ".py", 1096 | "mimetype": "text/x-python", 1097 | "name": "python", 1098 | "nbconvert_exporter": "python", 1099 | "pygments_lexer": "ipython3", 1100 | "version": "3.7.4" 1101 | } 1102 | }, 1103 | "nbformat": 4, 1104 | "nbformat_minor": 2 1105 | } 1106 | -------------------------------------------------------------------------------- /2. Data Types, Data Structures, Conditionals, Function and Operators.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": { 6 | "colab_type": "text", 7 | "id": "6R3fVGFhmAWQ" 8 | }, 9 | "source": [ 10 | "# Python basics - Data Types, Data Structures and Operators" 11 | ] 12 | }, 13 | { 14 | "cell_type": "markdown", 15 | "metadata": { 16 | "colab_type": "text", 17 | "id": "3PfdRGpGmAWS" 18 | }, 19 | "source": [ 20 | "#### Basic data types" 21 | ] 22 | }, 23 | { 24 | "cell_type": "markdown", 25 | "metadata": { 26 | "colab_type": "text", 27 | "id": "a694M29UmAWT" 28 | }, 29 | "source": [ 30 | "##### Numbers\n", 31 | "\n", 32 | "* Integers and floats work as you would expect from other languages:\n" 33 | ] 34 | }, 35 | { 36 | "cell_type": "code", 37 | "execution_count": null, 38 | "metadata": { 39 | "colab": { 40 | "autoexec": { 41 | "startup": false, 42 | "wait_interval": 0 43 | } 44 | }, 45 | "colab_type": "code", 46 | "id": "pUqj5vnjmAWW" 47 | }, 48 | "outputs": [], 49 | "source": [ 50 | "x = 4" 51 | ] 52 | }, 53 | { 54 | "cell_type": "code", 55 | "execution_count": null, 56 | "metadata": { 57 | "colab": { 58 | "autoexec": { 59 | "startup": false, 60 | "wait_interval": 0 61 | } 62 | }, 63 | "colab_type": "code", 64 | "id": "j4QX7CKImAWa", 65 | "outputId": "ee390b73-deb6-41ed-d483-14770db539a4" 66 | }, 67 | "outputs": [], 68 | "source": [ 69 | "print(x)\n", 70 | "type(x)" 71 | ] 72 | }, 73 | { 74 | "cell_type": "code", 75 | "execution_count": null, 76 | "metadata": { 77 | "colab": { 78 | "autoexec": { 79 | "startup": false, 80 | "wait_interval": 0 81 | } 82 | }, 83 | "colab_type": "code", 84 | "id": "HaSdR5hlmAWf", 85 | "outputId": "0298ca29-7b14-46da-ad68-a75a2b60eded" 86 | }, 87 | "outputs": [], 88 | "source": [ 89 | "print(type(x))" 90 | ] 91 | }, 92 | { 93 | "cell_type": "code", 94 | "execution_count": null, 95 | "metadata": { 96 | "colab": { 97 | "autoexec": { 98 | "startup": false, 99 | "wait_interval": 0 100 | } 101 | }, 102 | "colab_type": "code", 103 | "id": "J4XLsRRXmAWj", 104 | "outputId": "ab4a3ad2-5f17-47e9-82c7-947d1effc794" 105 | }, 106 | "outputs": [], 107 | "source": [ 108 | "print(x + 1) # Addition;\n", 109 | "print(x - 1) # Subtraction;\n", 110 | "print(x * 2) # Multiplication;\n", 111 | "print(x ** 2) # Exponentiation;" 112 | ] 113 | }, 114 | { 115 | "cell_type": "code", 116 | "execution_count": null, 117 | "metadata": { 118 | "colab": { 119 | "autoexec": { 120 | "startup": false, 121 | "wait_interval": 0 122 | } 123 | }, 124 | "colab_type": "code", 125 | "id": "c_XL0I_gmAWm", 126 | "outputId": "c23b84fe-d629-44bc-f037-c04dfb78e0da" 127 | }, 128 | "outputs": [], 129 | "source": [ 130 | "x += 1\n", 131 | "print(x)" 132 | ] 133 | }, 134 | { 135 | "cell_type": "code", 136 | "execution_count": null, 137 | "metadata": {}, 138 | "outputs": [], 139 | "source": [ 140 | "x // 2 # Floor Division" 141 | ] 142 | }, 143 | { 144 | "cell_type": "code", 145 | "execution_count": null, 146 | "metadata": { 147 | "colab": { 148 | "autoexec": { 149 | "startup": false, 150 | "wait_interval": 0 151 | } 152 | }, 153 | "colab_type": "code", 154 | "id": "yvi6iyYmmAWp" 155 | }, 156 | "outputs": [], 157 | "source": [ 158 | "x *= 2\n", 159 | "print(x)" 160 | ] 161 | }, 162 | { 163 | "cell_type": "code", 164 | "execution_count": null, 165 | "metadata": { 166 | "colab": { 167 | "autoexec": { 168 | "startup": false, 169 | "wait_interval": 0 170 | } 171 | }, 172 | "colab_type": "code", 173 | "id": "_7TdRWkimAWt", 174 | "outputId": "7c095d33-31f4-4ced-b238-cc6bc72d1492" 175 | }, 176 | "outputs": [], 177 | "source": [ 178 | "y = 2.5\n", 179 | "print(y)\n", 180 | "type(y) " 181 | ] 182 | }, 183 | { 184 | "cell_type": "code", 185 | "execution_count": null, 186 | "metadata": { 187 | "colab": { 188 | "autoexec": { 189 | "startup": false, 190 | "wait_interval": 0 191 | } 192 | }, 193 | "colab_type": "code", 194 | "id": "Prf2wHdVmAWw" 195 | }, 196 | "outputs": [], 197 | "source": [ 198 | "print(y + 1, y * 2, y ** 2) # Prints \"3.5 5.0 6.25\"" 199 | ] 200 | }, 201 | { 202 | "cell_type": "markdown", 203 | "metadata": { 204 | "colab_type": "text", 205 | "id": "Hu8lRFksmAWy" 206 | }, 207 | "source": [ 208 | "#### ACTIVITY:\n", 209 | "Create a variable called 'pi' and assign the float value 3.1415 to it. Print the value of pi." 210 | ] 211 | }, 212 | { 213 | "cell_type": "markdown", 214 | "metadata": { 215 | "colab_type": "text", 216 | "id": "XpMuDP09mAW4" 217 | }, 218 | "source": [ 219 | "##### Booleans\n", 220 | "* Python implements all of the usual operators for Boolean logic, but uses English words rather than symbols (`&&`, `||`, etc.):" 221 | ] 222 | }, 223 | { 224 | "cell_type": "code", 225 | "execution_count": null, 226 | "metadata": {}, 227 | "outputs": [], 228 | "source": [ 229 | "\"P\" == \"p\"" 230 | ] 231 | }, 232 | { 233 | "cell_type": "code", 234 | "execution_count": null, 235 | "metadata": { 236 | "colab": { 237 | "autoexec": { 238 | "startup": false, 239 | "wait_interval": 0 240 | } 241 | }, 242 | "colab_type": "code", 243 | "id": "T5MRPnFkmAW4", 244 | "outputId": "48dd7517-6dfc-4dd8-8560-eac03e76153e" 245 | }, 246 | "outputs": [], 247 | "source": [ 248 | "t, f = True, False\n", 249 | "print(type(t))" 250 | ] 251 | }, 252 | { 253 | "cell_type": "code", 254 | "execution_count": null, 255 | "metadata": { 256 | "colab": { 257 | "autoexec": { 258 | "startup": false, 259 | "wait_interval": 0 260 | } 261 | }, 262 | "colab_type": "code", 263 | "id": "62_ipHVVmAW7", 264 | "outputId": "f2350727-8471-4e73-9f38-efe2e5b62ba8" 265 | }, 266 | "outputs": [], 267 | "source": [ 268 | "print(t and f) # Logical AND;)\n", 269 | "print(t or f) # Logical OR;)\n", 270 | "print(not t) # Logical NOT;)\n", 271 | "print(t != f) # Logical Not Equal to;)" 272 | ] 273 | }, 274 | { 275 | "cell_type": "code", 276 | "execution_count": null, 277 | "metadata": { 278 | "colab": { 279 | "autoexec": { 280 | "startup": false, 281 | "wait_interval": 0 282 | } 283 | }, 284 | "colab_type": "code", 285 | "id": "d9YgMPvwmAW_", 286 | "outputId": "90d1204e-fbb0-41a7-b9b6-290dcca0f5e8" 287 | }, 288 | "outputs": [], 289 | "source": [ 290 | "print(t & f) # Logical AND;\n", 291 | "print(t | f) # Logical OR;" 292 | ] 293 | }, 294 | { 295 | "cell_type": "markdown", 296 | "metadata": { 297 | "colab_type": "text", 298 | "id": "IIswMh3GmAXC" 299 | }, 300 | "source": [ 301 | "##### Strings" 302 | ] 303 | }, 304 | { 305 | "cell_type": "code", 306 | "execution_count": null, 307 | "metadata": { 308 | "colab": { 309 | "autoexec": { 310 | "startup": false, 311 | "wait_interval": 0 312 | } 313 | }, 314 | "colab_type": "code", 315 | "id": "GnpnZghRmAXD", 316 | "outputId": "3b9c3023-307a-4544-f6a0-f3fb785649ae" 317 | }, 318 | "outputs": [], 319 | "source": [ 320 | "hell = 'helloooooooo' # String literals can use single quotes\n", 321 | "war = \"world\" # or double quotes; it does not matter.\n", 322 | "print(war)\n", 323 | "len(hell)" 324 | ] 325 | }, 326 | { 327 | "cell_type": "code", 328 | "execution_count": null, 329 | "metadata": { 330 | "colab": { 331 | "autoexec": { 332 | "startup": false, 333 | "wait_interval": 0 334 | } 335 | }, 336 | "colab_type": "code", 337 | "id": "mWzq74qcmAXF", 338 | "outputId": "46e584d0-a96d-4ed2-c05d-f96f20d4704d" 339 | }, 340 | "outputs": [], 341 | "source": [ 342 | "hw = hell + \" \"+ war # String concatenation\n", 343 | "print(hw)" 344 | ] 345 | }, 346 | { 347 | "cell_type": "code", 348 | "execution_count": null, 349 | "metadata": {}, 350 | "outputs": [], 351 | "source": [ 352 | "x = 12.9\n", 353 | "int(x)" 354 | ] 355 | }, 356 | { 357 | "cell_type": "code", 358 | "execution_count": null, 359 | "metadata": { 360 | "colab": { 361 | "autoexec": { 362 | "startup": false, 363 | "wait_interval": 0 364 | } 365 | }, 366 | "colab_type": "code", 367 | "id": "6ZXlmZ-0mAXH", 368 | "outputId": "6e4bc2d7-7303-42f3-b853-c232034042cb", 369 | "scrolled": true 370 | }, 371 | "outputs": [], 372 | "source": [ 373 | "hw12 = '%s %s %d' % (hell, war, 12) # s printf style string formatting\n", 374 | "print(hw12)\n", 375 | "print(type(hw12))" 376 | ] 377 | }, 378 | { 379 | "cell_type": "markdown", 380 | "metadata": { 381 | "colab_type": "text", 382 | "id": "PSzy7sipmAXL" 383 | }, 384 | "source": [ 385 | "#### String objects have a bunch of useful methods; for example:" 386 | ] 387 | }, 388 | { 389 | "cell_type": "code", 390 | "execution_count": null, 391 | "metadata": { 392 | "colab": { 393 | "autoexec": { 394 | "startup": false, 395 | "wait_interval": 0 396 | } 397 | }, 398 | "colab_type": "code", 399 | "id": "cWRlW4i3mAXM", 400 | "outputId": "cbbd7ef0-4562-4297-ea7c-cd4590defdf6", 401 | "scrolled": true 402 | }, 403 | "outputs": [], 404 | "source": [ 405 | "s = \"hello\"\n", 406 | "print(s.capitalize()) # Capitalize a string\n", 407 | "print(s.upper()) # Convert a string to uppercase\n", 408 | "print(s.lower()) # Convert a string to Lowercase\n", 409 | "print(s.replace('l', '(ell)')) # Replace all instances of one substring with another;\n", 410 | "print(' world ') # Strip leading and trailing whitespace\n", 411 | "print(' world '.strip())" 412 | ] 413 | }, 414 | { 415 | "cell_type": "markdown", 416 | "metadata": { 417 | "colab_type": "text", 418 | "id": "Qr10z7kimAXO" 419 | }, 420 | "source": [ 421 | "#### ACTIVITY:\n", 422 | "Create a variable 'firstString' and assign the value 'I am' to it. Create another variable 'secondString' and assign the value 'from Besant Batch' to it. \n", 423 | "\n", 424 | "Create an integer variable 'batchNo' and assign the value 32 to it. Concatenate and print such that the result looks this:\n", 425 | "\"Hello there: I AM FROM Besant BATCH 32!!!\"" 426 | ] 427 | }, 428 | { 429 | "cell_type": "markdown", 430 | "metadata": { 431 | "colab_type": "text", 432 | "id": "9sZoGIxgmAXV" 433 | }, 434 | "source": [ 435 | "## Lists\n", 436 | "\n", 437 | "* Lists are just like the arrays, declared in other languages.\n", 438 | "* A single list may contain DataTypes like Integers, Strings, as well as Objects. Lists are mutable, and hence, they can be altered even after their creation.\n", 439 | "\n", 440 | "* List in Python are ordered and have a definite count. \n", 441 | "* The elements in a list are indexed according to a definite sequence and the indexing of a list is done with 0 being the first index. \n", 442 | "* Each element in the list has its definite place in the list, which allows duplicating of elements in the list, with each element having its own distinct place and credibility." 443 | ] 444 | }, 445 | { 446 | "cell_type": "code", 447 | "execution_count": null, 448 | "metadata": { 449 | "colab": { 450 | "autoexec": { 451 | "startup": false, 452 | "wait_interval": 0 453 | } 454 | }, 455 | "colab_type": "code", 456 | "id": "HxYlFRzqmAXV", 457 | "outputId": "7db7d2fd-b07a-440e-be55-a90fd584eddc" 458 | }, 459 | "outputs": [], 460 | "source": [ 461 | "xs = [3, 1, 2] # Create a list\n", 462 | "print(xs)\n", 463 | "print(xs[2])\n", 464 | "print(xs[-1], xs[-2], xs[-3]) # Negative indices count from the end of the list; prints \"2\"" 465 | ] 466 | }, 467 | { 468 | "cell_type": "code", 469 | "execution_count": null, 470 | "metadata": {}, 471 | "outputs": [], 472 | "source": [ 473 | "xs = 3,1,2\n", 474 | "xs" 475 | ] 476 | }, 477 | { 478 | "cell_type": "code", 479 | "execution_count": null, 480 | "metadata": {}, 481 | "outputs": [], 482 | "source": [ 483 | "List = [['State', 'Street'] , ['employees']] # Creating a Multi-Dimensional List # (By Nesting a list inside a List) \n", 484 | "print(List)" 485 | ] 486 | }, 487 | { 488 | "cell_type": "code", 489 | "execution_count": null, 490 | "metadata": {}, 491 | "outputs": [], 492 | "source": [ 493 | "List = [1, 2, 4, 4, 3, 3, 3, 6, 5] # Creating a List with the use of Numbers (Having duplicate values) \n", 494 | "print(List) \n", 495 | "\n", 496 | "\n", 497 | "List = [1, 2, 'State', 4, 'Street', 6, 'Employees', 5.25] # Creating a List with mixed type of values(Having numbers and strings) \n", 498 | "print(List) " 499 | ] 500 | }, 501 | { 502 | "cell_type": "code", 503 | "execution_count": null, 504 | "metadata": { 505 | "colab": { 506 | "autoexec": { 507 | "startup": false, 508 | "wait_interval": 0 509 | } 510 | }, 511 | "colab_type": "code", 512 | "id": "6hLw_lxOmAXb", 513 | "outputId": "01508aaf-97d3-4421-a51c-83f6c9cfdf3b" 514 | }, 515 | "outputs": [], 516 | "source": [ 517 | "xs[2] = 'foo' # Lists can contain elements of different types\n", 518 | "xs" 519 | ] 520 | }, 521 | { 522 | "cell_type": "code", 523 | "execution_count": null, 524 | "metadata": {}, 525 | "outputs": [], 526 | "source": [ 527 | "xs" 528 | ] 529 | }, 530 | { 531 | "cell_type": "code", 532 | "execution_count": null, 533 | "metadata": { 534 | "colab": { 535 | "autoexec": { 536 | "startup": false, 537 | "wait_interval": 0 538 | } 539 | }, 540 | "colab_type": "code", 541 | "id": "B1DkJx2MmAXe", 542 | "outputId": "0c57251e-a3bf-478e-8e3f-d63e797992eb" 543 | }, 544 | "outputs": [], 545 | "source": [ 546 | "xs.append('new') # Add a new element to the end of the list (Extend as well)\n", 547 | "xs" 548 | ] 549 | }, 550 | { 551 | "cell_type": "code", 552 | "execution_count": null, 553 | "metadata": { 554 | "colab": { 555 | "autoexec": { 556 | "startup": false, 557 | "wait_interval": 0 558 | } 559 | }, 560 | "colab_type": "code", 561 | "id": "Yx7IMEVZmAXi", 562 | "outputId": "1221fe36-c53e-4875-f95d-5808d3383c9e", 563 | "scrolled": true 564 | }, 565 | "outputs": [], 566 | "source": [ 567 | "x = xs.pop(2) # Remove and return the last element of the list\n", 568 | "print(x)\n", 569 | "print(xs)" 570 | ] 571 | }, 572 | { 573 | "cell_type": "code", 574 | "execution_count": null, 575 | "metadata": {}, 576 | "outputs": [], 577 | "source": [ 578 | "xs" 579 | ] 580 | }, 581 | { 582 | "cell_type": "code", 583 | "execution_count": null, 584 | "metadata": {}, 585 | "outputs": [], 586 | "source": [ 587 | "xs.insert(2,['new_2',12,'abc'])\n", 588 | "xs" 589 | ] 590 | }, 591 | { 592 | "cell_type": "code", 593 | "execution_count": null, 594 | "metadata": {}, 595 | "outputs": [], 596 | "source": [ 597 | "List = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] # Creating a List \n", 598 | "print(\"Intial List: \") \n", 599 | "print(List) \n", 600 | "\n", 601 | "List.remove(12) # Removing elements from List using Remove() method \n", 602 | "List.remove(6)\n", 603 | "print(List) " 604 | ] 605 | }, 606 | { 607 | "cell_type": "code", 608 | "execution_count": null, 609 | "metadata": {}, 610 | "outputs": [], 611 | "source": [ 612 | "list1 = [1, 2, 3, 4, 1, 1, 1, 4, 5] \n", 613 | " \n", 614 | "print(list1.index(4)) # Will print the index of '4' in list1 \n", 615 | " \n", 616 | "list2 = ['cat', 'bat', 'mat', 'cat', 'pet'] \n", 617 | "\n", 618 | "print(list2.index('cat')) # Will print the index of 'cat' in list2 " 619 | ] 620 | }, 621 | { 622 | "cell_type": "code", 623 | "execution_count": null, 624 | "metadata": {}, 625 | "outputs": [], 626 | "source": [ 627 | "lis2 = list1.copy() #to copy a list\n", 628 | "list1.sort() #to sort in ascending order\n", 629 | "list1.reverse() # to reverse the list \n", 630 | "del list1[2 : 5] # to delete elements from pos. 2 to 5\n", 631 | "list1.clear() # Clears all the elements in the list" 632 | ] 633 | }, 634 | { 635 | "cell_type": "code", 636 | "execution_count": null, 637 | "metadata": {}, 638 | "outputs": [], 639 | "source": [ 640 | "a = list1.clear()\n", 641 | "list1" 642 | ] 643 | }, 644 | { 645 | "cell_type": "markdown", 646 | "metadata": { 647 | "colab_type": "text", 648 | "id": "vi9N4z7FmAXl" 649 | }, 650 | "source": [ 651 | "#### ACTIVITY:\n", 652 | "Create a list 'myList' with the following elements in it: 'a', [1, 2, 3] and 'abc' to it. \n", 653 | "\n", 654 | "Add another element 'batch' to it. Extract out [1,2,3] from it. " 655 | ] 656 | }, 657 | { 658 | "cell_type": "markdown", 659 | "metadata": { 660 | "colab_type": "text", 661 | "id": "8mHEbinBmAXm" 662 | }, 663 | "source": [ 664 | "##### Slicing\n", 665 | "In addition to accessing list elements one at a time, Python provides concise syntax to access sublists; this is known as slicing:" 666 | ] 667 | }, 668 | { 669 | "cell_type": "code", 670 | "execution_count": null, 671 | "metadata": { 672 | "colab": { 673 | "autoexec": { 674 | "startup": false, 675 | "wait_interval": 0 676 | } 677 | }, 678 | "colab_type": "code", 679 | "id": "Lck6uqpUmAXn", 680 | "outputId": "da7e7dd6-c85f-46d3-ac97-fd2855ffbd80" 681 | }, 682 | "outputs": [], 683 | "source": [ 684 | "str_list = [\"a\",\"b\",\"c\",\"d\",\"e\",\"f\"]\n", 685 | "print(str_list)" 686 | ] 687 | }, 688 | { 689 | "cell_type": "code", 690 | "execution_count": null, 691 | "metadata": { 692 | "colab": { 693 | "autoexec": { 694 | "startup": false, 695 | "wait_interval": 0 696 | } 697 | }, 698 | "colab_type": "code", 699 | "id": "jXFOYtuhmAXs", 700 | "outputId": "ffc8a3ee-35aa-419d-b546-a63b942e09df" 701 | }, 702 | "outputs": [], 703 | "source": [ 704 | "print(str_list[1])\n", 705 | "print(str_list[-1])" 706 | ] 707 | }, 708 | { 709 | "cell_type": "code", 710 | "execution_count": null, 711 | "metadata": { 712 | "colab": { 713 | "autoexec": { 714 | "startup": false, 715 | "wait_interval": 0 716 | } 717 | }, 718 | "colab_type": "code", 719 | "id": "xEgoGm2rmAXv", 720 | "outputId": "ce3f4169-2964-463b-8221-fefeb3903015" 721 | }, 722 | "outputs": [], 723 | "source": [ 724 | "print(str_list[2:4]) # Get a slice from index 2 to 4 (exclusive)\n", 725 | "print(str_list[2:]) # Get a slice from index 2 to the end\n", 726 | "print(str_list[:2]) # Get a slice from the start to index 2 (exclusive)\n", 727 | "print(str_list[:]) # Get a slice of the whole list\n", 728 | "print(str_list[:-1]) # Slice indices can be negative" 729 | ] 730 | }, 731 | { 732 | "cell_type": "markdown", 733 | "metadata": { 734 | "colab_type": "text", 735 | "id": "gzUsCkQSmAX1" 736 | }, 737 | "source": [ 738 | "#### ACTIVITY:\n", 739 | "Create a list 'mySecondList' with the following elements in it: 'a', 'b', 23, True.\n", 740 | "\n", 741 | "Extract out the last element using reverse indexing. Change the element at index 1 to 'bat'. Print out the modified list" 742 | ] 743 | }, 744 | { 745 | "cell_type": "markdown", 746 | "metadata": { 747 | "colab": { 748 | "autoexec": { 749 | "startup": false, 750 | "wait_interval": 0 751 | } 752 | }, 753 | "colab_type": "code", 754 | "id": "uwxJmUT9mAX1" 755 | }, 756 | "source": [ 757 | "## if Statements \n", 758 | "\n", 759 | "* if statement is the most simple decision making statement. \n", 760 | "* It is used to decide whether a certain statement or block of statements will be executed or not i.e \n", 761 | "if a certain condition is true then a block of statement is executed otherwise not.\n", 762 | "\n", 763 | "" 764 | ] 765 | }, 766 | { 767 | "cell_type": "markdown", 768 | "metadata": {}, 769 | "source": [ 770 | "## if- else\n", 771 | "\n", 772 | "* The if statement alone tells us that if a condition is true it will execute a block of statements and if the condition is false it won’t. But what if we want to do something else if the condition is false. Here comes the else statement. \n", 773 | "* We can use the else statement with if statement to execute a block of code when the condition is false\n", 774 | "\n", 775 | "" 776 | ] 777 | }, 778 | { 779 | "cell_type": "markdown", 780 | "metadata": {}, 781 | "source": [ 782 | "## Nested If \n", 783 | "* A nested if is an if statement that is the target of another if statement. \n", 784 | "* Nested if statements means an if statement inside another if statement. \n", 785 | "* Yes, Python allows us to nest if statements within if statements. i.e, \n", 786 | "we can place an if statement inside another if statement.\n", 787 | "\n", 788 | "" 789 | ] 790 | }, 791 | { 792 | "cell_type": "markdown", 793 | "metadata": {}, 794 | "source": [ 795 | "## if-elif-else ladder\n", 796 | "\n", 797 | "* Here, a user can decide among multiple options. The if statements are executed from the top down.\n", 798 | "* As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and\n", 799 | "the rest of the ladder is bypassed. \n", 800 | "* If none of the conditions is true, then the final else statement will be executed.\n", 801 | "\n", 802 | "" 803 | ] 804 | }, 805 | { 806 | "cell_type": "code", 807 | "execution_count": null, 808 | "metadata": { 809 | "colab": { 810 | "autoexec": { 811 | "startup": false, 812 | "wait_interval": 0 813 | } 814 | }, 815 | "colab_type": "code", 816 | "id": "Y7_ES_JrmAX4", 817 | "outputId": "59500ab2-6093-4a8d-c3c4-6b3ece8e6032", 818 | "scrolled": true 819 | }, 820 | "outputs": [], 821 | "source": [ 822 | "x = int(input(\"Please enter an integer: \"))\n", 823 | "x" 824 | ] 825 | }, 826 | { 827 | "cell_type": "code", 828 | "execution_count": null, 829 | "metadata": { 830 | "colab": { 831 | "autoexec": { 832 | "startup": false, 833 | "wait_interval": 0 834 | } 835 | }, 836 | "colab_type": "code", 837 | "id": "6tYm0-AimAX7", 838 | "outputId": "410be1f5-36bf-45d9-c08d-a52554071102" 839 | }, 840 | "outputs": [], 841 | "source": [ 842 | "if x < 0:\n", 843 | " print('Negative value, X is : {}'.format(5))\n", 844 | "elif x == 0:\n", 845 | " print('Zero')\n", 846 | "elif x == 1:\n", 847 | " print('Single')\n", 848 | "else:\n", 849 | " print('more than 1')" 850 | ] 851 | }, 852 | { 853 | "cell_type": "markdown", 854 | "metadata": { 855 | "colab_type": "text", 856 | "id": "ItdHNCXdmAX-" 857 | }, 858 | "source": [ 859 | "#### ACTIVITY:\n", 860 | "Read in an integer number using raw_input. Using if-else statement, check if the number is even or odd. \n", 861 | "\n", 862 | "If even, print out \"Number is even\". If odd, print out \"Number is odd\" (HINT: Use % operator). What if number is 0?" 863 | ] 864 | }, 865 | { 866 | "cell_type": "code", 867 | "execution_count": null, 868 | "metadata": { 869 | "colab": { 870 | "autoexec": { 871 | "startup": false, 872 | "wait_interval": 0 873 | } 874 | }, 875 | "colab_type": "code", 876 | "id": "4lOeysHRmAX_" 877 | }, 878 | "outputs": [], 879 | "source": [ 880 | "x = int(input(\"Please enter an integer: \"))\n", 881 | "\n", 882 | "if x == 0:\n", 883 | " print('The Value Given is Zero, Kindly enter another Number')\n", 884 | "elif x %2 == 0:\n", 885 | " print('The Number provided is Even')\n", 886 | "else:\n", 887 | " print('The Number Given is Odd')" 888 | ] 889 | }, 890 | { 891 | "cell_type": "markdown", 892 | "metadata": { 893 | "colab_type": "text", 894 | "id": "dvTjew37mAYB" 895 | }, 896 | "source": [ 897 | "#### Loops\n", 898 | "You can loop over the elements of a list like this:" 899 | ] 900 | }, 901 | { 902 | "cell_type": "code", 903 | "execution_count": null, 904 | "metadata": { 905 | "colab": { 906 | "autoexec": { 907 | "startup": false, 908 | "wait_interval": 0 909 | } 910 | }, 911 | "colab_type": "code", 912 | "id": "RSfK_22vmAYC", 913 | "outputId": "c45ab61b-e444-4aaf-df91-3d622ce0c221", 914 | "scrolled": true 915 | }, 916 | "outputs": [], 917 | "source": [ 918 | "animals = ['cat', 'dog', 'monkey']\n", 919 | "# animals\n", 920 | "for i in animals:\n", 921 | " print(i)" 922 | ] 923 | }, 924 | { 925 | "cell_type": "code", 926 | "execution_count": null, 927 | "metadata": {}, 928 | "outputs": [], 929 | "source": [ 930 | "x = [-10,-5,0,1,2,3,4,5]\n", 931 | "for i in x:\n", 932 | " if i < 0:\n", 933 | " i = 5\n", 934 | " print('Negative value changed, Current X is : {}'.format(i))\n", 935 | " elif i == 0:\n", 936 | " print('Zero')\n", 937 | " elif i == 1:\n", 938 | " print('Single')\n", 939 | " else:\n", 940 | " print('more than 1')\n", 941 | "print(x)" 942 | ] 943 | }, 944 | { 945 | "cell_type": "markdown", 946 | "metadata": { 947 | "colab_type": "text", 948 | "id": "gj--TzromAYF" 949 | }, 950 | "source": [ 951 | "#### ACTIVITY:\n", 952 | "Using a for loop and range() function, print out all the odd numbers between 20-30." 953 | ] 954 | }, 955 | { 956 | "cell_type": "code", 957 | "execution_count": null, 958 | "metadata": { 959 | "colab": { 960 | "autoexec": { 961 | "startup": false, 962 | "wait_interval": 0 963 | } 964 | }, 965 | "colab_type": "code", 966 | "id": "e7iiBlUMmAYF" 967 | }, 968 | "outputs": [], 969 | "source": [ 970 | "for i in range(20,30):\n", 971 | " if i %2 ==1:\n", 972 | " print(i, end = ' ')" 973 | ] 974 | }, 975 | { 976 | "cell_type": "code", 977 | "execution_count": null, 978 | "metadata": {}, 979 | "outputs": [], 980 | "source": [ 981 | "raw = input('Please enter a string: ')\n", 982 | "vowels = 'AEIOUaeiou'\n", 983 | "count = 0\n", 984 | "for i in raw:\n", 985 | " if i in vowels:\n", 986 | " count+=1\n", 987 | "print(count)" 988 | ] 989 | }, 990 | { 991 | "cell_type": "markdown", 992 | "metadata": { 993 | "colab_type": "text", 994 | "id": "MCYLSvjNmAYH" 995 | }, 996 | "source": [ 997 | "#### ACTIVITY:\n", 998 | "Count the number of vowels in the string \"Hello Batch 32\"" 999 | ] 1000 | }, 1001 | { 1002 | "cell_type": "markdown", 1003 | "metadata": { 1004 | "colab_type": "text", 1005 | "id": "Q_NqL1VhmAYK" 1006 | }, 1007 | "source": [ 1008 | "## List comprehensions\n", 1009 | "* When programming, frequently we want to transform one type of data into another. \n", 1010 | "* As a simple example, consider the following code that computes square numbers:" 1011 | ] 1012 | }, 1013 | { 1014 | "cell_type": "code", 1015 | "execution_count": null, 1016 | "metadata": { 1017 | "colab": { 1018 | "autoexec": { 1019 | "startup": false, 1020 | "wait_interval": 0 1021 | } 1022 | }, 1023 | "colab_type": "code", 1024 | "id": "0tNuKBRfmAYL", 1025 | "outputId": "183d2300-4184-4f16-d81f-c680197306ba" 1026 | }, 1027 | "outputs": [], 1028 | "source": [ 1029 | "nums = [0, 1, 2, 3, 4]\n", 1030 | "squares = []\n", 1031 | "for x in nums:\n", 1032 | " squares.append(x ** 2)\n", 1033 | "print(squares)" 1034 | ] 1035 | }, 1036 | { 1037 | "cell_type": "markdown", 1038 | "metadata": { 1039 | "colab_type": "text", 1040 | "id": "9gVcLC-qmAYO" 1041 | }, 1042 | "source": [ 1043 | "You can make this code simpler using a list comprehension:" 1044 | ] 1045 | }, 1046 | { 1047 | "cell_type": "code", 1048 | "execution_count": null, 1049 | "metadata": { 1050 | "colab": { 1051 | "autoexec": { 1052 | "startup": false, 1053 | "wait_interval": 0 1054 | } 1055 | }, 1056 | "colab_type": "code", 1057 | "id": "gutXKIgemAYP", 1058 | "outputId": "7f462768-6ddb-4e14-d7a0-588c48bd2a6d" 1059 | }, 1060 | "outputs": [], 1061 | "source": [ 1062 | "nums = [0, 1, 2, 3, 4]\n", 1063 | "squares = [x ** 2 for x in nums]\n", 1064 | "squares" 1065 | ] 1066 | }, 1067 | { 1068 | "cell_type": "markdown", 1069 | "metadata": { 1070 | "colab_type": "text", 1071 | "id": "MiX82rpimAYR" 1072 | }, 1073 | "source": [ 1074 | "List comprehensions can also contain conditions:" 1075 | ] 1076 | }, 1077 | { 1078 | "cell_type": "code", 1079 | "execution_count": null, 1080 | "metadata": { 1081 | "colab": { 1082 | "autoexec": { 1083 | "startup": false, 1084 | "wait_interval": 0 1085 | } 1086 | }, 1087 | "colab_type": "code", 1088 | "id": "UR-WDw5KmAYR", 1089 | "outputId": "9e2dab4b-1185-44c1-90d4-4787011b0564" 1090 | }, 1091 | "outputs": [], 1092 | "source": [ 1093 | "nums = [0, 1, 2, 3, 4]\n", 1094 | "even_squares = [x ** 2 for x in nums if x % 2 == 0]\n", 1095 | "even_squares" 1096 | ] 1097 | }, 1098 | { 1099 | "cell_type": "markdown", 1100 | "metadata": { 1101 | "colab_type": "text", 1102 | "id": "hCk0wb0rmAYT" 1103 | }, 1104 | "source": [ 1105 | "#### ACTIVITY: \n", 1106 | "Create two variables: 'var1' with values 1-5 and 'var2' with values 10-20 in steps of 2 (i.e., 10,12,14,... etc). Using list comprehensions, print out result of (var1+var2) if (var1+var2) is a multiple of 3." 1107 | ] 1108 | }, 1109 | { 1110 | "cell_type": "code", 1111 | "execution_count": null, 1112 | "metadata": { 1113 | "colab": { 1114 | "autoexec": { 1115 | "startup": false, 1116 | "wait_interval": 0 1117 | } 1118 | }, 1119 | "colab_type": "code", 1120 | "id": "7nTBaXajmAYT" 1121 | }, 1122 | "outputs": [], 1123 | "source": [ 1124 | "var1 = [1, 2, 3, 4, 5]\n", 1125 | "var2 = [10,12,14,16,18,20]\n", 1126 | "var3 = var1 + var2\n", 1127 | "var3" 1128 | ] 1129 | }, 1130 | { 1131 | "cell_type": "code", 1132 | "execution_count": null, 1133 | "metadata": {}, 1134 | "outputs": [], 1135 | "source": [ 1136 | "print(var3)\n", 1137 | "output = [print(x) for x in var3 if x%3 ==0]\n", 1138 | "output" 1139 | ] 1140 | }, 1141 | { 1142 | "cell_type": "markdown", 1143 | "metadata": { 1144 | "colab_type": "text", 1145 | "id": "zF7t_2GkmAYV" 1146 | }, 1147 | "source": [ 1148 | "## Dictionaries\n", 1149 | "\n", 1150 | "* Dictionary in Python is an unordered collection of data values, used to store data values like a map, which unlike other Data \n", 1151 | "\n", 1152 | "* Types that hold only single value as an element Dictionary holds key:value pair. \n", 1153 | "\n", 1154 | "* Key value is provided in the dictionary to make it more optimized." 1155 | ] 1156 | }, 1157 | { 1158 | "cell_type": "code", 1159 | "execution_count": null, 1160 | "metadata": { 1161 | "colab": { 1162 | "autoexec": { 1163 | "startup": false, 1164 | "wait_interval": 0 1165 | } 1166 | }, 1167 | "colab_type": "code", 1168 | "id": "Ks5Har0DmAYV", 1169 | "outputId": "99fd7d1a-ff0c-4e09-ebd1-1fb2eb08cbdd" 1170 | }, 1171 | "outputs": [], 1172 | "source": [ 1173 | "Dict = {} # Creating an empty Dictionary \n", 1174 | "print(\"Empty Dictionary: \") \n", 1175 | "print(Dict) \n", 1176 | "\n", 1177 | "Dict = dict({1: 'State', 2: 'Street', 3:'Bellandur'}) # with dict() method \n", 1178 | "print(Dict) \n", 1179 | "\n", 1180 | "Dict = dict([(1, 'State'), (2, 'Street')]) # with each item as a Pair \n", 1181 | "print(Dict) " 1182 | ] 1183 | }, 1184 | { 1185 | "cell_type": "code", 1186 | "execution_count": null, 1187 | "metadata": {}, 1188 | "outputs": [], 1189 | "source": [ 1190 | "d = {'cat': 'cute', 'dog': 'furry'} # Create a new dictionary with some data\n", 1191 | "# print(d['cat']) # Get an entry from a dictionary; prints \"cute\"\n", 1192 | "print('rat' in d) # Check if a dictionary has a given key; prints \"True\"" 1193 | ] 1194 | }, 1195 | { 1196 | "cell_type": "code", 1197 | "execution_count": null, 1198 | "metadata": { 1199 | "colab": { 1200 | "autoexec": { 1201 | "startup": false, 1202 | "wait_interval": 0 1203 | } 1204 | }, 1205 | "colab_type": "code", 1206 | "id": "7onTyGXlmAYX", 1207 | "outputId": "b8d7d5f7-4138-4a48-de33-528ad1679daa" 1208 | }, 1209 | "outputs": [], 1210 | "source": [ 1211 | "d['fish'] = 'wet' # Set an entry in a dictionary\n", 1212 | "print(d['fish']) " 1213 | ] 1214 | }, 1215 | { 1216 | "cell_type": "code", 1217 | "execution_count": null, 1218 | "metadata": { 1219 | "colab": { 1220 | "autoexec": { 1221 | "startup": false, 1222 | "wait_interval": 0 1223 | } 1224 | }, 1225 | "colab_type": "code", 1226 | "id": "nVo3UI79mAYc", 1227 | "outputId": "a1aba035-3549-4c3d-8f70-56d4a9399c01" 1228 | }, 1229 | "outputs": [], 1230 | "source": [ 1231 | "print(d['monkey'])" 1232 | ] 1233 | }, 1234 | { 1235 | "cell_type": "code", 1236 | "execution_count": null, 1237 | "metadata": { 1238 | "colab": { 1239 | "autoexec": { 1240 | "startup": false, 1241 | "wait_interval": 0 1242 | } 1243 | }, 1244 | "colab_type": "code", 1245 | "id": "dduJZXyKmAYd", 1246 | "outputId": "fe5c8a95-c799-4327-dc0f-3ba34a9016c6" 1247 | }, 1248 | "outputs": [], 1249 | "source": [ 1250 | "print(d.get('monkey', 'N/A')) # Get an element with a default\n", 1251 | "print(d.get('fish', 'N/A')) # Get an element with a default" 1252 | ] 1253 | }, 1254 | { 1255 | "cell_type": "code", 1256 | "execution_count": null, 1257 | "metadata": { 1258 | "colab": { 1259 | "autoexec": { 1260 | "startup": false, 1261 | "wait_interval": 0 1262 | } 1263 | }, 1264 | "colab_type": "code", 1265 | "id": "TW4VWtC1mAYf", 1266 | "outputId": "93b3d3d5-ef30-4abb-b842-85851d7e4f5b" 1267 | }, 1268 | "outputs": [], 1269 | "source": [ 1270 | "del d['fish'] # Remove an element from a dictionary\n", 1271 | "print(d.get('fish', 'N/A')) # \"fish\" is no longer a key" 1272 | ] 1273 | }, 1274 | { 1275 | "cell_type": "code", 1276 | "execution_count": null, 1277 | "metadata": {}, 1278 | "outputs": [], 1279 | "source": [ 1280 | "# Creating a Nested Dictionary \n", 1281 | "Dict = {1: 'State', 2: 'For', 3:{'A' : 'Welcome', 'B' : 'To', 'C' : 'Bellandur'}} \n", 1282 | " \n", 1283 | "print(Dict)" 1284 | ] 1285 | }, 1286 | { 1287 | "cell_type": "code", 1288 | "execution_count": null, 1289 | "metadata": {}, 1290 | "outputs": [], 1291 | "source": [ 1292 | "Dict = {} # Creating an empty Dictionary \n", 1293 | "print(\"Empty Dictionary: \") \n", 1294 | "print(Dict) \n", 1295 | "\n", 1296 | "Dict[0] = 'State' # Adding elements one at a time \n", 1297 | "Dict[2] = 'For'\n", 1298 | "Dict[3] = 'Street'\n", 1299 | "print(\"Dictionary after adding 3 elements: \") \n", 1300 | "print(Dict)" 1301 | ] 1302 | }, 1303 | { 1304 | "cell_type": "code", 1305 | "execution_count": null, 1306 | "metadata": {}, 1307 | "outputs": [], 1308 | "source": [ 1309 | "Dict['Value_set'] = 2, 3, 4 # Adding set of values to a single Key \n", 1310 | "print(\"Dictionary after adding 3 elements: \") \n", 1311 | "print(Dict)" 1312 | ] 1313 | }, 1314 | { 1315 | "cell_type": "code", 1316 | "execution_count": null, 1317 | "metadata": {}, 1318 | "outputs": [], 1319 | "source": [ 1320 | "Dict[2] = 'Welcomes' # Updating existing Key's Value \n", 1321 | "print(\"Updated key value: \") \n", 1322 | "print(Dict) " 1323 | ] 1324 | }, 1325 | { 1326 | "cell_type": "code", 1327 | "execution_count": null, 1328 | "metadata": {}, 1329 | "outputs": [], 1330 | "source": [ 1331 | "Dict[5] = {'Nested' :{'1' : 'Life', '2' : 'at'}} # Adding Nested Key value to Dictionary\n", 1332 | "print(\"Adding a Nested Key: \") \n", 1333 | "print(Dict)" 1334 | ] 1335 | }, 1336 | { 1337 | "cell_type": "code", 1338 | "execution_count": null, 1339 | "metadata": {}, 1340 | "outputs": [], 1341 | "source": [ 1342 | "del Dict['A'][2] # Deleting a Key from Nested Dictionary\n", 1343 | "print(\"\\nDeleting a key from Nested Dictionary: \") \n", 1344 | "print(Dict) " 1345 | ] 1346 | }, 1347 | { 1348 | "cell_type": "code", 1349 | "execution_count": null, 1350 | "metadata": {}, 1351 | "outputs": [], 1352 | "source": [ 1353 | "Dict = {1: 'State', 'Street': 'For', 3: 'Employees'} # Creating a Dictionary\n", 1354 | "pop_ele = Dict.pop('1') # Deleting a key using pop() method \n", 1355 | "pop_ele" 1356 | ] 1357 | }, 1358 | { 1359 | "cell_type": "code", 1360 | "execution_count": null, 1361 | "metadata": {}, 1362 | "outputs": [], 1363 | "source": [ 1364 | "pop_ele = Dict.popitem() # Deleting an arbitrary key using popitem() function \n", 1365 | "pop_ele" 1366 | ] 1367 | }, 1368 | { 1369 | "cell_type": "code", 1370 | "execution_count": null, 1371 | "metadata": {}, 1372 | "outputs": [], 1373 | "source": [ 1374 | "# Deleting entire Dictionary \n", 1375 | "Dict.clear()\n", 1376 | "print(Dict) " 1377 | ] 1378 | }, 1379 | { 1380 | "cell_type": "markdown", 1381 | "metadata": { 1382 | "colab_type": "text", 1383 | "id": "yhiN9vhMmAYi" 1384 | }, 1385 | "source": [ 1386 | "It is easy to iterate over the keys in a dictionary:" 1387 | ] 1388 | }, 1389 | { 1390 | "cell_type": "code", 1391 | "execution_count": null, 1392 | "metadata": { 1393 | "colab": { 1394 | "autoexec": { 1395 | "startup": false, 1396 | "wait_interval": 0 1397 | } 1398 | }, 1399 | "colab_type": "code", 1400 | "id": "feIXTyfsmAYi", 1401 | "outputId": "c95f695f-820a-419b-e3ef-6b29f132bf75", 1402 | "scrolled": true 1403 | }, 1404 | "outputs": [], 1405 | "source": [ 1406 | "d = {'person': 2, 'cat': 4, 'spider': 8, 'spider': 10}\n", 1407 | "for i in d:\n", 1408 | " legs = d[i]\n", 1409 | " print('A %s has %d legs' % (i, legs))" 1410 | ] 1411 | }, 1412 | { 1413 | "cell_type": "markdown", 1414 | "metadata": { 1415 | "colab_type": "text", 1416 | "id": "XofdJMZjmAYj" 1417 | }, 1418 | "source": [ 1419 | "## Dictionary comprehensions: \n", 1420 | "\n", 1421 | "* These are similar to list comprehensions, but allow you to easily construct dictionaries." 1422 | ] 1423 | }, 1424 | { 1425 | "cell_type": "code", 1426 | "execution_count": null, 1427 | "metadata": { 1428 | "colab": { 1429 | "autoexec": { 1430 | "startup": false, 1431 | "wait_interval": 0 1432 | } 1433 | }, 1434 | "colab_type": "code", 1435 | "id": "YPgJz7NXmAYk", 1436 | "outputId": "8c620d4d-897d-4901-a917-9c13caa9d197" 1437 | }, 1438 | "outputs": [], 1439 | "source": [ 1440 | "nums = [0, 1, 2, 3, 4]\n", 1441 | "even_num_to_square = {x: x ** 2 for x in nums if x % 2 == 0}\n", 1442 | "even_num_to_square" 1443 | ] 1444 | }, 1445 | { 1446 | "cell_type": "markdown", 1447 | "metadata": { 1448 | "colab_type": "text", 1449 | "id": "aQ3sBSWcmAYl" 1450 | }, 1451 | "source": [ 1452 | "#### ACTIVITY:\n", 1453 | "Create a dictionary 'myDict' with the following (key, value) pairs. ('Name', \"XYZ\"), ('Batch', 32), (\"Location\", \"Bangalore\").\n", 1454 | "Iterate over the dictionary and print out the following (order doesn't matter):" 1455 | ] 1456 | }, 1457 | { 1458 | "cell_type": "markdown", 1459 | "metadata": { 1460 | "colab_type": "text", 1461 | "id": "iVzmzwEnmAYl" 1462 | }, 1463 | "source": [ 1464 | "My Name is XYZ" 1465 | ] 1466 | }, 1467 | { 1468 | "cell_type": "markdown", 1469 | "metadata": { 1470 | "colab_type": "text", 1471 | "id": "2NVD76BkmAYm" 1472 | }, 1473 | "source": [ 1474 | "My Batch is 32" 1475 | ] 1476 | }, 1477 | { 1478 | "cell_type": "markdown", 1479 | "metadata": { 1480 | "colab_type": "text", 1481 | "id": "je4sZ169mAYn" 1482 | }, 1483 | "source": [ 1484 | "My Location is Bangalore" 1485 | ] 1486 | }, 1487 | { 1488 | "cell_type": "markdown", 1489 | "metadata": { 1490 | "colab_type": "text", 1491 | "id": "1J5C9LiFmAYp" 1492 | }, 1493 | "source": [ 1494 | "## Tuples\n", 1495 | "\n", 1496 | "* A tuple is an (immutable) ordered list of values. \n", 1497 | "\n", 1498 | "* A tuple is in many ways similar to a list; one of the most important differences is that tuples can be used as keys in dictionaries, while lists cannot. Here is a trivial example:" 1499 | ] 1500 | }, 1501 | { 1502 | "cell_type": "code", 1503 | "execution_count": null, 1504 | "metadata": { 1505 | "colab": { 1506 | "autoexec": { 1507 | "startup": false, 1508 | "wait_interval": 0 1509 | } 1510 | }, 1511 | "colab_type": "code", 1512 | "id": "q-hm1UO7mAYp", 1513 | "outputId": "1e6e5912-3eb5-436f-bda2-4b815c11695e" 1514 | }, 1515 | "outputs": [], 1516 | "source": [ 1517 | "# An empty tuple \n", 1518 | "empty_tuple = () \n", 1519 | "print (empty_tuple)" 1520 | ] 1521 | }, 1522 | { 1523 | "cell_type": "code", 1524 | "execution_count": null, 1525 | "metadata": {}, 1526 | "outputs": [], 1527 | "source": [ 1528 | "# Creating non-empty tuples \n", 1529 | " \n", 1530 | "# One way of creation \n", 1531 | "tup = 'python', 'State'\n", 1532 | "print(tup) \n", 1533 | " \n", 1534 | "# Another for doing the same \n", 1535 | "tup = ('python', 'State') \n", 1536 | "print(tup)\n", 1537 | "\n", 1538 | "t = (5, 6) # Create a tuple\n", 1539 | "print(type(t))" 1540 | ] 1541 | }, 1542 | { 1543 | "cell_type": "code", 1544 | "execution_count": null, 1545 | "metadata": {}, 1546 | "outputs": [], 1547 | "source": [ 1548 | "# Code for concatenating 2 tuples \n", 1549 | " \n", 1550 | "tuple1 = (0, 1, 2, 3) \n", 1551 | "tuple2 = ('python', 'State') \n", 1552 | " \n", 1553 | "# Concatenating above two \n", 1554 | "print(tuple1 + tuple2) " 1555 | ] 1556 | }, 1557 | { 1558 | "cell_type": "code", 1559 | "execution_count": null, 1560 | "metadata": {}, 1561 | "outputs": [], 1562 | "source": [ 1563 | "# Code for creating nested tuples \n", 1564 | " \n", 1565 | "tuple1 = (0, 1, 2, 3) \n", 1566 | "tuple2 = ('python', 'State') \n", 1567 | "tuple3 = (tuple1, tuple2) \n", 1568 | "print(tuple3) " 1569 | ] 1570 | }, 1571 | { 1572 | "cell_type": "code", 1573 | "execution_count": null, 1574 | "metadata": { 1575 | "colab": { 1576 | "autoexec": { 1577 | "startup": false, 1578 | "wait_interval": 0 1579 | } 1580 | }, 1581 | "colab_type": "code", 1582 | "id": "pe1lY-dcmAYv", 1583 | "outputId": "863870e6-999f-4bef-f549-bd0aba491aa3" 1584 | }, 1585 | "outputs": [], 1586 | "source": [ 1587 | "t[0] = 1\n", 1588 | "print [1:5]" 1589 | ] 1590 | }, 1591 | { 1592 | "cell_type": "code", 1593 | "execution_count": null, 1594 | "metadata": {}, 1595 | "outputs": [], 1596 | "source": [ 1597 | "# code to test slicing \n", 1598 | " \n", 1599 | "tuple1 = (0 ,1, 2, 3) \n", 1600 | "print(tuple1[1:]) \n", 1601 | "print(tuple1[::-1]) \n", 1602 | "print(tuple1[2:4]) " 1603 | ] 1604 | }, 1605 | { 1606 | "cell_type": "code", 1607 | "execution_count": null, 1608 | "metadata": {}, 1609 | "outputs": [], 1610 | "source": [ 1611 | "# Code for deleting a tuple \n", 1612 | " \n", 1613 | "tuple3 = ( 0, 1) \n", 1614 | "del tuple3 \n", 1615 | "print(tuple3)" 1616 | ] 1617 | }, 1618 | { 1619 | "cell_type": "code", 1620 | "execution_count": null, 1621 | "metadata": {}, 1622 | "outputs": [], 1623 | "source": [ 1624 | "# Code for converting a list and a string into a tuple \n", 1625 | " \n", 1626 | "list1 = [0, 1, 2] \n", 1627 | "print(tuple(list1)) \n", 1628 | "print(tuple('python')) # string 'python' " 1629 | ] 1630 | }, 1631 | { 1632 | "cell_type": "code", 1633 | "execution_count": null, 1634 | "metadata": {}, 1635 | "outputs": [], 1636 | "source": [ 1637 | "#python code for creating tuples in a loop \n", 1638 | " \n", 1639 | "tup = ('State') \n", 1640 | "for i in range(3): \n", 1641 | " tup = (tup)*2\n", 1642 | " print(tup)" 1643 | ] 1644 | }, 1645 | { 1646 | "cell_type": "code", 1647 | "execution_count": null, 1648 | "metadata": {}, 1649 | "outputs": [], 1650 | "source": [] 1651 | }, 1652 | { 1653 | "cell_type": "markdown", 1654 | "metadata": { 1655 | "colab_type": "text", 1656 | "id": "T-MbT7gFmAYx" 1657 | }, 1658 | "source": [ 1659 | "#### ACTIVITY:\n", 1660 | "Create a tuple named 'myTup' with the following elements: 1, 2, 'abc'. Print this tuple. Access the first two elements of the tuple. Can you add another element 'xyz' to myTup? What should we do if we want to get (1, 2, 'abc', 'xyz') usin gthe existing tuple?" 1661 | ] 1662 | }, 1663 | { 1664 | "cell_type": "code", 1665 | "execution_count": null, 1666 | "metadata": { 1667 | "colab": { 1668 | "autoexec": { 1669 | "startup": false, 1670 | "wait_interval": 0 1671 | } 1672 | }, 1673 | "colab_type": "code", 1674 | "id": "eZYHGLLfmAYx" 1675 | }, 1676 | "outputs": [], 1677 | "source": [] 1678 | }, 1679 | { 1680 | "cell_type": "markdown", 1681 | "metadata": { 1682 | "colab_type": "text", 1683 | "id": "SwADWnFgmAYy" 1684 | }, 1685 | "source": [ 1686 | "## Functions\n", 1687 | "\n", 1688 | "* Python functions are defined using the `def` keyword. For example:\n", 1689 | "\n", 1690 | "* A function is a set of statements that take inputs, do some specific computation and produces output. \n", 1691 | "\n", 1692 | "* The idea is to put some commonly or repeatedly done task together and make a function, so that instead of writing the same code again and again for different inputs, we can call the function.\n", 1693 | "\n", 1694 | "* Python provides built-in functions like print(), etc. but we can also create your own functions. These functions are called user-defined functions." 1695 | ] 1696 | }, 1697 | { 1698 | "cell_type": "code", 1699 | "execution_count": null, 1700 | "metadata": { 1701 | "colab": { 1702 | "autoexec": { 1703 | "startup": false, 1704 | "wait_interval": 0 1705 | } 1706 | }, 1707 | "colab_type": "code", 1708 | "id": "-LZLE-F_mAYz", 1709 | "outputId": "0fb9fbf6-ffb3-4fa3-ba84-44a2442bd625" 1710 | }, 1711 | "outputs": [], 1712 | "source": [ 1713 | "def sign(x):\n", 1714 | " if x > 0:\n", 1715 | " return 'positive'\n", 1716 | " elif x < 0:\n", 1717 | " return 'negative'\n", 1718 | " else:\n", 1719 | " return 'zero'\n", 1720 | "\n", 1721 | "for x in [-1, 0, 1]:\n", 1722 | " print sign(x)" 1723 | ] 1724 | }, 1725 | { 1726 | "cell_type": "markdown", 1727 | "metadata": { 1728 | "colab_type": "text", 1729 | "id": "v0eqOanymAY0" 1730 | }, 1731 | "source": [ 1732 | "We will often define functions to take optional keyword arguments, like this:" 1733 | ] 1734 | }, 1735 | { 1736 | "cell_type": "code", 1737 | "execution_count": null, 1738 | "metadata": { 1739 | "colab": { 1740 | "autoexec": { 1741 | "startup": false, 1742 | "wait_interval": 0 1743 | } 1744 | }, 1745 | "colab_type": "code", 1746 | "id": "V7fxtplJmAY1", 1747 | "outputId": "909f8c05-4dba-4a5f-fbc2-ac5c077e410e" 1748 | }, 1749 | "outputs": [], 1750 | "source": [ 1751 | "def hello(name, loud=False):\n", 1752 | " if loud:\n", 1753 | " print ('HELLO, %s' % name.upper())\n", 1754 | " else:\n", 1755 | " print ('Hello, %s!' % name)\n", 1756 | "\n", 1757 | "hello('Bob', loud = True)\n", 1758 | "hello('Fred')" 1759 | ] 1760 | }, 1761 | { 1762 | "cell_type": "markdown", 1763 | "metadata": { 1764 | "colab_type": "text", 1765 | "id": "_7N11WZymAY2" 1766 | }, 1767 | "source": [ 1768 | "#### ACTIVITY:\n", 1769 | "Define a function which would take a number 'n' as input and compute the sum of natural numbers till n.\n", 1770 | "Example if input number is 5, the function returns the result: 1+2+3+4+5" 1771 | ] 1772 | }, 1773 | { 1774 | "cell_type": "markdown", 1775 | "metadata": { 1776 | "colab_type": "text", 1777 | "id": "-sYiC88hmAY4" 1778 | }, 1779 | "source": [ 1780 | "HINT: You can use the shortcut formula n(n+1)/2.\n", 1781 | "So for n = 5, result = 5*6/2 = 15" 1782 | ] 1783 | }, 1784 | { 1785 | "cell_type": "code", 1786 | "execution_count": null, 1787 | "metadata": { 1788 | "colab": { 1789 | "autoexec": { 1790 | "startup": false, 1791 | "wait_interval": 0 1792 | } 1793 | }, 1794 | "colab_type": "code", 1795 | "id": "y2V1xhfimAY4" 1796 | }, 1797 | "outputs": [], 1798 | "source": [] 1799 | }, 1800 | { 1801 | "cell_type": "markdown", 1802 | "metadata": { 1803 | "colab_type": "text", 1804 | "id": "VBAOhE80mAY5" 1805 | }, 1806 | "source": [ 1807 | "#### ACTIVITY:\n", 1808 | "Write a function 'F' which would take in two numbers. Based on user choice 1 == add the numbers or 2 == multiply the two numbers, perform the operation and return the appropriate results" 1809 | ] 1810 | }, 1811 | { 1812 | "cell_type": "code", 1813 | "execution_count": null, 1814 | "metadata": {}, 1815 | "outputs": [], 1816 | "source": [] 1817 | }, 1818 | { 1819 | "cell_type": "markdown", 1820 | "metadata": {}, 1821 | "source": [ 1822 | "### Python Operators\n", 1823 | "Python language supports the following types of operators.\n", 1824 | "\n", 1825 | "* Arithmetic Operators\n", 1826 | "* Comparison / Relational Operators\n", 1827 | "* Assignment Operators\n", 1828 | "* Logical Operators\n", 1829 | "* Bitwise Operators\n", 1830 | "* Membership Operators\n", 1831 | "* Identity Operators" 1832 | ] 1833 | }, 1834 | { 1835 | "cell_type": "code", 1836 | "execution_count": null, 1837 | "metadata": {}, 1838 | "outputs": [], 1839 | "source": [ 1840 | "# Arithmetic Operators\n", 1841 | "a = 2\n", 1842 | "b = 3\n", 1843 | "c = 0\n", 1844 | "\n", 1845 | "c = a + b \n", 1846 | "print(\"Addition - Value of c is \", c)\n", 1847 | "\n", 1848 | "c = a - b\n", 1849 | "print(\"Substraction - Value of c is \", c)\n", 1850 | "\n", 1851 | "c = a * b\n", 1852 | "print(\"Multiplication - Value of c is \", c)\n", 1853 | "\n", 1854 | "c = a / b\n", 1855 | "print(\"Division - Value of c is \", c)\n", 1856 | "\n", 1857 | "c = a//b \n", 1858 | "print(\"Floor Division - Value of c is \", c)\n", 1859 | "\n", 1860 | "c = a % b\n", 1861 | "print(\"Modulus / Remainder - Value of c is \", c)\n", 1862 | "\n", 1863 | "c = a**b \n", 1864 | "print(\"Exponent / Power - Value of c is \", c)" 1865 | ] 1866 | }, 1867 | { 1868 | "cell_type": "code", 1869 | "execution_count": null, 1870 | "metadata": {}, 1871 | "outputs": [], 1872 | "source": [ 1873 | "# Comparison / Relational Operators\n", 1874 | "a = 10\n", 1875 | "b = 10\n", 1876 | "c = 0\n", 1877 | "\n", 1878 | "if ( a == b ):\n", 1879 | " print(\"Line 1 - a is equal to b\")\n", 1880 | "else:\n", 1881 | " print(\"Line 1 - a is not equal to b\")\n", 1882 | "\n", 1883 | "if ( a != b ):\n", 1884 | " print(\"Line 2 - a is not equal to b\")\n", 1885 | "else:\n", 1886 | " print(\"Line 2 - a is equal to b\")\n", 1887 | "\n", 1888 | "if ( a < b ):\n", 1889 | " print(\"Line 3 - a is less than b\") \n", 1890 | "else:\n", 1891 | " print(\"Line 3 - a is not less than b\")\n", 1892 | "\n", 1893 | "if ( a > b ):\n", 1894 | " print(\"Line 4 - a is greater than b\")\n", 1895 | "else:\n", 1896 | " print(\"Line 4 - a is not greater than b\")" 1897 | ] 1898 | }, 1899 | { 1900 | "cell_type": "code", 1901 | "execution_count": null, 1902 | "metadata": {}, 1903 | "outputs": [], 1904 | "source": [ 1905 | "a = 5;\n", 1906 | "b = 20;\n", 1907 | "if ( a <= b ):\n", 1908 | " print(\"Line 5 - a is either less than or equal to b\")\n", 1909 | "else:\n", 1910 | " print(\"Line 5 - a is neither less than nor equal to b\")\n", 1911 | "\n", 1912 | "if ( b >= a ):\n", 1913 | " print(\"Line 6 - b is either greater than or equal to b\")\n", 1914 | "else:\n", 1915 | " print(\"Line 6 - b is neither greater than nor equal to b\")" 1916 | ] 1917 | }, 1918 | { 1919 | "cell_type": "code", 1920 | "execution_count": null, 1921 | "metadata": {}, 1922 | "outputs": [], 1923 | "source": [ 1924 | "# Assignment Operators\n", 1925 | "a = 2\n", 1926 | "b = 3\n", 1927 | "c = 0\n", 1928 | "\n", 1929 | "c = a + b\n", 1930 | "print(\"Line 1 - Value of c is \", c)\n", 1931 | "\n", 1932 | "c += a\n", 1933 | "print(\"Line 2 - Value of c is \", c) \n", 1934 | "\n", 1935 | "c *= a\n", 1936 | "print(\"Line 3 - Value of c is \", c) \n", 1937 | "\n", 1938 | "c /= a \n", 1939 | "print(\"Line 4 - Value of c is \", c) \n", 1940 | "\n", 1941 | "c //= a\n", 1942 | "print(\"Line 5 - Value of c is \", c)\n", 1943 | "\n", 1944 | "c %= a\n", 1945 | "print(\"Line 6 - Value of c is \", c)\n", 1946 | "\n", 1947 | "c **= a\n", 1948 | "print(\"Line 7 - Value of c is \", c)" 1949 | ] 1950 | }, 1951 | { 1952 | "cell_type": "code", 1953 | "execution_count": null, 1954 | "metadata": {}, 1955 | "outputs": [], 1956 | "source": [ 1957 | "# Logical Operators\n", 1958 | "x = True\n", 1959 | "y = False\n", 1960 | "\n", 1961 | "print('x and y is',x and y)\n", 1962 | "print('x or y is',x or y)\n", 1963 | "print('not x is',not x)" 1964 | ] 1965 | }, 1966 | { 1967 | "cell_type": "code", 1968 | "execution_count": null, 1969 | "metadata": {}, 1970 | "outputs": [], 1971 | "source": [ 1972 | "# Bitwise Operators\n", 1973 | "a = 60 # 60 = 0011 1100 \n", 1974 | "b = 13 # 13 = 0000 1101 \n", 1975 | "c = 0\n", 1976 | "\n", 1977 | "c = a & b; # 12 = 0000 1100 #both should be 1\n", 1978 | "print(\"Line 1 - Value of c is \", c)\n", 1979 | "\n", 1980 | "c = a | b; # 61 = 0011 1101 #either should be 1\n", 1981 | "print(\"Line 2 - Value of c is \", c)\n", 1982 | "\n", 1983 | "c = a ^ b; # 49 = 0011 0001 #both should be different\n", 1984 | "print(\"Line 3 - Value of c is \", c)" 1985 | ] 1986 | }, 1987 | { 1988 | "cell_type": "code", 1989 | "execution_count": null, 1990 | "metadata": {}, 1991 | "outputs": [], 1992 | "source": [ 1993 | "# Membership Operators\n", 1994 | "# in \t Evaluates to true if it finds a variable in the specified sequence and false otherwise.\n", 1995 | "# not in \t Evaluates to true if it does not finds a variable in the specified sequence and false otherwise.\n", 1996 | "\n", 1997 | "a = 1\n", 1998 | "b = 20\n", 1999 | "list = [1, 2, 3, 4, 5 ]\n", 2000 | "\n", 2001 | "if ( a in list ):\n", 2002 | " print(\"Line 1 - a is available in the given list\")\n", 2003 | "else:\n", 2004 | " print(\"Line 1 - a is not available in the given list\")" 2005 | ] 2006 | }, 2007 | { 2008 | "cell_type": "code", 2009 | "execution_count": null, 2010 | "metadata": {}, 2011 | "outputs": [], 2012 | "source": [ 2013 | "a = 10\n", 2014 | "if ( a in list ):\n", 2015 | " print(\"Line 2 - a is available in the given list\")\n", 2016 | "else:\n", 2017 | " print(\"Line 2 - a is not available in the given list\")\n", 2018 | "\n", 2019 | "if (b not in list):\n", 2020 | " print(\"Line 3 - b is not available in the given list\")\n", 2021 | "else:\n", 2022 | " print(\"Line 3 - b is available in the given list\")" 2023 | ] 2024 | }, 2025 | { 2026 | "cell_type": "code", 2027 | "execution_count": null, 2028 | "metadata": {}, 2029 | "outputs": [], 2030 | "source": [ 2031 | "# Identity Operators\n", 2032 | "# is \t Evaluates to true if the variables on either side of the operator point to the same object and false otherwise.\n", 2033 | "# is not \t Evaluates to false if the variables on either side of the operator point to the same object and true otherwise.\n", 2034 | "\n", 2035 | "a = 20\n", 2036 | "b = 30\n", 2037 | "\n", 2038 | "#print(a is b)\n", 2039 | "print(a is not b)" 2040 | ] 2041 | }, 2042 | { 2043 | "cell_type": "code", 2044 | "execution_count": null, 2045 | "metadata": {}, 2046 | "outputs": [], 2047 | "source": [ 2048 | "# String Traversal\n", 2049 | "# Range function in loops\n", 2050 | "\n", 2051 | "string_to_iterate = \"Python\"\n", 2052 | "\n", 2053 | "for char in string_to_iterate:\n", 2054 | " print(char)\n", 2055 | "\n", 2056 | "# Printing index\n", 2057 | "for char_index in range(len(string_to_iterate)):\n", 2058 | " print(char_index)\n", 2059 | "\n", 2060 | "c = 'Programming Language'\n", 2061 | "string_to_iterate = 'Python'\n", 2062 | "# Printing the exact values \n", 2063 | "for char_index in range(len(string_to_iterate)):\n", 2064 | " print(c[char_index])" 2065 | ] 2066 | } 2067 | ], 2068 | "metadata": { 2069 | "colab": { 2070 | "default_view": {}, 2071 | "name": "Python_basics.ipynb", 2072 | "provenance": [], 2073 | "version": "0.3.2", 2074 | "views": {} 2075 | }, 2076 | "kernelspec": { 2077 | "display_name": "Python 3", 2078 | "language": "python", 2079 | "name": "python3" 2080 | }, 2081 | "language_info": { 2082 | "codemirror_mode": { 2083 | "name": "ipython", 2084 | "version": 3 2085 | }, 2086 | "file_extension": ".py", 2087 | "mimetype": "text/x-python", 2088 | "name": "python", 2089 | "nbconvert_exporter": "python", 2090 | "pygments_lexer": "ipython3", 2091 | "version": "3.7.4" 2092 | } 2093 | }, 2094 | "nbformat": 4, 2095 | "nbformat_minor": 1 2096 | } 2097 | --------------------------------------------------------------------------------