├── .gitignore ├── README.md ├── ipython-notebook ├── conditionals.py ├── data-types.py ├── defining-functions.py ├── dictionaries.py ├── hello.py ├── import_library.py ├── list-sections.py ├── lists.py ├── more-printing.py ├── simple_math.py ├── test.py ├── user-input.py ├── variables.py ├── weather.py ├── while-loop.py └── workshop.ipynb ├── sections ├── ask_csv.py ├── conditionals.md ├── csv.md ├── google.md ├── google_result.png ├── google_search.png ├── grok.md ├── input.md ├── installation.md ├── loop.py ├── loops.md ├── motivate.md ├── motivation.py ├── multiline.md ├── notes.md ├── nypl_items.csv ├── repl.md ├── resources.md ├── run.md ├── stack_overflow.png ├── types.md └── variables.md └── update.sh /.gitignore: -------------------------------------------------------------------------------- 1 | *~ 2 | *# 3 | .#* 4 | *.dnc 5 | __pycache__ -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Introduction to Python 2 | 3 | 4 | Python is a high-level programming language widely used in both industry and the academy. It is particularly suited to working with textual and numeric data, and has a strong developer community that enables Python programmers to leverage code that has already been written to solve many problems. Python emphasizes readability and comprehensibility, and its straightforward syntax makes it an accessible first programming language. 5 | 6 | [Getting set up](sections/installation.md) 7 | [Interacting with Python](sections/repl.md) 8 | [Types](sections/types.md) 9 | [Variables](sections/variables.md) 10 | [Running scripts](sections/run.md) 11 | [Lists and Loops](sections/loops.md) 12 | [Conditionals](sections/conditionals.md) 13 | [Input](sections/input.md) 14 | [Using Google](sections/google.md) 15 | [A little motivation](sections/motivate.md) 16 | [Working with files](csv.md) 17 | [Python resources](sections/resources.md) 18 | -------------------------------------------------------------------------------- /ipython-notebook/conditionals.py: -------------------------------------------------------------------------------- 1 | # Conditionals 2 | 3 | weather = "sunny" 4 | 5 | if weather == "sunny": 6 | print("Bring your shades") 7 | elif weather == "rainy": 8 | print("Bring your umbrella") 9 | else: 10 | print("I don't know what you should bring! I'm just a little program...") 11 | 12 | -------------------------------------------------------------------------------- /ipython-notebook/data-types.py: -------------------------------------------------------------------------------- 1 | # A string is a set of characters, which can be letters, spaces, numbers, and special characters. 2 | 3 | print(type("I'm a string! I'm the first type you learned.")) 4 | 5 | # Integers are numbers without decimal places 6 | 7 | print(type(5)) 8 | 9 | # Floating point numbers (floats) are numbers with decimal places 10 | 11 | print(type(10.0)) 12 | 13 | # If you want more precise answers, use floats 14 | 15 | print(11 / 5) 16 | print(11.0 / 5.0) 17 | -------------------------------------------------------------------------------- /ipython-notebook/defining-functions.py: -------------------------------------------------------------------------------- 1 | # Creating functions 2 | 3 | 4 | def weather_advice(weather): 5 | if weather == "sunny": 6 | return "Bring your shades" 7 | elif weather == "rainy": 8 | return "Bring your umbrella" 9 | elif weather == "snowy": 10 | return "You need snowshoes today" 11 | else: 12 | return "I don't know what you should bring! I'm just a little program..." 13 | 14 | print(weather_advice('snowy')) 15 | print(weather_advice('hail')) 16 | 17 | -------------------------------------------------------------------------------- /ipython-notebook/dictionaries.py: -------------------------------------------------------------------------------- 1 | # Dictionaries 2 | 3 | # Let's make a phone book 4 | 5 | phone_book = {'Alice':199933355555, 6 | 'Bob':14446669999, 7 | 'Betty Suarez':18884321111, 8 | 'Wilhelmina Slater':12223334444} 9 | 10 | 11 | print(phone_book['Alice']) 12 | 13 | def look_up_number(name): 14 | return phone_book[name] 15 | 16 | print("Betty's number is",look_up_number('Betty Suarez')) 17 | 18 | -------------------------------------------------------------------------------- /ipython-notebook/hello.py: -------------------------------------------------------------------------------- 1 | # Your first program 2 | 3 | print("Hello world!") 4 | -------------------------------------------------------------------------------- /ipython-notebook/import_library.py: -------------------------------------------------------------------------------- 1 | # Import the "random" library so we can use its functions 2 | import random 3 | 4 | print('Random number from 1 to 100: ') 5 | print(random.randint(1,100)) 6 | 7 | print('') 8 | 9 | def roll_dice(number_of_dice): 10 | for x in range(0,number_of_dice): 11 | print(random.randint(1,6)) 12 | 13 | print('Roll dice:') 14 | roll_dice(5) 15 | -------------------------------------------------------------------------------- /ipython-notebook/list-sections.py: -------------------------------------------------------------------------------- 1 | groceries = ['ham','eggs','cheese'] 2 | flowers = ['rose','violet','daisy'] 3 | primes = [2,3,5,7,11,13] 4 | 5 | print(groceries[0]) # prints the first item (counting starts at 0) 6 | 7 | print(primes[2:4]) # prints from the third to the fifth item 8 | 9 | print(flowers[1:]) # prints from the second item to the end 10 | 11 | print(primes[:3]) # prints from the beginning to the fourth item 12 | 13 | 14 | # Add an item to a list 15 | flowers.append('buttercup') 16 | print(flowers) 17 | 18 | 19 | # Remove an item to a list 20 | groceries.remove('ham') 21 | print(groceries) 22 | -------------------------------------------------------------------------------- /ipython-notebook/lists.py: -------------------------------------------------------------------------------- 1 | # Define some lists 2 | 3 | empty_list = [] 4 | groceries = ['ham','eggs','cheese'] 5 | flowers = ['rose','violet','daisy'] 6 | primes = [2,3,5,7,11,13] 7 | 8 | print(empty_list) 9 | print(flowers) 10 | 11 | # Use a for loop to go through (or "iterate over") lists and do something to each item 12 | 13 | for flower in flowers: 14 | print(flower) 15 | 16 | for item in groceries: 17 | print(item) 18 | 19 | for number in primes: 20 | double_prime = number * 2 21 | print(double_prime) 22 | -------------------------------------------------------------------------------- /ipython-notebook/more-printing.py: -------------------------------------------------------------------------------- 1 | # Print a string on multiple lines 2 | 3 | print('''Mary had a little lamb, 4 | Its fleece was white as snow, 5 | And everywhere that Mary went, 6 | The lamb was sure to go.''') 7 | 8 | 9 | # A string is a set of characters, either letters, numbers, or symbols 10 | 11 | # You can use these characters to start and end strings: 12 | # Single quote: ' 13 | # Double quote: " 14 | # Triple quote: ''' (can be used for multiline string) 15 | 16 | # Don't mix and match! Always have the same mark at the beginning and end of the string. 17 | -------------------------------------------------------------------------------- /ipython-notebook/simple_math.py: -------------------------------------------------------------------------------- 1 | print(2 + 2) # Add 2 | print(200 - 55) # Subtract 3 | print(5 * 4) # Multiply 4 | print(144 / 12) # Divide 5 | print(11 % 2) # Mod (gives remainder) 6 | print(10 ** 2) # Exponent 7 | 8 | # <- These hash marks denote comments. Comments (lines beginning with a hash) aren't used when you run your program, and are useful for providing descriptions 9 | -------------------------------------------------------------------------------- /ipython-notebook/test.py: -------------------------------------------------------------------------------- 1 | prime_numbers = [2, 3, 5, 7, 11] 2 | 3 | for num in prime_numbers: 4 | print('The square of %s is:' % num) 5 | print(num * num) 6 | -------------------------------------------------------------------------------- /ipython-notebook/user-input.py: -------------------------------------------------------------------------------- 1 | # If you're using Python 3: 2 | 3 | name = input("What's your name? ") 4 | 5 | # If you're using Python 2: 6 | # 7 | # name = raw_input("What's your name? ") 8 | 9 | if len(name) > 12: 10 | print("Hi %s! Your name is quite long!" % name) 11 | else: 12 | print("Hi %s! Your name is quite short!" % name) 13 | -------------------------------------------------------------------------------- /ipython-notebook/variables.py: -------------------------------------------------------------------------------- 1 | # Variables 2 | 3 | lemonade_price = 0.25 4 | glasses_sold = 23 5 | 6 | profit = lemonade_price * glasses_sold 7 | 8 | print(profit) 9 | 10 | # Variable names can have letters, numbers, and certain special characters, such as underscore (_) 11 | 12 | # Make your variable names as descriptive as possible 13 | 14 | # The equals sign (=) assigns a variable name to a string, integer, float, or other data type 15 | -------------------------------------------------------------------------------- /ipython-notebook/weather.py: -------------------------------------------------------------------------------- 1 | # Let's combine some of what we've learned 2 | 3 | while True: 4 | # Use "raw_input" instead of "input" in Python 2 5 | weather = input("What's the weather today? ") 6 | if weather == "cloudy" or weather == "overcase": 7 | print("You don't need a hat") 8 | elif weather == "sunny" or weather == "warm": 9 | print("Wear shades") 10 | elif weather == "rainy" or weather == "wet": 11 | print("Bring an umbrella") 12 | elif weather == "snowy" or weather == "cold": 13 | print("Wear your wooly muffler") 14 | else: 15 | print("I don't know what you should do today...") 16 | -------------------------------------------------------------------------------- /ipython-notebook/while-loop.py: -------------------------------------------------------------------------------- 1 | # While loops 2 | 3 | while 1 == 1: 4 | print("I've broken my computer!") 5 | 6 | # As long as 1 is equal to 1 (which will always be true), the program will continue to print "Oh no!" 7 | 8 | -------------------------------------------------------------------------------- /ipython-notebook/workshop.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 8, 6 | "metadata": { 7 | "collapsed": false 8 | }, 9 | "outputs": [ 10 | { 11 | "name": "stdout", 12 | "output_type": "stream", 13 | "text": [ 14 | "Hello world!\n" 15 | ] 16 | } 17 | ], 18 | "source": [ 19 | "# %load hello.py\n", 20 | "# Your first program\n", 21 | "\n", 22 | "print('Hello world!')" 23 | ] 24 | }, 25 | { 26 | "cell_type": "code", 27 | "execution_count": 9, 28 | "metadata": { 29 | "collapsed": false 30 | }, 31 | "outputs": [ 32 | { 33 | "name": "stdout", 34 | "output_type": "stream", 35 | "text": [ 36 | "4\n", 37 | "145\n", 38 | "20\n", 39 | "12\n", 40 | "1\n", 41 | "100\n" 42 | ] 43 | } 44 | ], 45 | "source": [ 46 | "# %load math.py\n", 47 | "# Basic math\n", 48 | "\n", 49 | "print(2 + 2) # Add\n", 50 | "print(200 - 55) # Subtract\n", 51 | "print(5 * 4) # Multiply\n", 52 | "print(144 / 12) # Divide\n", 53 | "print(11 % 2) # Mod (gives remainder)\n", 54 | "print(10 ** 2) # Exponent\n", 55 | "\n", 56 | "# <- These hash marks denote comments. Comments (lines beginning with a hash) aren't used when you run your program, and are useful for providing descriptions\n" 57 | ] 58 | }, 59 | { 60 | "cell_type": "code", 61 | "execution_count": null, 62 | "metadata": { 63 | "collapsed": false 64 | }, 65 | "outputs": [], 66 | "source": [ 67 | "# %load multi-line-string.py\n", 68 | "# Print a string on multiple lines\n", 69 | "\n", 70 | "print('''Mary had a little lamb,\n", 71 | "Its fleece was white as snow,\n", 72 | "And everywhere that Mary went,\n", 73 | "The lamb was sure to go.''')\n", 74 | "\n", 75 | "# You can use these characters to start and end strings:\n", 76 | "# Single quote: '\n", 77 | "# Double quote: \"\n", 78 | "# Triple quote: ''' (can be used for multiline string)\n", 79 | "\n", 80 | "# Don't mix and match! Always have the same mark at the start and end of your string\n" 81 | ] 82 | }, 83 | { 84 | "cell_type": "code", 85 | "execution_count": 11, 86 | "metadata": { 87 | "collapsed": false 88 | }, 89 | "outputs": [ 90 | { 91 | "name": "stdout", 92 | "output_type": "stream", 93 | "text": [ 94 | "\n", 95 | "\n", 96 | "\n", 97 | "2\n", 98 | "2.2\n" 99 | ] 100 | } 101 | ], 102 | "source": [ 103 | "# %load types.py\n", 104 | "# Types\n", 105 | "\n", 106 | "# A string is a set of characters, which can be letters, spaces, numbers, and special characters.\n", 107 | "\n", 108 | "print(type(\"I'm a string! I'm the first type you learned.\"))\n", 109 | "\n", 110 | "# Integers are numbers without decimal places\n", 111 | "\n", 112 | "print(type(5))\n", 113 | "\n", 114 | "# Floating point numbers (floats) are numbers with decimal places\n", 115 | "\n", 116 | "print(type(10.0))\n", 117 | "\n", 118 | "# If you want more precise answers, use floats\n", 119 | "\n", 120 | "print(11 / 5)\n", 121 | "print(11.0 / 5.0)\n" 122 | ] 123 | }, 124 | { 125 | "cell_type": "code", 126 | "execution_count": 12, 127 | "metadata": { 128 | "collapsed": false 129 | }, 130 | "outputs": [ 131 | { 132 | "name": "stdout", 133 | "output_type": "stream", 134 | "text": [ 135 | "5.75\n" 136 | ] 137 | } 138 | ], 139 | "source": [ 140 | "# %load variables.py\n", 141 | "# Variables\n", 142 | "\n", 143 | "lemonade_price = 0.25\n", 144 | "glasses_sold = 23\n", 145 | "\n", 146 | "profit = lemonade_price * glasses_sold\n", 147 | "\n", 148 | "print(profit)\n", 149 | "\n", 150 | "# Variable names can have letters, numbers, and certain special characters, such as underscore (_)\n", 151 | "\n", 152 | "# Make your variable names as descriptive as possible\n", 153 | "\n", 154 | "# The equals sign (=) assigns a variable name to a string, integer, float, or other data type\n" 155 | ] 156 | }, 157 | { 158 | "cell_type": "code", 159 | "execution_count": 13, 160 | "metadata": { 161 | "collapsed": false, 162 | "scrolled": true 163 | }, 164 | "outputs": [ 165 | { 166 | "name": "stdout", 167 | "output_type": "stream", 168 | "text": [ 169 | "30\n", 170 | "I like Python!\n", 171 | "Banana\n" 172 | ] 173 | } 174 | ], 175 | "source": [ 176 | "# %load len-and-strings.py\n", 177 | "# Len()\n", 178 | "\n", 179 | "# The len() function can tell you how many characters is in a string. Later, we'll see it can return the number of items in a list.\n", 180 | "\n", 181 | "print(len('How many characters long am I?'))\n", 182 | "\n", 183 | "# You can use some math operations on strings\n", 184 | "\n", 185 | "print(\"I like \" + \"Python!\")\n", 186 | "\n", 187 | "print(\"Ba\" + \"na\" * 2)\n" 188 | ] 189 | }, 190 | { 191 | "cell_type": "code", 192 | "execution_count": null, 193 | "metadata": { 194 | "collapsed": true 195 | }, 196 | "outputs": [], 197 | "source": [ 198 | "# Be careful running this one! It might not stop...\n", 199 | "\n", 200 | "while 1 == 1:\n", 201 | " print('Oh no!')\n", 202 | " \n", 203 | "# As long as 1 is equal to 1 (which will always be true), the program will continue to print \"Oh no!\"" 204 | ] 205 | }, 206 | { 207 | "cell_type": "code", 208 | "execution_count": null, 209 | "metadata": { 210 | "collapsed": false 211 | }, 212 | "outputs": [], 213 | "source": [ 214 | "# %load if.py\n", 215 | "# Conditionals\n", 216 | "\n", 217 | "number = 9\n", 218 | "\n", 219 | "if number % 2 == 0:\n", 220 | " print(\"The number is even\")\n", 221 | "else:\n", 222 | " print(\"The number is odd\")\n", 223 | "\n", 224 | "# Be more specific in your answer with string formatters\n", 225 | " \n", 226 | "if number % 2 == 0:\n", 227 | " print(\"%s is even\" % number)\n", 228 | "else:\n", 229 | " print(\"%s is odd\" % number)\n", 230 | "\n", 231 | "# %s is a placeholder that is replaced by the variable after the %\n" 232 | ] 233 | }, 234 | { 235 | "cell_type": "code", 236 | "execution_count": null, 237 | "metadata": { 238 | "collapsed": true 239 | }, 240 | "outputs": [], 241 | "source": [ 242 | "# %load functions.py\n", 243 | "# Defining functions\n", 244 | "\n", 245 | "# Make the even-odd program above into a function\n", 246 | "\n", 247 | "def check_if_even(number):\n", 248 | " if number % 2 == 0:\n", 249 | " print(\"%s is even\" % number)\n", 250 | " else:\n", 251 | " print(\"%s is odd\" % number)\n", 252 | "\n", 253 | "check_if_even(9)\n", 254 | "check_if_even(34)\n", 255 | "check_if_even(101)\n", 256 | "check_if_even(1000000)\n" 257 | ] 258 | }, 259 | { 260 | "cell_type": "code", 261 | "execution_count": null, 262 | "metadata": { 263 | "collapsed": true 264 | }, 265 | "outputs": [], 266 | "source": [ 267 | "# %load input.py\n", 268 | "# Take input from user\n", 269 | "\n", 270 | "name = raw_input(\"What's your name? \")\n", 271 | "\n", 272 | "if len(name) > 10:\n", 273 | " print(\"Your name is too long!\")\n", 274 | "else:\n", 275 | " print(\"Nice name!\")\n" 276 | ] 277 | }, 278 | { 279 | "cell_type": "code", 280 | "execution_count": null, 281 | "metadata": { 282 | "collapsed": false 283 | }, 284 | "outputs": [], 285 | "source": [ 286 | "# %load weather.py\n", 287 | "# Let's pull together some of what we've learned\n", 288 | "\n", 289 | "\n", 290 | "\n", 291 | "while 1:\n", 292 | " weather = raw_input(\"What's the weather today? \")\n", 293 | " if weather == \"cloudy\":\n", 294 | " print(\"You don't need a hat\")\n", 295 | " elif weather == \"sunny\":\n", 296 | " print(\"Wear shades\")\n", 297 | " elif weather == \"rainy\":\n", 298 | " print(\"Bring an umbrella\")\n", 299 | " elif weather == \"snowy\":\n", 300 | " print(\"Wear your wolly muffler\")\n", 301 | " else:\n", 302 | " print(\"I don't know what you should do today...\")\n" 303 | ] 304 | }, 305 | { 306 | "cell_type": "code", 307 | "execution_count": null, 308 | "metadata": { 309 | "collapsed": true 310 | }, 311 | "outputs": [], 312 | "source": [ 313 | "# %load lists.py\n", 314 | "# Lists\n", 315 | "\n", 316 | "# Start with some lists\n", 317 | "\n", 318 | "groceries = ['ham','eggs','cheese']\n", 319 | "flowers = ['rose','violet','daisy']\n", 320 | "primes = [2,3,5,7,11,13]\n", 321 | "\n", 322 | "print(flowers)\n", 323 | "\n", 324 | "# Use a for loop to iterate over lists and do something to each item\n", 325 | "\n", 326 | "for flower in flowers:\n", 327 | " print(flower)\n", 328 | "\n", 329 | "for item in groceries:\n", 330 | " print(item)\n" 331 | ] 332 | }, 333 | { 334 | "cell_type": "code", 335 | "execution_count": 3, 336 | "metadata": { 337 | "collapsed": false 338 | }, 339 | "outputs": [ 340 | { 341 | "name": "stdout", 342 | "output_type": "stream", 343 | "text": [ 344 | "eggs\n", 345 | "[5, 7]\n", 346 | "['violet', 'daisy']\n", 347 | "[2, 3, 5]\n", 348 | "['rose', 'violet', 'daisy', 'buttercup']\n", 349 | "['eggs', 'cheese']\n" 350 | ] 351 | } 352 | ], 353 | "source": [ 354 | "# %load list-sections.py\n", 355 | "# Find objects in lists\n", 356 | "\n", 357 | "groceries = ['ham','eggs','cheese']\n", 358 | "flowers = ['rose','violet','daisy']\n", 359 | "primes = [2,3,5,7,11,13]\n", 360 | "\n", 361 | "print(groceries[1])\n", 362 | "\n", 363 | "print(primes[2:4])\n", 364 | "\n", 365 | "print(flowers[1:])\n", 366 | "\n", 367 | "print(primes[:3])\n", 368 | "\n", 369 | "# Add and remove items in lists\n", 370 | "\n", 371 | "flowers.append('buttercup')\n", 372 | "print(flowers)\n", 373 | "\n", 374 | "groceries.remove('ham')\n", 375 | "print(groceries)\n" 376 | ] 377 | }, 378 | { 379 | "cell_type": "code", 380 | "execution_count": null, 381 | "metadata": { 382 | "collapsed": true 383 | }, 384 | "outputs": [], 385 | "source": [ 386 | "# %load dicts.py\n", 387 | "# Dictionaries\n", 388 | "\n", 389 | "# Let's make a phone book\n", 390 | "\n", 391 | "phone_book = {'Alice':199933355555,\n", 392 | " 'Bob':14446669999,\n", 393 | " 'Rilke':18884321111,\n", 394 | " 'Goethe':12223334444}\n", 395 | "\n", 396 | "print(phone_book['Alice'])\n", 397 | "\n", 398 | "def look_up_number(name):\n", 399 | " print(phone_book[name])\n", 400 | "\n", 401 | "look_up_number('Rilke')\n", 402 | "look_up_number('Goethe')\n" 403 | ] 404 | }, 405 | { 406 | "cell_type": "code", 407 | "execution_count": null, 408 | "metadata": { 409 | "collapsed": true 410 | }, 411 | "outputs": [], 412 | "source": [ 413 | "# %load import_library.py\n", 414 | "# Importing libraries\n", 415 | "\n", 416 | "import random\n", 417 | "\n", 418 | "print(random.randint(1,100))\n", 419 | "\n", 420 | "def roll_dice(number_of_dice):\n", 421 | " for x in range(0,number_of_dice):\n", 422 | " print(random.randint(1,6))\n", 423 | "\n", 424 | "roll_dice(5)\n" 425 | ] 426 | }, 427 | { 428 | "cell_type": "code", 429 | "execution_count": null, 430 | "metadata": { 431 | "collapsed": true 432 | }, 433 | "outputs": [], 434 | "source": [] 435 | } 436 | ], 437 | "metadata": { 438 | "kernelspec": { 439 | "display_name": "Python 3", 440 | "language": "python", 441 | "name": "python3" 442 | }, 443 | "language_info": { 444 | "codemirror_mode": { 445 | "name": "ipython", 446 | "version": 2 447 | }, 448 | "file_extension": ".py", 449 | "mimetype": "text/x-python", 450 | "name": "python", 451 | "nbconvert_exporter": "python", 452 | "pygments_lexer": "ipython2", 453 | "version": "2.7.6" 454 | } 455 | }, 456 | "nbformat": 4, 457 | "nbformat_minor": 0 458 | } 459 | -------------------------------------------------------------------------------- /sections/ask_csv.py: -------------------------------------------------------------------------------- 1 | import csv 2 | 3 | file = open('nypl_items.csv', 'r') 4 | entries = csv.DictReader(file) 5 | 6 | dictionary = {} 7 | 8 | for row in entries: 9 | dictionary[row['id']] = row['Title'] 10 | 11 | while 1: 12 | id = input("Please enter an ID number: ") 13 | print(dictionary[id]) 14 | -------------------------------------------------------------------------------- /sections/conditionals.md: -------------------------------------------------------------------------------- 1 | [<<< Previous](loops.md) | [Next >>>](input.md) 2 | 3 | # Conditionals 4 | 5 | Conditionals allow programs to change their behavior based on whether some statement is true or false. Let's try this out by writing a script that will give different outputs based on the weather: 6 | 7 | ``` 8 | weather = "sunny" 9 | 10 | if weather == "sunny": 11 | print("Bring your shades") 12 | else: 13 | print("I don't know what you should bring! I'm just a little program...") 14 | ``` 15 | 16 | In our first line, we set a variable `weather` to the string "sunny," representing what the weather is like outside. The `if` statement checks whether the variable weather is set to "sunny." If it is, the code in the block beneath is executed, so the text "Bring your shades" will be printed. 17 | 18 | The `else` statement handles any inputs that aren't "sunny"—the program merely prints out that it doesn't know what you should bring. Try this script out both with the variable set to "sunny" and the variable set to some other value. 19 | 20 | What if we want our program to handle other kinds of weather, giving different messages for each one? Other cases after the first `if` statement are handled with `elif`: 21 | 22 | ``` 23 | weather = "sunny" 24 | 25 | if weather == "sunny": 26 | print("Bring your shades") 27 | elif weather == "rainy": 28 | print("Bring your umbrella") 29 | elif weather == "snowy": 30 | print("Bring your wooly muffler") 31 | else: 32 | print("I don't know what you should bring! I'm just a little program...") 33 | ``` 34 | 35 | You can add as many `elif` statements as you need, meaning that conditionals in Python have one `if` statement, any number of `elif` statements, and one `else` statement that catches any input not covered by `if` or `elif`. Over the next sections, we'll work on improving this little application, making it able to handle user input directly. 36 | 37 | ## Challenge 38 | 39 | Add two more elif statements to this program to make it better able to handle different kinds of weather. 40 | 41 | [<<< Previous](loops.md) | [Next >>>](input.md) 42 | -------------------------------------------------------------------------------- /sections/csv.md: -------------------------------------------------------------------------------- 1 | [<<< Previous](motivate.md) | [Next >>>>](resources.md) 2 | 3 | ## Working with external files 4 | 5 | A common task in Python is to pull in and work with data from an external source, such as a spreadsheet or database. In this section, we'll use Python to open and read a `.csv` (plain text spreadsheet) file. 6 | 7 | ### Reading the .csv 8 | 9 | Let's write a short script that will open the `.csv` and read in the lines: 10 | 11 | ``` 12 | import csv 13 | 14 | file = open('nypl_items.csv', 'r') 15 | entries = csv.DictReader(file) 16 | ``` 17 | 18 | The `open` function with `r` reads a text file and pulls in its contents. (It can also be used to write to a text file.) 19 | 20 | The `csv.DictReader()` function takes a text file in .csv format and parses it. It gives back a list of dictionaries that use the field name (such as "id" and "Title") as the key. The dictionaries look like this: 21 | 22 | ``` 23 | {'Contributor': 'Emmet, Thomas Addis, 1828-1919 | Cabot, George | Lowell, John', 'Place': 'Boston, Mass.', 'id': '794', 'Description': 'Introduces Mr. [Jonathan?] Dwight, of Springfield.', 'Subject': '', 'Digital': 'http://digitalcollections.nypl.org/items/8ea65050-c52d-012f-b37d-58d385a7bc34', 'Title': 'Letter to George Cabot, Beverly [Mass.]', 'Note': '', 'Publisher': '', 'Date': '1785-07-02', 'Genre': '', 'Language': '', 'Resource': 'text'} 24 | ``` 25 | 26 | Let's try printing out only titles: 27 | 28 | ``` 29 | import csv 30 | 31 | file = open('nypl_items.csv', 'r') 32 | entries = csv.DictReader(file) 33 | 34 | for row in entries: 35 | print(row['Title']) 36 | ``` 37 | 38 | Like before, you may need to use `Control-c` to cancel the printout. 39 | 40 | OK, let's try something a little more involved. What if I want all the entries that are chromolithographs? (I'm not even sure what chromolithographs are, but they sound awesome...) Let's say that this time we also want both the title of the entry and also its URL on the NYPL website, so we can check them out. 41 | 42 | ``` 43 | import csv 44 | 45 | file = open('nypl_items.csv', 'r') 46 | entries = csv.DictReader(file) 47 | 48 | 49 | for row in entries: 50 | if row['Genre'] == 'Chromolithographs': 51 | print(row['Title'], row['Digital']) 52 | ``` 53 | 54 | ### Challenges 55 | 56 | 1. Can you figure out a way to find out how many chromolithographs are in the NYPL .csv file? Two ways to do this would be to add the items to a list and then use `len()`, or to create a variable that gets bigger as the program loops. You might want to collaborate with your tablemates on this one. 57 | 58 | 2. Write a short program that asks the user for the ID number of an entry and returns the title. This is pretty hard, so feel free to take a peek at the [solution](ask_csv.py). 59 | 60 | [<<< Previous](motivate.md) | [Next >>>>](resources.md) 61 | -------------------------------------------------------------------------------- /sections/google.md: -------------------------------------------------------------------------------- 1 | [<<< Previous](input.md) | [Next >>>](motivate.md) 2 | 3 | ## Finding Answers with Google 4 | 5 | Our weather app is working pretty well, but you may have noticed that it's case sensitive: 6 | 7 | ``` 8 | What is the weather like today? snowy 9 | Bring your wooly muffler 10 | What is the weather like today? SNOWY 11 | I don't know what you should bring! I'm just a little program... 12 | ``` 13 | 14 | How could we fix our program to handle cases like this? We could add a bunch of new `elif` statements, like this: 15 | 16 | ``` 17 | [...] 18 | elif weather == "snowy": 19 | print("Bring your wooly muffler") 20 | elif weather == "SNOWY": 21 | print("Bring your wooly muffler") 22 | [...] 23 | ``` 24 | 25 | This is a lot of work, and it's a pretty ugly solution. If we wanted to add more cases to our program, we would have to write them in twice every time, and it still wouldn't fix inputs like `Snowy`. The best way to improve our program would be to convert the input to lower case before we send it to our `if/else` block. 26 | 27 | ### Googling for answers 28 | 29 | Even if you're a super rad Python programmer, you're not going to remember every function name or how to do things you might not have touched in awhile. One thing programmers get very good at is googling for answers. In fact, this is arguably the most important skill in modern-day programming. So let's use Google to find out how to convert strings to lower case. 30 | 31 | Let's try the search term make string lowercase Python: 32 | 33 | 34 |

35 | 36 | ![make string lower case Python Google search](google_search.png) 37 | 38 |

39 | 40 | Notice that the first result is from a site called Stack Overflow. This is a questions and answers site for programmers that usually has strong answers to questions about Python. 41 | 42 |

43 | 44 | ![Google search results with stack overflow answer on top](google_result.png) 45 | 46 |

47 | 48 | On the Stack Overflow page, take a quick look at the question to make sure it's relevant to your problem. However, we need to scroll down to the answers to find what we're looking for: 49 | 50 |

51 | 52 | ![stack overflow answer for making strings lowercase. the answer says to use string.lower()](stack_overflow.png) 53 | 54 |

55 | 56 | Also notice the snarky debate below! Another "feature" of Stack Overflow. 57 | 58 | ### Implementing our answer 59 | 60 | According to this answer, we can make a string lowercase by adding `.lower()` to the end of it, like this: 61 | 62 | ``` 63 | >>> "SNOWY".lower() 64 | 'snowy' 65 | ``` 66 | 67 | OK, that seems to work, even if we don't really know what's going on with that dot. Let's incorporate this transformation into our weather app: 68 | 69 | ``` 70 | while True: 71 | weather = input("What is the weather like today? ") 72 | weather = weather.lower() 73 | 74 | if weather == "sunny": 75 | print("Bring your shades") 76 | elif weather == "quit": 77 | break 78 | elif weather == "rainy": 79 | print("Bring your umbrella") 80 | elif weather == "snowy": 81 | print("Bring your wooly muffler") 82 | else: 83 | print("I don't know what you should bring! I'm just a little program...") 84 | ``` 85 | 86 | This new script should handle any combination of upper or lowercase characters. The new second line sets the weather variable to a new value, `weather.lower()`, which is a lowercase version of the original input. 87 | 88 | There's no shame in googling for answers! Error messages are especially useful to google when you run into them. Keep an eye out for Stack Overflow answers, as they tend to have useful examples. The [official Python documentation](https://docs.python.org/3/) will also frequently come up, but I would recommend avoiding it as a resource until you have more programming experience. It's a great resource, but the way information is presented can be confusing until you get the hang of reading documentation. 89 | 90 | ## Challenge 91 | 92 | 1. Is there something you would like to do with Python that we haven't covered yet? Do you find some language feature confusing? Take a minute now to use Google to ask a question about Python. If you can't think of something to google, look up how to append items to lists. 93 | 94 | 2. (optional) OK, I told you not to look at the Python documentation. But doesn't that make you really want to go look at the Python documentation? How bad could this "documentation" really be? What terrible secrets might it hold? 95 | 96 | Fine. Have a look at the [Python documentation on built-in functions](https://docs.python.org/3/library/functions.html). Don't say I didn't warn you. 97 | 98 | [<<< Previous](input.md) | [Next >>>](motivate.md) 99 | -------------------------------------------------------------------------------- /sections/google_result.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/smythp/intro-python-workshop/945d1d1e2f894b3b522ed119a1697e170113ed55/sections/google_result.png -------------------------------------------------------------------------------- /sections/google_search.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/smythp/intro-python-workshop/945d1d1e2f894b3b522ed119a1697e170113ed55/sections/google_search.png -------------------------------------------------------------------------------- /sections/grok.md: -------------------------------------------------------------------------------- 1 | ## Grok 2 | 3 | Grok is a word that appears in Robert Heinlein's novel *Stranger in a Strange Land*. Literally, it means "to drink." Metaphorically, it means to internalize something—to make it part of yourself. Programmers have picked up the word *grok* and use it to indicate a deep understanding of a concept. 4 | 5 | You certainly don't have to understand programming concepts deeply to get a lot of use out of programming. However, sometimes taking some time out to step back and learn the ins and outs of an idea will allow you to avoid hitting cognitive roadblocks, making it possible to write and understand more complex programs. 6 | 7 | If you find yourself stressed out by working with code you don't understand, break it down into compoenents. Then write short throwaway programs, one to five lines, that explore the concepts or language features that you don't fully understand. When you grok the components, you'll be better prepared to tackle the larger whole. 8 | 9 | [Grok on Wikipedia](https://en.wikipedia.org/wiki/Grok) 10 | [Grok on the jargon file](http://www.catb.org/jargon/html/G/grok.html) 11 | -------------------------------------------------------------------------------- /sections/input.md: -------------------------------------------------------------------------------- 1 | [<<< Previous](conditionals.md) | [Next >>>](google.md) 2 | 3 | ## Input 4 | 5 | **Note:** If you're using Python 2.7, replace all `input()` functions in the code below with `raw_input()`. You can check your version by running `python --version` in the command line. 6 | 7 | Python allows you to take input directly from the user using the `input` function. Let's use it to improve our weather application by asking for the weather before displaying the output. 8 | 9 | ``` 10 | weather = input("What is the weather like today? ") 11 | 12 | if weather == "sunny": 13 | print("Bring your shades") 14 | elif weather == "rainy": 15 | print("Bring your umbrella") 16 | elif weather == "snowy": 17 | print("Bring your wooly muffler") 18 | else: 19 | print("I don't know what you should bring! I'm just a little program...") 20 | ``` 21 | 22 | When you run this program, Python should ask you for some input with the prompt `What is the weather like today?` (The space before the second `"` makes the prompt look more tidy in the console.) It will then return some advice based on the input. Try running it now. 23 | 24 | ### Asking repeatedly 25 | 26 | What if we want Python to keep asking for input instead of exiting after the first question is answered? For that, we can use something called a while loop. 27 | 28 | Remember our for loop? Instead of iterating through a list like the for loop, our while loop will continue to execute as long as a certain condition is true. Here's a very simple while loop that will run forever until you quit it manually. 29 | 30 | ``` 31 | while True: 32 | print("Oh no! I'm stuck...") 33 | ``` 34 | 35 | In the terminal, you can escape from this endless loop by pressing `Control-c` on your keyboard. 36 | 37 | Let's apply the while loop to our weather app: 38 | 39 | ``` 40 | while True: 41 | weather = input("What is the weather like today? ") 42 | 43 | if weather == "sunny": 44 | print("Bring your shades") 45 | elif weather == "rainy": 46 | print("Bring your umbrella") 47 | elif weather == "snowy": 48 | print("Bring your wooly muffler") 49 | else: 50 | print("I don't know what you should bring! I'm just a little program...") 51 | ``` 52 | 53 | Notice that we had to shift everything over one tab to fit it in the `while` block. Now our program will ask us for input again and again, and give us different answers each time. 54 | 55 | Let's add one more feature: an `elif` statement that will break us out of the loop and end the program: 56 | 57 | ``` 58 | while True: 59 | weather = input("What is the weather like today? ") 60 | 61 | if weather == "sunny": 62 | print("Bring your shades") 63 | elif weather == "quit": 64 | break 65 | elif weather == "rainy": 66 | print("Bring your umbrella") 67 | elif weather == "snowy": 68 | print("Bring your wooly muffler") 69 | else: 70 | print("I don't know what you should bring! I'm just a little program...") 71 | ``` 72 | 73 | The `break` command ends the current loop early, ending the program when "quit" is given as input. 74 | 75 | ### Challenge 76 | 77 | 1\. How much of the code above do you understand? Even if you do kind of understand it, do you "grok" it—that is, *really* understand it? 78 | 79 | Open up your REPL (type `python` at the `$` prompt). Play around with `input()` a bit until you understand it's behavior really well. Write a two-line program in the REPL or in a script that takes some input and echoes it back to the user. 80 | 81 | Alternatively, mess around with `while`. Try using things other than `True` and see if the code in the loop runs. If you can, write a while loop that prints out the numbers from 1 to 10 and stops. 82 | 83 | 2\. (optional) Read a little about the weird word [grok](grok.md). 84 | 85 | [<<< Previous](conditionals.md) | [Next >>>](google.md) 86 | -------------------------------------------------------------------------------- /sections/installation.md: -------------------------------------------------------------------------------- 1 | [Next >>>](repl.md) 2 | 3 | ### Installation 4 | 5 | For these exercises, we will be using Anaconda, a version of Python that comes packaged with useful libraries for working with natural language and scientific data. 6 | 7 | To download Anaconda, [follow this link](https://www.continuum.io/downloads) and click the button for your operating system and Python 3.x (3.6 at the time of this writing). You want the 64-bit, graphical installer version. 8 | 9 | After installation, to test that Anaconda is working correctly, type 10 | 11 | $ python --version 12 | 13 | in your terminal. If Anaconda is working, your output should look like this: 14 | 15 | Python 3.6.4:: Anaconda 2.5.0 (64-bit) 16 | 17 | Note that to get this output you may need to refresh your terminal by typing `exec $SHELL` in the prompt (including the `$`) or by closing and reopening the terminal. 18 | 19 | [Next >>>](repl.md) 20 | -------------------------------------------------------------------------------- /sections/loop.py: -------------------------------------------------------------------------------- 1 | prime_numbers = [2, 3, 5, 7, 11] 2 | 3 | for num in prime_numbers: 4 | print(num * num) 5 | -------------------------------------------------------------------------------- /sections/loops.md: -------------------------------------------------------------------------------- 1 | [<<< Previous](run.md) | [Next >>>](conditionals.md) 2 | 3 | # Lists and Loops 4 | 5 | ## Lists 6 | 7 | Remember lists? They look like this: 8 | 9 | flowers = ['rose', 'violet', 'buttercup'] 10 | 11 | For now, let's just create a list and print it out. Our script will look like this: 12 | 13 | ``` 14 | flowers = ['rose', 'violet', 'buttercup'] 15 | print(flowers) 16 | ``` 17 | 18 | Save this to a new file called `loop.py` and run it with `python loop.py`. You should see the list printed out in the terminal. 19 | 20 | So far, we've only learned one function: `type()`. Let's try out another: 21 | 22 | ``` 23 | flowers = ['rose', 'violet', 'buttercup'] 24 | # print(flowers) 25 | 26 | list_length = len(flowers) 27 | 28 | print(list_length) 29 | ``` 30 | 31 | The `len()` function returns the number of items in a list or the number of characters in a string. 32 | 33 | Notice that, if you run the code above, you won't see the `flowers` list printed out. That's because that line has become a comment. If you put a `#` (hash or pound) at the beginning of a line, that line will be ignored. 34 | 35 | # List Indexing 36 | 37 | A useful property of a list is the list index. This allows you to pick out an item from within the list by a number starting from zero: 38 | 39 | print(flowers[1]) # rose 40 | print(flowers[1]) # violet 41 | 42 | You can print out the last item in a list using negative numbers: 43 | 44 | print(flowers[-1]) # buttercup 45 | 46 | ## Loops 47 | 48 | What if we want to print out each item in the list separately? For that, we'll need something called a loop: 49 | 50 | ``` 51 | flowers = ['rose', 'violet', 'buttercup'] 52 | # print(flowers) 53 | for flower in flowers: 54 | print("My favorite flower is the", flower) 55 | ``` 56 | 57 | What's happening here? This kind of loop is called a "for" loop, and tells Python: "for each item in the list, do something." Let's break it down: 58 | 59 | ``` 60 | for in : 61 | 62 | ``` 63 | 64 | Indented code like this is known as a "code block." Python will run the code in the code block once for each item in the list. You can also refer to \ in the block. 65 | 66 | You can also perform more complicated operations. Let's tackle one in a challenge. 67 | 68 | ## Challenge 69 | 70 | Here's a list of numbers: 71 | 72 | ``` 73 | prime_numbers = [2, 3, 5, 7, 11] 74 | ``` 75 | 76 | Write some code to print out the square of each of these numbers. The solution is [here](loop.py), but you're not allowed to look at it until you've tried to solve it yourself for 3.5 minutes. Seriously. That's 210 seconds. 77 | 78 | ## Advanced Challenge 79 | 80 | First, ignore this challenge because it's too hard. Next, look up string formatting on Google and use it to write a loop that gives the following output: 81 | 82 | ``` 83 | The square of 2 is 4. 84 | The square of 3 is 9. 85 | The square of 5 is 25. 86 | The square of 7 is 49. 87 | The square of 11 is 121. 88 | ``` 89 | 90 | [<<< Previous](run.md) | [Next >>>](conditionals.md) 91 | -------------------------------------------------------------------------------- /sections/motivate.md: -------------------------------------------------------------------------------- 1 | [<<< Previous](google.md) | [Next >>>>](csv.md) 2 | 3 | ## A Little Motivation 4 | 5 | Early on, we learned a bit about lists, which look like this: 6 | 7 | ['rose', 'violet', 'buttercup'] 8 | 9 | We're going to create a small application that will print a random motivational saying every time a user presses `Enter`. Our first step will be to create a list of positive sayings: 10 | 11 | ``` 12 | motivational_phrases = [ 13 | "Importing modules is easy!", 14 | "Programming! Yay!", 15 | "You write lists like a pro!", 16 | ] 17 | ``` 18 | 19 | Lists open with a square bracket `[`, have items seperated with commas, and end with a square bracket `]`, like this: 20 | 21 | [1, 2, 3, 4, 5] 22 | 23 | Our positivity list above spreads the list out over multiple lines for greater readability, which is allowed in Python. Remember that you can change the strings in the list to whatever phrases you choose. 24 | 25 | ### Importing a module 26 | 27 | Now that we have our sayings, let's use it in conjunction with some functionality from a module that's built into Python: the `random` module. 28 | 29 | ``` 30 | import random 31 | 32 | motivational_phrases = [ 33 | "Importing modules is easy!", 34 | "Programming! Yay!", 35 | "You write lists like a pro!", 36 | ] 37 | 38 | print(random.choice(motivational_phrases)) 39 | ``` 40 | 41 | The `random.choice` function chooses a random item from a list and returns it. The `.` syntax indicates that the function is coming from the `random` library. 42 | 43 | 1. The real point of this section is to learn `import`, which is where Python really starts to get interesting. Python comes with many libraries (importable collections of code), and you can install many more. Think of something you're interested in doing (statistics, text analysis, web scraping, quantitative analysis, processing Excel/PDF/image files) and search google "\ python library". You're almost certain to find some useful results. 44 | 45 | 2. (optional) As with our weather app, this positive saying generator could be improved by making it so the program doesn't have to run again every time to get new output. Add a while loop for the final version. You can see a solution [here](motivation.py). 46 | 47 | [<<< Previous](google.md) | [Next >>>>](csv.md) 48 | -------------------------------------------------------------------------------- /sections/motivation.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | while True: 4 | motivational_phrases = [ 5 | "Importing modules is easy!", 6 | "Programming! Yay!", 7 | "You write lists like a pro!", 8 | ] 9 | 10 | # Because this is input, the user will 11 | # need to hit enter to see a new phrase 12 | input(random.choice(motivational_phrases)) 13 | -------------------------------------------------------------------------------- /sections/multiline.md: -------------------------------------------------------------------------------- 1 | ## Multi-line string 2 | 3 | Once you have your "Hello world!" program running, replace the text in your `hello.py` file with this: 4 | 5 | ``` 6 | print('''Mary had a little lamb, 7 | Its fleece was white as snow, 8 | And everywhere that Mary went, 9 | The lamb was sure to go.''') 10 | ``` 11 | 12 | Run the program again and you should see the poem as output over four lines. 13 | 14 | ### Why use triple quotes? 15 | 16 | There are four ways to create strings in Python: 17 | 18 | ``` 19 | 'Hello world!' 20 | "Hello world!" 21 | '''Hello world!''' 22 | """Hello world!""" 23 | ``` 24 | 25 | The first two examples allow you to create single-line strings. The last two allow you to create multi-line strings. Notice that you should not mix and match these opening and closing quotes, as you'll get an error: 26 | 27 | ``` 28 | >>> print("Hello world!') 29 | File "", line 1 30 | print("Hello world!') 31 | ^ 32 | SyntaxError: EOL while scanning string literal 33 | ``` 34 | 35 | You've probably already seen similar messages as you've tried the examples so far, but if not...congratulations on your first error! You'll see a lot of errors as you learn Python, and they're actually pretty helpful, so don't be afraid of them. We'll talk more about errors in the next section. 36 | 37 | ### Differences between the REPL and running scripts 38 | 39 | Remember how, in the REPL, we could do things like this? 40 | 41 | ``` 42 | >>> x = 5 43 | >>> x 44 | 5 45 | ``` 46 | 47 | In the REPL, the results after Python evaluates your input are automatically printed out for you. This is not the case with longer Python programs. If you want to see the output in the console, you'll need to use the `print()` function. (Notice that IPython cells are actually a beefed up version of the REPL that can take multiple lines, so if you're using the IPython method for running scripts, you can still do stuff like this.) 48 | -------------------------------------------------------------------------------- /sections/notes.md: -------------------------------------------------------------------------------- 1 | ### What was "print"? 2 | 3 | The `print()` statement you used in the last section is an example of a function. We'll talk more about functions later, but for now you can think of them as actions that are performed on a piece of data. The `print()` function operates on the data within the parentheses by printing that data to the screen. 4 | 5 | Let's try out another function that will help us to learn more about the kinds of data available to us in Python: 6 | 7 | 8 | ### IDE 9 | 10 | An IDE (Integrated Development Environment) is a program that can be used for both writing and running scripts, and they usually come with a number of specialized features. Python comes with its own IDE, but it only runs well on Windows and Linux, not on OSX. More powerful cross-platform IDEs for Python, such as [PyCharm](https://www.jetbrains.com/pycharm/) and [Spyder](https://pythonhosted.org/spyder/) will also allow you to write and run Python programs on your desktop. Check out these tutorials if you're interested in using an IDE to write and execute Python code: 11 | 12 | [IDLE tutorial (not recommended for OSX)](https://www.youtube.com/watch?v=lBkcDFRA958) 13 | [PyCharm Quickstart](https://www.jetbrains.com/help/pycharm/2016.1/quick-start-guide.html) 14 | [Spyder tutorial](http://datasciencesource.com/python-with-spyder-tutorial/) 15 | 16 | 17 | 18 | 19 | ### IPython Notebook 20 | 21 | IPython Notebooks are graphical interfaces to Python that run in the browser. To start a notebook, enter 22 | 23 | $ ipython notebook 24 | 25 | in your terminal. You should see messages appear in your terminal window, and your browser should open to a list of files. Once IPython is open in the browser, click `New` in the top right and select `Python` under `Notebook` from the dropdown menu. 26 | 27 | THe IPython interface consists of cells, which can contain text or Python code. In the first cell (the blank space next to the text that says `In [ ]`, enter the text 28 | 29 | print("Hello world!") 30 | 31 | then hit `Shift-Enter`. You should see the output `Hello world!` appear below. 32 | -------------------------------------------------------------------------------- /sections/repl.md: -------------------------------------------------------------------------------- 1 | [<<< Previous](installation.md) | [Next >>>](types.md) 2 | 3 | ## Interacting with Python 4 | 5 | To start an interactive session with Python, open your terminal and type 6 | 7 | $ python 8 | 9 | at the prompt. You should see something like this 10 | 11 | ``` 12 | Python 3.6.3 |Anaconda, Inc.| (default, Oct 13 2017, 12:02:49) 13 | [GCC 7.2.0] on Linux 14 | Type "help", "copyright", "credits" or "license" for more information. 15 | >>> 16 | ``` 17 | 18 | Unlike the normal `$` terminal prompt, the Python prompt looks like this: 19 | 20 | ``` 21 | >>> 22 | ``` 23 | 24 | Keep an eye on this, as a common early source of confusion is entering terminal commands into the Python prompt or entering Python commands into the terminal. 25 | 26 | ### A Little Math 27 | 28 | Let's try a little math at the Python prompt: 29 | 30 | ``` 31 | >>> 2 + 3 32 | 5 33 | >>> 14 - 10 34 | 4 35 | >>> 10 * 10 36 | 100 37 | >>> 6 / 3 38 | 2 39 | >>> 21 % 4 40 | 1 41 | ``` 42 | 43 | The first four operations above are addition, subtraction, multiplication, and division, respectively. The last operation is modulo, or mod, which returns the remainder after division. 44 | 45 | Note the way you interact with Python at the prompt. After entering an expression such as `2 + 3`, Python "evaluates" it to a simpler form, `5`, and then prints out the answer for you. This process is called the Read Eval Print Loop, or REPL. Reading takes commands from you, the input is evaluated or run, the result is printed out, and the prompt is shown again to wait for more input. The normal terminal (the one with the `$`) is another example of a REPL. 46 | 47 | The REPL is useful for quick tests and, later, can be used for exploring and debugging your programs interactively. 48 | 49 | ## Challenges 50 | 51 | 1. For a few minutes, practice moving in and out of Python's interactive mode (also known as the REPL). You can get out of Python by hitting `Control-d` or by typing `exit()`, and you can get back in by typing `python` at the `$` prompt. Remember that you're in the REPL when you see `>>>`, and you're in bash when you see the `$`. 52 | 2. One "operator" (math symbol) we didn't learn is the exponent—you know, "x raised to the power of..." If you were Guido van Rossum, the creator of Python, how would you define this operator? Look up the exponent operator in Python on Google and see how close you were. 53 | 54 | [<<< Previous](installation.md) | [Next >>>](types.md) 55 | -------------------------------------------------------------------------------- /sections/resources.md: -------------------------------------------------------------------------------- 1 | [<<< Previous](csv.md) 2 | 3 | ## Python resources 4 | 5 | [Learn Python the Hard Way](http://learnpythonthehardway.org/book/) - An example-driven introduction to Python. 6 | 7 | [How to Think Like a Computer Scientist - Python Edition](http://interactivepython.org/courselib/static/thinkcspy/index.html) - A good intro if you're also interested in learning basic computer science concepts. 8 | 9 | [Automate the Boring Stuff with Python](https://automatetheboringstuff.com/) - A fun book that teaches Python while automating some common (and annoying) tasks. 10 | 11 | [CodeAcademy: Python](http://www.codecademy.com/en/tracks/python) - An interactive tutorial for learning the basics of Python. (I recommend trying the books above first, as learning to use a text editor or IDE such as IPython or IDLE is an important part of the learning curve.) A good supplemental resource. 12 | 13 | [<<< Previous](csv.md) 14 | -------------------------------------------------------------------------------- /sections/run.md: -------------------------------------------------------------------------------- 1 | [<<< Previous](variables.md) | [Next >>>](loops.md) 2 | 3 | ## Running scripts 4 | 5 | So far, you've interacted with Python one line at a time in the REPL. For the rest of this session, we're going to write and execute longer programs. 6 | 7 | ### Your first script 8 | 9 | Open your text editor of choice (such as Sublime) and create a new file with this line: 10 | 11 | print("Hello world!") 12 | 13 | Save it with the name `hello.py` to a known location, such as your desktop. Open your terminal and move to the desktop directory: 14 | 15 | $ cd Desktop 16 | 17 | Once you're in the folder with your `hello.py` file, run it with: 18 | 19 | $ python hello.py 20 | Hello world! 21 | 22 | As above, you should see the text `Hello world!` appear as output. We needed the `print()` function here because, unlike in the REPL, things aren't automatically printed out when writing scripts. 23 | 24 | Congratulations! You've written your first script. That's kind of a big deal. 25 | 26 | ## Challenges 27 | 28 | 1. Rewrite your program so that you assign the message to a variable, then print the variable. This will make your program two lines instead of one. There's a fancy programmer word for rewriting your code without changing it's behavior—"refactoring." 29 | 30 | 2. (optional) Are you already getting sick of typing `python hello.py` again and again? Try typing `!!` in the command line (the `$`). This will run your last line of code again. 31 | 32 | 3. (even more optional) If you're on Windows and have a minute, try pressing the Windows button on your keyboard and searching for a program called `IDLE` that comes with Python. It's a special editor (or IDE) that lets you run Python code from inside it. You might like it more than git bash. 33 | 34 | ## A Note on Text 35 | 36 | Fundamentally, Python programs are just text files. You can write them in any text editor, like Sublime Text or Notepad on Windows. When you pass the text file to Python, it runs the code in the file one line at a time. There's nothing special about `.py` files, they're just regular text files. This makes them work well with command line tools like Git. The tools you've learned so far—the command line, Git, markdown, grep, Sublime—are all designed to work well together, and the medium through which they all work is plain text. 37 | 38 | [<<< Previous](variables.md) | [Next >>>](loops.md) 39 | -------------------------------------------------------------------------------- /sections/stack_overflow.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/smythp/intro-python-workshop/945d1d1e2f894b3b522ed119a1697e170113ed55/sections/stack_overflow.png -------------------------------------------------------------------------------- /sections/types.md: -------------------------------------------------------------------------------- 1 | [<<< Previous](repl.md) | [Next >>>](variables.md) 2 | 3 | ## Types 4 | 5 | Types are classifications that let the computer know how a programmer intends to use a piece of data. You can just think of them as, well, types of data. 6 | 7 | We've already seen one type in the last section: the integer. In this section, we'll learn four more: the floating point number, the string, the boolean, and the list. 8 | 9 | Enter these lines as you see them below: 10 | 11 | ``` 12 | >>> type(1) 13 | 14 | >>> type(1.0) 15 | 16 | >>> type("Hello there!") 17 | 18 | >>> type(True) 19 | 20 | >>> type([1, 2, 3]) 21 | 22 | ``` 23 | 24 | Each of these represents a different type: 25 | 26 | Float: `1.0` 27 | 28 | Floats are numbers with decimals, and are treated a little differently than integers. 29 | 30 | String: `"Hello there!"` 31 | 32 | Strings are arbitrary sets of characters, such as letters and numbers. You can think of them as a way to store text. 33 | 34 | Boolean: `True` and `False` 35 | 36 | Boolean is a fancy term for values representing "true" and "false," or "truthiness" and "falsiness." 37 | 38 | List: `[1, 2, 3]` 39 | 40 | A list is an ordered collection of values. You can put any type in a list: `["rose", "daisy", "buttercup"]` is also a valid list. 41 | 42 | Don't worry about trying to actively remember these types. We'll be working with each in turn in the following sections. 43 | 44 | ## What's the deal with type()? 45 | 46 | `type()` is a function. You can think of functions in Python in a few different ways: 47 | 48 | 1. A way of doing something in Python. 49 | 2. A way of saving some code for reuse. 50 | 3. A way of taking an input, transforming that input, and returning an output. The input goes in the parentheses `()`. 51 | 52 | These are all valid ways of thinking about functions. We'll be learning more about functions in later sections. 53 | 54 | [<<< Previous](repl.md) | [Next >>>](variables.md) 55 | -------------------------------------------------------------------------------- /sections/variables.md: -------------------------------------------------------------------------------- 1 | [<<< Previous](types.md) | [Next >>>](run.md) 2 | 3 | ## Variables 4 | 5 | A variable is a symbol that refers to an object, such as a string, integer, or list. If you're not already at the Python prompt, open your terminal and type `python` at the `$`. You're in the right place when you see `>>>`. 6 | 7 | Try these commands in order: 8 | 9 | ``` 10 | >>> x = 5 11 | >>> x 12 | 5 13 | >>> x + 10 14 | 15 15 | >>> y = "hello" 16 | >>> y 17 | 'hello' 18 | >>> y + " and goodbye" 19 | 'hello and goodbye' 20 | ``` 21 | 22 | As you can see above, the `=` sign lets you assign symbols like `x` and `y` to data. 23 | 24 | Variables can be longer words as well: 25 | 26 | ``` 27 | >>> breakfast = ['ham', 'eggs', 'toast'] 28 | >>> breakfast 29 | ['ham', 'eggs', 'toast'] 30 | >>> type(breakfast) 31 | 32 | ``` 33 | 34 | Variables can have letters, numbers, and underscores, but should start with a letter. 35 | 36 | ### Challenge 37 | 38 | So I just told you that variables shouldn't start with a number or an underscore. What does that even mean? Will your computer explode if you write `3_flower = "buttercup"`? 39 | 40 | Only one way to find out. Try giving weird names to variables and see if you can learn a bit about the rules. 41 | 42 | [<<< Previous](types.md) | [Next >>>](run.md) 43 | -------------------------------------------------------------------------------- /update.sh: -------------------------------------------------------------------------------- 1 | git add -A 2 | git commit -m "automatic update" 3 | git push 4 | --------------------------------------------------------------------------------