├── Exercises ├── ExerciseModule1End.py ├── Exercises1.py ├── Exercises2.py ├── Exercises3 │ ├── ADream.txt │ ├── BooksRead.csv │ ├── Exercises3.py │ ├── HumptyDumpty.txt │ ├── copy_file.py │ ├── count_words.py │ ├── holidays.csv │ ├── lwc.py │ ├── menu.csv │ ├── myphones.csv │ ├── phones.csv │ ├── print_file.py │ ├── weights.csv │ ├── xhumpty.txt │ ├── xmajor │ └── xweights.csv └── Exercises4 │ ├── Exercises4.py │ ├── myphones.csv │ └── phones.py ├── Programming-Assignment ├── Problem-Set-3 │ ├── HumptyDumpty.txt │ ├── ProblemSet3.py │ ├── flowers.csv │ ├── humptylength.txt │ └── problem3_6.py ├── ProblemSet1.py ├── ProblemSet2.py ├── ProblemSet3.py └── ProblemSet4 │ ├── ProblemSet4.py │ ├── myphones.csv │ └── phones.py └── README.md /Exercises/ExerciseModule1End.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Sat Oct 15 17:11:51 2016 4 | 5 | @author: Abdullah A. Alam 6 | """ 7 | 8 | # - ExerciseModule1End.py *- coding: utf-8 -*- 9 | """ Find and correct all the errors in the following Python functions. 10 | Upload your file. """ 11 | """ 12 | Exercise 1 13 | """ 14 | #%% 15 | def print_phrase(): 16 | phrase = "Now is the time" 17 | print (phrase) 18 | #%% 19 | """ 20 | Exercise 2 21 | """ 22 | #%% 23 | def favorite_sport(favorite): 24 | sport = "favorite" 25 | print("Your favorite sport is",sport) 26 | #%% 27 | """ 28 | Exercise 3 29 | """ 30 | #%% 31 | def username(yourname): 32 | print("Your name is ",yourname) 33 | #%% 34 | """ 35 | Exercise 4 36 | """ 37 | #%% 38 | def compare_numbers(x,y): 39 | if x == y: 40 | print("they are equal") 41 | else: 42 | print(x, "and", y, 'are not equal') 43 | #%% 44 | """ 45 | Exercise 5 46 | """ 47 | #%% 48 | def count_by_5(): 49 | """ Count from 5 to 100 in steps of 5 """ 50 | """ 5 10 15 20 25 30 35 40 45 50 55 60 65 70 75 80 85 90 95 100 """ 51 | print ('Count from 5 to 100 in steps of 5') 52 | ct = 5 53 | while ct <= 100: 54 | print(ct, end = " ") 55 | ct = ct + 5 56 | print() 57 | #%% -------------------------------------------------------------------------------- /Exercises/Exercises1.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Sat Oct 15 00:04:07 2016 4 | 5 | @author: Abdullah A. Alam 6 | """ 7 | 8 | # -Exercises1.py *- coding: utf-8 -*- 9 | 10 | 11 | 12 | 13 | 14 | """ 15 | Student needs: 16 | Exercises1.py 17 | 18 | We will mainly use the following window panes: IPython Console, Editor, 19 | File Explorer, and Object Inspector. 20 | #%% breaks up the Editor document into cells. The green triangle in the tool 21 | bar executes the entire file (after saving it), Ctrl-Enter (Command-Return on a 22 | Mac) executes only the cell that the cursor is in (but does not save). 23 | 24 | Instructions on changing working directory in Spyder: At the top on the right 25 | you will see a path, the working directory. To its right is a yellow file 26 | folder. Click it and you can change the working directory. When you do, you 27 | can click the icon to the right of that and set that path as the current 28 | console's new working directory. Then all the panes: Editor, IPython Console, 29 | and File Explorer are pointed to this current working directory. 30 | """ 31 | 32 | """ 33 | Quick look at arithmetic operations 34 | +, -, *, **, /, //, % 35 | These add, subtraction, multiple, exponentiate, divide, integer divide (drops 36 | fractional part), computes remainder on division for integers. 37 | Try some examples interactively in IPython window on lower right. 38 | """ 39 | #%% 40 | def hello(): 41 | """ prints hello, world """ 42 | print("Hello, world!") 43 | 44 | #%% 45 | def areacircle(radius): 46 | """ Computes the area of a circle of the given radius """ 47 | area = 3.14*radius**2 48 | print("The area of a circle of radius",radius,"is", area) 49 | 50 | #%% 51 | 52 | """ 53 | Exercise: 54 | Write a function 'def areatriangle(b,h)' to compute the area 55 | of a triangle: formula is area = .5*b*h. 56 | Output should look like: 57 | The area of a triangle of base 3 and height 5 is 7.5 58 | 59 | You can test your function by executing the following code: 60 | """ 61 | #%% 62 | # The following will test areatriangle() 63 | areatriangle(3,5) 64 | areatriangle(2,20) 65 | #%% 66 | """ 67 | Solution: 68 | """ 69 | #%% 70 | def areatriangle(b, h): 71 | """ Computes the area of a triangle of the given base and height """ 72 | area = .5*b*h 73 | print("The area of a triangle of base", b, "and height", h, "is", area) 74 | 75 | 76 | #%% 77 | """ 78 | End solution 79 | """ 80 | """ 81 | To make a string we may use ' or ". Either works equally well. But if the 82 | string contains one, we need to use the other: 83 | """ 84 | #%% 85 | name = "His name is Conan O'Brien" 86 | cat = 'My cat is named "Butters"' 87 | print(name) 88 | print(cat) 89 | #%% 90 | """ 91 | If you need both a ' and a " in your string, you can use the escape 92 | character \ which tells Python that the following character is to be taken 93 | as the literal character and is not a quote to delimit the string. See it 94 | in action escaping the " below: 95 | """ 96 | #%% 97 | both = "My cat's name is \"Butters\"" 98 | print(both) 99 | #%% 100 | 101 | def fahrenheit_to_celsius(temp): 102 | """ Converts Fahrenheit temperature to Celsius. 103 | Formula is 5/9 of temp minus 32 """ 104 | # Note that this line is not executed 105 | # end='' keeps print from starting a new line. 106 | newTemp = 5*(temp-32)/9 107 | print("The Fahrenheit temperature",temp,"is equivalent to",newTemp,end='') 108 | print(" degrees Celsius") 109 | 110 | #%% 111 | 112 | """ 113 | Exercise: 114 | Write a function 'def celsius_to_fahrenheit(temp)' to convert Celsius 115 | to Fahrentheit temperature. The formula is (9/5) times temp plus 32. 116 | Print the output in the form: 117 | The Celsius temperature 50.0 is equivalent to 122.0 degrees Fahrenheit. 118 | """ 119 | #%% 120 | # The following will test the above function 121 | celsius_to_fahrenheit(100) 122 | celsius_to_fahrenheit(0) 123 | celsius_to_fahrenheit(50.) 124 | #%% 125 | """ 126 | Solution: 127 | """ 128 | #%% 129 | def celsius_to_fahrenheit(temp): 130 | """ Converts Celsius to Fahrentheit temperature. The formula is (9/5) times 131 | temp plus 32 """ 132 | # Note that this line is not executed 133 | # end='' keeps print from starting a new line. 134 | newTemp = temp*(9/5)+32 135 | print("The Celsius temperature",temp,"is equivalent to",newTemp,end='') 136 | print(" degrees Fahrenheit.") 137 | 138 | 139 | 140 | 141 | 142 | #%% 143 | """ 144 | End solution 145 | """ 146 | #%% 147 | 148 | def name(): 149 | """ Input first and last name, combine to one string and print """ 150 | fname = input("Enter your first name: ") 151 | lname = input("Enter your last name: ") 152 | fullname = fname + " " + lname 153 | 154 | print("Your name is:", fullname) 155 | 156 | #%% 157 | """ 158 | Exercise: 159 | Extend the name function written in class to include the city and state. 160 | That is, ask two more questions to get the city and the state you live in. 161 | Print where you are from on a new line. Put the customary comma between 162 | city and state. to save time, here is the starting function. 163 | Your run should look like the following (even if this is not the customary 164 | way in your country): 165 | Enter your first name: Bill 166 | 167 | Enter your last name: Boyd 168 | 169 | Enter the city you live in: Middletown 170 | 171 | Enter the state you live in: CT 172 | Your name is: Bill Boyd 173 | You live in: Middletown, CT 174 | 175 | """ 176 | """ 177 | Solution: 178 | """ 179 | #%% 180 | def name(): 181 | """ Input first and last name, combine to one string and print 182 | Also, input the city and state and print.""" 183 | fname = input("Enter your first name: ") 184 | lname = input("Enter your last name: ") 185 | fullname = fname + " " + lname 186 | city = input("Enter the city you live in: ") 187 | state = input("Enter the state you live in: ") 188 | address = city + ", " + state 189 | 190 | print("Your name is:", fullname) 191 | print("You live in:", address) 192 | 193 | 194 | #%% 195 | """ 196 | End solution 197 | """ 198 | #%% 199 | def if_statement(): 200 | """ Three slightly difference versions of if: if, if-else, if-elif-else""" 201 | x = 5 202 | y = 0 203 | z = 0 204 | if x > 0: 205 | print("x is positive") 206 | 207 | if y > 0: 208 | print("y is positive") 209 | else: 210 | print("y is not positive") 211 | 212 | # elif can be repeated as often as necessary 213 | if z > 0: 214 | print("z is positive") 215 | elif z < 0: 216 | print("z is negative") 217 | else: 218 | print("z must be 0") 219 | 220 | #%% 221 | """ 222 | Python uses '=' for assignment and '==' for testing equality. Also '!=' is 223 | used to test for non-equality. Try these examples: 224 | """ 225 | #%% 226 | x = 5 227 | y = 5 228 | z = 6 229 | #%% 230 | """ 231 | Now we try to following: 232 | """ 233 | print("x is equal to y: ", x == y) 234 | print("x is not equal to y: ", x != y) 235 | print("x is equal to z: ", x == z) 236 | print("x is not equal to z: ", x != z) 237 | #%% 238 | """ 239 | The following function uses an 'if' statement. Note that the indention marks 240 | the scope of the 'if', 'elif', 'else' actions. 241 | """ 242 | def area(type_, x): 243 | """ Computes the area of a square or circle. 244 | type_ must be the string "circle or the string "square" 245 | We use type_ here, because type is a Python keyword. """ 246 | if type_ == "circle": 247 | area = 3.14*x**2 248 | print(area) 249 | elif type_ == "square": 250 | area = x**2 251 | print(area) 252 | else: 253 | print("I don't know that one.") 254 | #%% 255 | """ 256 | Exercise: 257 | Write a function absolutevalue(num) that computes the absolute value of 258 | a number. You will need to use an 'if' statement. Remember if a number is 259 | less than zero then you must multiply by -1 to make it greater than zero. 260 | Give output in the form: 261 | 262 | The absolute value of -5 is 5 263 | """ 264 | #%% 265 | # Test runs 266 | absolutevalue(5) 267 | absolutevalue(-5) 268 | absolutevalue(4-4) 269 | #%% 270 | """ 271 | Solution: 272 | """ 273 | #%% 274 | def absolutevalue(num): 275 | if num > 0: 276 | newAbs = abs(num) 277 | print("The absolute values of", num, "is", newAbs) 278 | else: 279 | newAbs = abs(num) 280 | print("The absolute value of", num, "is", newAbs) 281 | 282 | 283 | 284 | #%% 285 | """ 286 | End solution 287 | """ 288 | """ 289 | Example: The next three examples work with the 'input' statement and point out 290 | some of the things that you might need to be aware of in using one. It also 291 | shows how to use the 'print' statement without having a new line started at 292 | the end of that statement by using an 'end' argument in it. 293 | """ 294 | #%% 295 | def fahrenheit_to_celsius1(): 296 | """ BAD. Does not check input before using it. 297 | Input from keyboard, which is always a string and must often be 298 | converted to an int or float. 299 | Converts Fahrenheit temp to Celsius. 300 | """ 301 | 302 | temp_str = input("Enter a Fahrentheit temperature: ") 303 | temp = int(temp_str) 304 | newTemp = 5*(temp-32)/9 305 | print("The Fahrenheit temperature",temp,"is equivalent to ",end='') 306 | print(newTemp,"degrees Celsius") 307 | 308 | #%% 309 | """ 310 | Test the program above by entering a temperature such as 212. Also check what 311 | happens if you simply press enter. 312 | """ 313 | #%% 314 | def fahrenheit_to_celsius2(): 315 | """ IMPROVED. Does some checking of input before using it. 316 | Input from keyboard, which is always a string and must often be 317 | converted to an int or float. 318 | Converts Fahrenheit temp to Celsius. 319 | Uses 'if' to make sure an entry was made. 320 | """ 321 | 322 | temp_str = input("Enter a Fahrenheit temperature: ") 323 | if temp_str: 324 | temp = int(temp_str) 325 | newTemp = 5*(temp-32)/9 326 | print("The Fahrenheit temperature",temp,"is equivalent to ",end='') 327 | print(newTemp,"degrees Celsius") 328 | 329 | #%% 330 | """ 331 | Test the program above by entering the temperature 212 and also by simply 332 | pressing 'Enter' or 'Return' key. Note the improvement. Now try entering 'a'. 333 | """ 334 | #%% 335 | def fahrenheit_to_celsius3(): 336 | """ MORE IMPROVED. Does even more checking of input before using it. 337 | Input from keyboard, which is always a string and must often be 338 | converted to an int or float. 339 | Converts Fahrenheit temp to Celsius. 340 | Uses if to check whether input is a number and then uses .isdigit() method 341 | of strings to check whether input is made of of digits. 342 | """ 343 | 344 | temp_str = input("Enter a Fahrentheit temperature: ") 345 | if temp_str: 346 | if temp_str.isdigit(): 347 | temp = int(temp_str) 348 | newTemp = 5*(temp-32)/9 349 | print("The Fahrenheit temperature",temp,"is equivalent to ",end='') 350 | print(newTemp,"degrees Celsius") 351 | else: 352 | print("You must enter a number. Bye") 353 | #%% 354 | """ 355 | Test the program above by entering the temperature 212, by simply pressing 356 | 'Enter' or 'Return' key, and by entering 'a'. Note the improvement. We will 357 | leave the function at this point though further improvements could be made. 358 | """ 359 | """ 360 | The following function uses integer division. 361 | """ 362 | #%% 363 | def inches_to_feet1(inches): 364 | """ converts inches to feet and inches """ 365 | feet = inches//12 # division by integer with fraction thrown away 366 | extra_inches = inches - 12*feet 367 | print(inches,"inches is",feet,"feet and",extra_inches,"inches") 368 | #%% 369 | 370 | """ 371 | Exercise: Rewrite inches_to_feet1(inches) calling it inches_to_feet2(inches) 372 | using % to compute the inches. Recall that 19 % 5 will give 4 (the remainder). 373 | Copy and paste the original into the solution area and modify to same typing 374 | time. 375 | """ 376 | """ 377 | Solution: 378 | """ 379 | #%% 380 | 381 | def inches_to_feet2(inches): 382 | """ converts inches to feet and inches """ 383 | feet = inches//12 # division by integer with fraction thrown away 384 | extra_inches = inches%12 385 | print(inches,"inches is",feet,"feet and", extra_inches,"inches") 386 | 387 | 388 | 389 | 390 | #%% 391 | """ 392 | End solution 393 | """ 394 | """ 395 | The 'while' loop. Loops are used to repeat actions and the scope of this 396 | repetition is indicated by the indention after the 'while' statement. 397 | """ 398 | #%% 399 | def cheer(): 400 | """ Prints 2 4 6 8, who do we appreciate .... Note that everything in 401 | the while loop is indented. The first line not indented is the first 402 | line following the while loop. """ 403 | ct = 2 404 | while ct <= 8: 405 | print(ct,end=" ") # end = " " keeps from starting a new line 406 | ct = ct + 2 407 | print() # now we'll start a new line 408 | print("Who do we appreciate?") 409 | print("COURSERA!") 410 | 411 | #%% 412 | """ 413 | Exercise: 414 | Write a function count_down() that starts at 10 and counts down to rocket 415 | launch. It's output should be 10 9 8 7 6 5 4 3 2 1 BLASTOFF! You can make 416 | all the numbers on the same line or different lines. Use a while loop. 417 | """ 418 | """ 419 | Solution: 420 | """ 421 | #%% 422 | def count_down(): 423 | """ Prints 10 9 8 7 6 5 4 3 2 1 BLASTOFF! Use a while loop. """ 424 | ct = 10 425 | while ct > 0: 426 | print(ct, end=" ") 427 | ct = ct - 1 428 | print() 429 | print("BLASTOFF!") 430 | 431 | 432 | 433 | 434 | 435 | 436 | 437 | #%% 438 | """ 439 | End solution 440 | """ 441 | """ 442 | The 'for' loop. This loop uses an iterator to determine how many times to go 443 | through the loop. The iterator we use below is 'range(start, stop, step)'. 444 | """ 445 | #%% 446 | def cheer2(): 447 | """ Same as cheer, but uses a for loop and range() 448 | range uses a start number, a stop number and a step size. """ 449 | for ct in range(2,9,2): 450 | print(ct,end=' ') 451 | print() 452 | print("Who do we appreciate?") 453 | print("COURSERA!") 454 | 455 | #%% 456 | """ 457 | Exercise: 458 | Write a function countdown1() that starts at 10 and counts down to rocket 459 | launch. It's output should be 10 9 8 7 6 5 4 3 2 1 BLASTOFF! You can make 460 | all the numbers on the same line or different lines. Use a 'for' loop and 461 | range(). range has a start and a stop and a step that MAY BE NEGATIVE. 462 | """ 463 | """ 464 | Solution: 465 | """ 466 | #%% 467 | def countdown1(): 468 | for ct in range(10, 0, -1): 469 | print(ct, end=' ') 470 | print() 471 | print("BLASTOFF!") 472 | 473 | 474 | 475 | #%% 476 | """ 477 | End solution 478 | """ 479 | 480 | #%% 481 | """ 482 | Some of our exercises involve finding and fixing errors in code. 483 | Here is an example. Can you see the errors (there are two)? Note that the 484 | editor is pointing out one line with troubles. 485 | You can find the error by reading the example carefully, or trying to make 486 | it work by using Shift-Enter to insert the function into IPython and reading 487 | what error it gives or trying to run the function. 488 | """ 489 | #%% 490 | def favorite(): 491 | my_toy = input("What is my favorite toy? ") 492 | print("Your favorite toy is", my-toy) 493 | #%% 494 | """ 495 | My solution: 496 | """ 497 | 498 | def favorite(): 499 | my_toy = input("What is my favorite toy? ") 500 | print("Your favorite toy is", my_toy) 501 | 502 | 503 | 504 | 505 | 506 | #%% 507 | """ 508 | end solution 509 | """ -------------------------------------------------------------------------------- /Exercises/Exercises2.py: -------------------------------------------------------------------------------- 1 | # - Exercises2.py *- coding: utf-8 -*- 2 | 3 | 4 | 5 | 6 | 7 | 8 | """ 9 | Python has lists. The empty list is []. The following is a list of one 10 | item ["a"] and so is [3]. Here is a list with 3 items ["ball",3.14,-2]. Let's 11 | define a list, I'll call it lis and we'll do things with it to illustrate 12 | accessing items in a list. Execute the following cell with Ctrl-Enter. 13 | """ 14 | #%% 15 | lis = ["a","b","c","d","e","f"] 16 | #%% 17 | """ 18 | Exercise: 19 | Some of the things that we can do with lists. Let's try them together. 20 | 21 | lis[0] is the first element of the list. (index is 0) 22 | lis[1] is the second element of the list and so on. (index is 1) 23 | The length of the list is len(lis) and is the number of items in the list. 24 | lis[-1] is the last item in the list. 25 | lis[2:4] will list items 2 and 3 (but not 4) 26 | lis[:4] will list items 0, 1, 2, 3 (but not 4); that is all items up to 4 27 | lis[3:] will list all items starting with item 3. 28 | lis.append("g") will append "g" onto the end of the list 29 | "a" in lis # running this statement will return True 30 | "r" in lis # running this statement will return False 31 | 32 | Everything in Python is an object, whether it is a variable like x or a list 33 | like lis. Objects have methods indicated by the dot. So .append() is a method 34 | of the list object. We'll see more of this. 35 | """ 36 | """ 37 | Here is an example function using a list. We pass in a list of items and 38 | it checks for certain animals or flowers in the list. 39 | We'll try it out on several lists such as ['bear'], ['daisy', lion'], etc. 40 | """ 41 | #%% 42 | 43 | def who_is_there(lis): 44 | if "bear" in lis: 45 | print("There's a bear.") 46 | if "lion" in lis: 47 | print("There's a lion.") 48 | if "daisy" in lis or "iris" in lis: 49 | print("There are flowers.") 50 | if "daisy" in lis and "iris" in lis: 51 | print("There are at least two flowers.") 52 | if "donkey" in lis: 53 | print("There is a donkey.") 54 | if "horse" not in lis: 55 | print("There is no horse in the list.") 56 | print("The list has",len(lis), "items") 57 | #%% 58 | """ 59 | You should make up some lists and pass to 'who_is_there' to see how the if 60 | statements handle various combinations. Some test lists for who_is_there: 61 | """ 62 | #%% 63 | alion = ['lion'] 64 | ld = ['lion','daisy'] 65 | lbf = ['lion','bear','iris'] 66 | #%% 67 | """ 68 | The following function illustrates using lists in 'for' loops. Note that the 69 | loop variable 'let' steps through the list, alist, taking the value of each of 70 | its items in turn. 71 | """ 72 | #%% 73 | lis = ["a","b","c","d","e","f"] 74 | lis1 = ["a","b","a","r","c","a","a"] 75 | #%% 76 | def count_a(alist): 77 | ct = 0 78 | for let in alist: 79 | if let == 'a': 80 | ct = ct + 1 81 | print("There are",ct,"letter a's in the list.") 82 | #%% 83 | """ 84 | Note there is a basic design pattern to these lists. Some variable for 85 | accumulating the results (above it is ct) is initiated before entering the 86 | loop. This variable is updated within the loop. Afterwards that variable is 87 | used (in this case ct is printed out). 88 | """ 89 | 90 | """ 91 | Exercise: 92 | Take the following list, nlis, and compute its average. That is, write 93 | a function 'average(numlis)' that uses a 'for' loop to sum up the numbers 94 | in numlis and divide by the length of numlis. Just to be sure that you 95 | got all the numbers in numlis, print each one in your 'for' loop and 96 | print the length of the the list. When using a loop, one always needs to 97 | be careful that it loops as often as is expected. In this case also print out 98 | the number of items in the list. 99 | Caution: Do NOT use the variable nlis in your function. This function should 100 | work on any list of numbers. Just to be sure make sure that your function 101 | (without any changes) works on rlis as well as nlis. 102 | """ 103 | #%% 104 | nlis = [2,4,8,105,210,-3,47,8,33,1] # average should by 41.5 105 | rlis = [3.14, 7.26, -4.76, 0, 8.24, 9.1, -100.7, 4] # average is -9.215 106 | #%% 107 | # some tests for your function. Be sure your function works for these 108 | average(nlis) 109 | average(rlis) 110 | #%% 111 | """ 112 | Solution: 113 | """ 114 | #%% 115 | def average(numlis): 116 | sum = 0 117 | for i in range(0, len(numlis)): 118 | sum = sum+numlis[i] 119 | print(numlis[i]) 120 | average = sum/len(numlis) 121 | print("average is",average,"its count is",len(numlis)) 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | #%% 130 | """ 131 | End solution 132 | """ 133 | """ 134 | Let me emphasize that you can make a 'for' loop with just a list. 135 | One can simply step through a list to form the loop. 136 | 137 | In this example case it is a list of states and we will simply be stepping 138 | through the loop and printing out the states. 139 | """ 140 | #%% 141 | newEngland = ["Maine","New Hampshire","Vermont", "Rhodes Island", 142 | "Massachusetts","Connecticut"] 143 | 144 | def for_state(slis): 145 | for state in slis: 146 | print(state) 147 | 148 | #%% 149 | """ 150 | Keep in mind that a 'for' loop can step through various kinds of iterators. 151 | """ 152 | """ 153 | Exercise: 154 | Write a function 'print_list(lis)' that prints items of the list lis. Test it 155 | by running the three tests that I give here. This requires writing a function 156 | that includes a loop like the one above, but uses lis for the iterator. Inside 157 | your function you should use lis to represent the list. If you do so, your 158 | function should pass all three tests below. 159 | """ 160 | #%% 161 | letter_list = ['a', 'b', 'c'] 162 | cap_list = ['A', 'B', 'C', 'D'] 163 | misc_list = ['ball', 3.14, -50, 'university', "course"] 164 | #%% 165 | """ 166 | Solution: 167 | """ 168 | #%% 169 | def print_list(lis): 170 | for list in lis: 171 | print(list) 172 | 173 | 174 | #%% 175 | """ 176 | End solution 177 | """ 178 | """ 179 | Lets' talk about data types. For starters Python has integers (e.g., 40), float 180 | or real numbers (e.g., 40.0), string ("hello"), list ( ['a','b','c']), bool 181 | (boolean -- that is, True or False). In Python they are called int, float, 182 | str, list, bool. You can tell what type a variable x is by entering type(x). 183 | Here is an example of several: 184 | """ 185 | #%% 186 | x = 17 # integer 187 | y = 3.14 # float 188 | z = "The Walrus and the Carpenter" # string 189 | z1 = "30" # string 190 | z2 = '40' # string 191 | vowels = ['a','e','i','o','u'] # list of strings 192 | nums = ['1','2','3', '3.14'] # list of strings 193 | phrases = ["’Twas brillig, and the slithy toves", 194 | "Did gyre and gimble in the wabe:"] # list of strings (2 strings, in fact) 195 | r = True # boolean 196 | s = False # boolean 197 | #%% 198 | """ 199 | Often you can convert one type to another: int(z1) makes and returns an 200 | integer (30); float(z2) returns a float or real number (40.0); str(y) returns 201 | the string "3.14"; etc. 202 | This is important because z1+z2 is not 70 (it is '3040'); however, 203 | int(z1)+int(z2) is 70. Here is a simple program showing when you might want to 204 | use this technique. 205 | """ 206 | #%% 207 | def multiply(): 208 | numstr1 = input("Enter a number: ") 209 | numstr2 = input("Enter another number: ") 210 | num1 = float(numstr1) 211 | num2 = float(numstr2) 212 | print("Their product is ", num1 * num2) 213 | # print("Won't work: ", numstr1 * numstr2) 214 | #%% 215 | """ 216 | Compare list(range(2,20,3)) and range(2,20,3). The first one is a list and 217 | the second one is what Python calls an iterator. The second one dishes out 218 | the next element in the list each time it is called. This is one of the changes 219 | from Python 2 to Python 3. In Python 2 it was a list and there was a function 220 | xrange() for iterating without building the list. That is gone from Python 3. 221 | Can you think of a reason that using range in Python 2 might not be a good idea 222 | with huge lists? 223 | """ 224 | #%% 225 | print(list(range(2,20,3))) 226 | print(range(2,20,3)) 227 | #%% 228 | """ 229 | Caution: Notice that large numbers never include commas. Compare these two 230 | examples. In the second, Python thinks that it is printing 3 numbers not 1. 231 | """ 232 | print(12345678) 233 | print(12,345,678) 234 | #%% 235 | """ 236 | Another caution. The following are Python keywords. They have special meaning 237 | and shouldn't be used as variable names: 238 | and del from not while 239 | as elif global or with 240 | assert else if pass yield 241 | break except import print 242 | class exec in raise 243 | continue finally is return 244 | def for lambda try 245 | 246 | You'll just get a syntax error: 247 | """ 248 | #%% 249 | except = 5 250 | #%% 251 | """ 252 | Note: for readability, if you feel that you need to use one of these as a 253 | variable, you could use an underscore after it. For example, and_, class_, etc. 254 | That makes it different from the Python keyword. 255 | """ 256 | #%% 257 | newEngland = ["Maine","New Hampshire","Vermont", "Rhodes Island", 258 | "Massachusetts","Connecticut"] 259 | 260 | def for_state(state_list): 261 | for state in state_list: 262 | print(state) 263 | 264 | #%% 265 | """ 266 | Let's print a small report. Here is a list of New England states and 267 | their populations. We'll print this as a table or report. Essentially, this 268 | is like the little function above, except that we need to handle the variables 269 | in a more sophisticated way. 270 | """ 271 | #%% 272 | newEngland = [["Massachusetts",6692824],["Connecticut",3596080], 273 | ["Maine",1328302],["New Hampshire",1323459], 274 | ["Rhode Island",1051511],["Vermont",626630]] 275 | #%% 276 | """ 277 | Exercise: 278 | Before writing the function, let's understand this list of lists better. 279 | Try this out. 280 | What is the first item of newEngland? (i.e., the one of index 0) 281 | What is the second item? 282 | What is the name of the state in the second element? How do we get that? 283 | What is the population of the state in the second element? 284 | """ 285 | """ 286 | Solution: 287 | """ 288 | #%% 289 | print(newEngland[0]) 290 | print(newEngland[1]) 291 | state = newEngland[1] 292 | print(state) 293 | print("population: ", state[1], " name:", state[0]) 294 | print(newEngland[1][0]) 295 | print(newEngland[1][1]) 296 | 297 | 298 | 299 | 300 | 301 | 302 | 303 | #%% 304 | """ 305 | End solution 306 | """ 307 | #%% 308 | newEngland = [["Massachusetts",6692824],["Connecticut",3596080], 309 | ["Maine",1328302],["New Hampshire",1323459], 310 | ["Rhode Island",1051511],["Vermont",626630]] 311 | 312 | def report1(state_data): 313 | """ prints population report """ 314 | print("Population State") 315 | for state_item in state_data: 316 | print(state_item[1], " ", state_item[0]) 317 | 318 | #%% 319 | """ 320 | Note: that because we pass the list into the function by way of the argument 321 | state_data, the above works on the following mid-Atlantic list. Execute the 322 | following cell to define midAtlantic in IPython and try it: 323 | """ 324 | #%% 325 | midAtlantic = [["New York",19746227],["New Jersey",8938175], 326 | ["Pennsylvania",12787209]] 327 | #%% 328 | """ 329 | Note that we don't use 19,746,227 as the population of New York. Why? 330 | """ 331 | """ 332 | Another way to do it. 333 | """ 334 | #%% 335 | newEngland = [["Massachusetts",6692824],["Connecticut",3596080], 336 | ["Maine",1328302],["New Hampshire",1323459], 337 | ["Rhode Island",1051511],["Vermont",626630]] 338 | 339 | def report2(state_data): 340 | """ prints population report """ 341 | print("Population State") 342 | for i in range(0,len(state_data)): 343 | print(state_data[i][1], " ", state_data[i][0]) 344 | 345 | #%% 346 | 347 | """ 348 | Find the sum of the populations of the New England states. Print 349 | out how many there are. Use a basic loop design pattern. 350 | """ 351 | #%% 352 | newEngland = [["Massachusetts",6692824],["Connecticut",3596080], 353 | ["Maine",1328302],["New Hampshire",1323459], 354 | ["Rhode Island",1051511],["Vermont",626630]] 355 | 356 | def population(state_data): 357 | """ Sums state populations """ 358 | sum_ = 0 359 | num_states = len(state_data) 360 | for i in range(0,num_states): 361 | one_state = state_data[i] 362 | pop = one_state[1] 363 | sum_ = sum_ + pop 364 | print("The total population of this list of states is",sum_) 365 | print("There are",num_states,"states in this list of states.") 366 | #%% 367 | 368 | """ 369 | Version using more syntactic sugar -- the variables have better and more 370 | meaningful names. This may read better in a bigger program. 371 | """ 372 | #%% 373 | def population(state_data): 374 | """ Sums state populations """ 375 | population = 1 376 | sum_ = 0 377 | num_states = len(state_data) 378 | for state in range(0,num_states): 379 | sum_ = sum_ + state_data[state][population] 380 | print("The total population of this list of states is",sum_) 381 | print("There are",num_states,"states in this list of states.") 382 | #%% 383 | 384 | """ 385 | Exercise: 386 | Write a function 'average(nlis)' that uses a 'for' loop and 'range()' to sum up 387 | the numbers in nlis and divide by the length of nlis. Just to be sure that you 388 | have used all the numbers in nlis, print each one in your 'for' loop and print 389 | the length of the list. Do not use the variable numlis in your function! If you 390 | change to a different list will it work? For numlis, the output should look 391 | like: 392 | 393 | 65 44 3 56 48 74 7 97 95 42 394 | the average is 53.1 395 | """ 396 | #%% 397 | numlis = [65, 44, 3, 56, 48, 74, 7, 97, 95, 42] # test on this list 398 | numlis2 = [4,6,8,12,2,7,19] # test on a second list to be sure 399 | #%% 400 | """ 401 | Solution Starter: 402 | """ 403 | #%% 404 | def average(nlis): 405 | # pass # delete this and enter your code starting here 406 | sum = 0 407 | num = len(nlis) 408 | for i in range(0, num): 409 | sum = sum + nlis[i] 410 | print(nlis[i], end = " ") 411 | print() 412 | print("the average is ", sum/num) 413 | 414 | 415 | 416 | 417 | 418 | 419 | 420 | 421 | 422 | 423 | 424 | 425 | 426 | 427 | 428 | 429 | 430 | 431 | 432 | 433 | 434 | 435 | 436 | 437 | 438 | 439 | 440 | 441 | 442 | 443 | #%% 444 | """ 445 | End solution 446 | """ 447 | """ 448 | Another and simpler solution using the list itself as the iterator 449 | """ 450 | def average1(nlis): 451 | sum = 0 452 | for i in nlis: 453 | sum = sum + i 454 | print(i, end = " ") 455 | print() 456 | print("the average is", sum/len(nlis)) 457 | """ 458 | Libraries. Python is a "small" language in the sense that many tools 459 | that are available are not automatically included when you run it. Many of 460 | these tools are in modules called libaries and can be loaded into your program 461 | only when you need them, keeping your programs smaller when they aren't needed. 462 | A typical way of doing that is 463 | 464 | import random 465 | 466 | which will load the library named random. 467 | """ 468 | #%% 469 | import random 470 | #%% 471 | # Each run of the following gives a different random number between 0 and 1 472 | print(random.random()) 473 | #%% 474 | # Each run of the following gives a different random integer between 3 and 8 475 | print(random.randint(3,8)) 476 | #%% 477 | """ 478 | The following example builds a sentence using various parts of speech. 479 | It randomly chooses words from a list by using random.choice(), a function 480 | or method imported from a library called random. We have used a method of the 481 | string data type to capitalize the first letter of the sentence. 482 | """ 483 | #%% 484 | import random 485 | 486 | verbs=["goes","cooks","shoots","faints","chews","screams"] 487 | nouns=["bear","lion","mother","baby","sister","car","bicycle","book"] 488 | adverbs=["handily","sweetly","sourly","gingerly","forcefully","meekly"] 489 | articles=["a","the","that","this"] 490 | 491 | def sentence(): 492 | article = random.choice(articles) 493 | noun = random.choice(nouns) 494 | verb = random.choice(verbs) 495 | adverb = random.choice(adverbs) 496 | 497 | our_sentence = article + " " + noun + " " + verb + " " + adverb + "." 498 | our_sentence = our_sentence.capitalize() 499 | 500 | print(our_sentence) 501 | #%% 502 | """ 503 | Exercise: 504 | Adapt this function to write a four line poem. Call it simple_poem(). 505 | Essentially you have to write a loop around this so that you get 4 lines. 506 | Remember that the inside or scope of the loop has to be indented 4 spaces. 507 | Note: The Edit menu has a quick way to indent a series of lines. The function 508 | is repeated here for your convenience in modifying it. 509 | """ 510 | """ 511 | Solution (modify the copy below to be your simple_poem function): 512 | """ 513 | #%% 514 | import random 515 | 516 | verbs=["are","is","goes","cooks","shoots","faints","chews","screams"] 517 | nouns=["bear","lion","mother","baby","sister","car","bicycle","book"] 518 | adverbs=["handily","sweetly","sourly","gingerly","forcefully","meekly"] 519 | articles=["a","the","that","this"] 520 | 521 | def simple_poem(): 522 | article = random.choice(articles) 523 | noun = random.choice(nouns) 524 | verb = random.choice(verbs) 525 | adverb = random.choice(adverbs) 526 | 527 | our_sentence = article + " " + noun + " " + verb + " " + adverb + "." 528 | our_sentence = our_sentence.capitalize() 529 | 530 | print(our_sentence) 531 | 532 | 533 | #%% 534 | def simple_poem(): 535 | for i in range(4): 536 | article = random.choice(articles) 537 | noun = random.choice(nouns) 538 | verb = random.choice(verbs) 539 | adverb = random.choice(adverbs) 540 | 541 | our_sentence = article + " " + noun + " " + verb + " " + adverb + "." 542 | our_sentence = our_sentence.capitalize() 543 | 544 | print(our_sentence) 545 | 546 | 547 | 548 | 549 | 550 | 551 | 552 | 553 | 554 | 555 | 556 | 557 | #%% 558 | """ 559 | End Solution: 560 | """ 561 | """ 562 | Let's look at a couple of loop design patterns. 563 | """ 564 | """ 565 | Example: Add numbers until you get a blank one. This initializes a variable 566 | sum_ and adds to it each time through the loop. Afterwards sum_ is used in a 567 | print statement. 568 | """ 569 | #%% 570 | def add_up(): 571 | sum_ = 0 572 | while True: # will loop forever 573 | num = int(input("Enter a number, input 0 to quit: ")) 574 | if num == 0: 575 | break # breaks out of while loop 576 | sum_ = sum_ + num 577 | print(sum_) 578 | #%% 579 | """ 580 | Building lists - recall the .append() method 581 | """ 582 | #%% 583 | baseball = [] 584 | baseball.append("ball") 585 | baseball.append("bat") 586 | baseball.append("mitt") 587 | baseball 588 | #%% 589 | """ 590 | Let's write a program to build a list of the numbers. Before we initialized 591 | sum_ to 0. The equivalent for a list is to set it to the empty list. Adding to 592 | the sum has its equivalent in appending to the list. 593 | """ 594 | #%% 595 | def store_up(): 596 | num_lis = [] 597 | while True: 598 | nextnum = int(input("Enter a number, 0 to quit: ")) 599 | if nextnum == 0: 600 | break 601 | num_lis.append(nextnum) 602 | print(num_lis) 603 | #%% 604 | """ 605 | Exercise: 606 | Write a function diner_waitress() that asks for you order. First start an empty 607 | list, call it order. Then use a while loop and an input() statement to gather 608 | the order. Continue in the while loop until the customer says "that's all". 609 | Onne way to end the loop is to use 'break' to break out of the loop when 610 | "that's all" is entered. 611 | Recall that you can add to a list by using the list's .append() method; suppose 612 | that your list is called order. To create an empty list you can use 613 | order = []. You are going to have to input one food at a time and append it 614 | to the order list. 615 | Then print out the order. Here is my run: 616 | 617 | diner_waitress() 618 | Hello, I'll be your waitress. What will you have? 619 | 620 | menu item: eggs 621 | 622 | menu item: bacon 623 | 624 | menu item: toast 625 | 626 | menu item: jelly 627 | 628 | menu item: that's all 629 | You've ordered: 630 | ['eggs', 'bacon', 'toast', 'jelly'] 631 | 632 | """ 633 | #%% 634 | """ 635 | Solution: 636 | """ 637 | #%% 638 | def diner_waitress(): 639 | menu_lis = [] 640 | print("Hello, I'll be your waitress. What will you have?") 641 | while True: 642 | nextmenu = (input("menu item: ")) 643 | if nextmenu == "that's all": 644 | break 645 | menu_lis.append(nextmenu) 646 | print("You've ordered: ") 647 | print(menu_lis) 648 | #%% 649 | 650 | 651 | 652 | 653 | 654 | 655 | 656 | 657 | #%% -------------------------------------------------------------------------------- /Exercises/Exercises3/ADream.txt: -------------------------------------------------------------------------------- 1 | A Dream within a Dream 2 | by Edgar Allen Poe 3 | 4 | Take this kiss upon the brow! 5 | And, in parting from you now, 6 | Thus much let me avow-- 7 | You are not wrong, who deem 8 | That my days have been a dream; 9 | Yet if hope has flown away 10 | In a night, or in a day, 11 | In a vision, or in none, 12 | Is it therefore the less gone? 13 | All that we see or seem 14 | Is but a dream within a dream. 15 | 16 | I stand amid the roar 17 | Of a surf-tormented shore, 18 | And I hold within my hand 19 | Grains of the golden sand-- 20 | How few! yet how they creep 21 | Through my fingers to the deep, 22 | While I weep--while I weep! 23 | O God! can I not grasp 24 | Them with a tighter clasp? 25 | O God! can I not save 26 | One from the pitiless wave? 27 | Is all that we see or seem 28 | But a dream within a dream? -------------------------------------------------------------------------------- /Exercises/Exercises3/BooksRead.csv: -------------------------------------------------------------------------------- 1 | "Beckert, Sven",Empire of Cotton,history 2 | "Buckley, Carla",The Deepest Secret,mystery 3 | "Carcaterra, Lorenzo",Chasers,mystery 4 | "Catton, Bruce",The Army of the Potomac: The Glory Road,military 5 | "Cohen, Gabriel",The Ninth Step,mystery 6 | "Darwin, Charles",Origin of Species,science 7 | "Ho, Yong",China: An Illustrated History,history 8 | "James, Henry",Daisy Miller,novel 9 | "Larsson, Stieg",The Girl who played with fire,novel 10 | "Lewis, Michael",Liar's Poker: rising through the wreckage on Wall Street,economics 11 | "Messenger, Bill",Elements of Jazz: From Cakewalks to Fusion,music 12 | "Paulos, John Allen",Innumeracy,mathematics 13 | "Penzler, Otto, ed.",Murder at the Racetrack ,mystery 14 | "Pintoff, Stefanie",Secret of the White Rose,mystery 15 | "Post, Robert C.","Democracy, Expertise, Academic Freedom",law 16 | "Solzhenitsyn, Alexander",One Day in the Life of Ivan Denisovich,novel 17 | "Torrence, Bruce F. and Eve A.",The Student's Introduction to Mathematica,mathematics 18 | "Woods, Stewart",Mounting Fears,novel 19 | -------------------------------------------------------------------------------- /Exercises/Exercises3/Exercises3.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Tue Oct 18 15:06:36 2016 4 | 5 | @author: Abdullah A. Alam 6 | """ 7 | 8 | # -Exercises3.py *- coding: utf-8 -*- 9 | 10 | """ 11 | TUPLES 12 | Tuple (like the list type this is a data collection type) 13 | Note a pair of numbers 3,4 is referred to as a tuple. There are tuples of 14 | various sizes: 3,4 and 3,4,5 and 3,4,5,6 are all tuples. They do not have to 15 | be numbers. The following are also tuples: 'a,','b' and x, y, z and 16 | "Morning", "Afternoon", "Evening". In Python we can set tuples equal to other 17 | tuples as follows: 18 | """ 19 | #%% 20 | x,y = 3,4 21 | print (x,y) 22 | #%% 23 | a,b,c = 10,11,12 24 | print(a,b,c) 25 | print(b) 26 | #%% 27 | """ 28 | The tuple 4,6,8 is written by Python with parentheses: (4,6,8) 29 | """ 30 | #%% 31 | 4,6,8 32 | #%% 33 | """ 34 | The items in tuples can be accessed much like those in a list, but unlike a 35 | list, a tuple cannot be changed. One cannot add to a tuple or remove an item 36 | from a tuple. It is said to be immutable. 37 | 38 | Let's define a tuple and look at how to access its items: 39 | """ 40 | #%% 41 | tup = ('a','e','i','o','u') 42 | #%% 43 | """ The following accesses are just like in a list. """ 44 | print("tup is", tup) 45 | print(tup[0]) 46 | print(tup[1]) 47 | print(tup[-1]) 48 | print(tup[-2]) 49 | print(tup[1:3]) 50 | print(tup[:3]) 51 | #%% 52 | """ 53 | DICTIONARIES 54 | Dictionary data type (another collection datatype along with list and tuple): 55 | d = {} creates an empty dictionary 56 | d={key1:value1, key2:value2, key3:value3} - use key to find the value 57 | d[key2] gives value2, etc. 58 | Lists and strings are in order and you can use slicing to single out an item: 59 | lis[3] or strg[3] give the item with index 3 in the list or string. This won't 60 | work with dictionaries. So you use d[key] to get the value that goes with key. 61 | Example: 62 | """ 63 | #%% 64 | d = {"Johnny": "5 years old", "Sally": "7 years old", "Eva":"10 years old", 65 | "Peggy": "7 years old"} 66 | #%% 67 | """ 68 | Try out the following: 69 | d[0] gives an error 70 | d['Sally'] gives '7 years old' 71 | d prints out as 72 | {'Eva': '10 years old', 73 | 'Peggy': '7 years old', 74 | 'Sally': '7 years old', 75 | 'Johnny': '5 years old'} 76 | d.items() # this gives the items in the form of a list of tuples 77 | d.keys() # this gives the keys 78 | d.values() # this gives the values 79 | Note that the order is not the order entered. 80 | Note also that the keys must be unique but the values don't have to be 81 | 82 | Accessing. All the following two loops do the same or a similar thing: 83 | """ 84 | #%% 85 | for key,value in d.items(): 86 | print(key, "--> ", value) 87 | #%% 88 | for item in d.items(): 89 | print(item) 90 | #%% 91 | for item in d.items(): 92 | print(item) 93 | print(item[0], "--> ", item[1]) 94 | #%% 95 | for item in d.items(): 96 | print(item[0], "--> ", item[1]) 97 | #%% 98 | for key in d: 99 | print(key, "--> ", d[key]) 100 | #%% 101 | for key in d.keys(): 102 | print(key, "--> ", d[key]) 103 | #%% 104 | """ 105 | If you want to see only the values: 106 | """ 107 | #%% 108 | for value in d.values(): 109 | print(value) 110 | #%% 111 | """ 112 | The following will add the key:value pair "Ted":"5 years old" to d or change 113 | the value if 'Ted' is already a key in d: 114 | """ 115 | #%% 116 | d['Ted'] = "5 years old" 117 | #%% 118 | d 119 | #%% 120 | """ 121 | d["sally"] gives an error because "s" is not capitalized 122 | d["Jim"] gives an error because "Jim" is not a key. 123 | d["5 years old"] gives an error because "5 years old" is a value not a key 124 | """ 125 | """ 126 | Exercise: 127 | Consider the following dictionary of US News and World Reports list of best 128 | affordable sportscars (ascars). Execute the line below so that you have the 129 | dictionary in your IPython console. Then answer (retrieve) the following. 130 | Press if you lock up on some step. 131 | a) Type ascars to display the dictionary 132 | b) Using the key retrieve the Nissan sportcar. 133 | b) Using the key retrieve the Chevy sportscar. 134 | c) Change the MINI Cooper car to a "Coupe". Display ascars to check that it 135 | worked. 136 | d) Write a small 2 line loop to display all the values and only the values 137 | e) Write a small 2 line loop to display all the keys (and only the keys). 138 | 139 | Here is the list to execute: 140 | """ 141 | #%% 142 | ascars = {"Ford" : "Mustang","Mazda" : "Miata", "Scion" : "FR-S", 143 | "Subaru" : "BRZ","Dodge" : "Challenger", "Nissan" : "370Z", "Chevy" : "Camaro", 144 | "Hyundai" : "Genesis Coupe" , "MINI Cooper" : "Roadster"} 145 | 146 | #%% 147 | """ 148 | Solutions 149 | """ 150 | #%% 151 | "a" 152 | #%% 153 | ascars["Nissan"] 154 | #%% 155 | "b" 156 | #%% 157 | ascars["Chevy"] 158 | #%% 159 | "c" 160 | #%% 161 | ascars["MINI Cooper"]="Coupe" 162 | #%% 163 | "d" 164 | #%% 165 | for value in ascars.values(): 166 | print(value) 167 | #%% 168 | "e" 169 | #%% 170 | for key in ascars.keys(): 171 | print(key) 172 | #%% 173 | """ 174 | Some summary facts: 175 | Lists can be appended to and items can be addressed by item number. 176 | Tuples are immutable (can't be changed). Item can be addressed by item number. 177 | Dictionaries can be appended to. Items cannot be retrieved by item number, 178 | because the items have no inherent order. The values can be retrieved by 179 | using their keys. 180 | """ 181 | """ 182 | Exercise: 183 | Lists, tuples and dictionaries 184 | Let's examine the differences. 185 | First, lists and tuples are ordered, so this makes sense: lis[2], tup[3] 186 | Dictionaries are not ordered, so dict[0] returns an error. 187 | Dictionaries don't look items up by index number, but by key; you can't do 188 | this with lists and tuples. 189 | [] is an empty list; () is an empty tuple; and {} is an empty dictionary. 190 | Tuples can't be modified, but lists and dictionaries can. 191 | You can stride lists and tuples, but not dictionaries. Dictionaries have no 192 | notion of order and hence cannot be sliced ([3:7] doesn't mean anything) and 193 | they cannot be strided -- it might appear that you can, but the order is 194 | unpredictable. 195 | Try the following out and see what works: 196 | """ 197 | #%% 198 | # Execute this cell to create these variables 199 | namelist = ["George", "Sally", "Catherine", "James", "Peggy"] 200 | x,y,z = "George","Sally","Catherine" 201 | mytuple = x,y,z 202 | agedict = {"George":"17","Sally":"19", 203 | "Catherine":"18"} 204 | #%% 205 | # Which work (you might copy each into IPython and see whether it works)? 206 | namelist[1] # yes or no 207 | mytuple[1] # yes or no 208 | agedict[1] # yes or no 209 | #%% 210 | # Which work? 211 | namelist.append("Rod") # yes or no 212 | mytuple.append("Rod") # yes or no 213 | agedict.append("Rod") # yes or no 214 | #%% 215 | # Which work? 216 | namelist[1]="Rod" # yes or no 217 | mytuple[1] = "Rod" # yes or no 218 | agedict["Rod"]="23" # yes or no 219 | 220 | #%% 221 | """ 222 | OPERATING SYSTEM COMMANDS 223 | Some useful operation system commands for the rest of this lesson: 224 | Mac/unix/Linix 225 | pwd prints the current working directory 226 | ls lists the files in the current directory (options -l, -F, -a, -A) 227 | Windows 228 | cd , prints the current working directory 229 | dir lists the files in the current directory (one column) 230 | dir/w lists the files in the directory "wide" (multi-column) 231 | 232 | In an IPython window you can execute many operating system commands by 233 | putting an ! in front of them. On my Windows pc, the above Unix style commands 234 | work without the ! in front. 235 | 236 | These might be helpful when reading and writing files, because you either 237 | have to give the full directory path or assume the file is in the 238 | current working directory and use a relative path. '!cd ,' or '!pwd' will show 239 | you what the current working directory is. 240 | 241 | Another note: there is a button to the right of the Global Working Directory 242 | (this is the path displayed in the upper right of the toolbar) to set the 243 | displayed path as the current working directory. 244 | """ 245 | 246 | """ 247 | READING AND WRITING TEXT FILES 248 | 249 | Reading/writing files summary: 250 | infile = open(filename) # For reading. Also infile = open(filename,'r') 251 | infile.close() 252 | outfile = open(filename,"w") "Open for writing 253 | outfile.write("string to write") 254 | outfile.close() 255 | """ 256 | #%% 257 | def print_file(filename): 258 | """ Opens file and prints its contents line by line. """ 259 | infile = open(filename) 260 | 261 | for line in infile: 262 | print(line, end="") # the file has "\n" at the end of each line already 263 | 264 | infile.close() 265 | #%% 266 | def copy_file(infilename, outfilename): 267 | """ Opens two files and copies one into the other line by line. """ 268 | infile = open(infilename) 269 | outfile = open(outfilename,'w') 270 | 271 | for line in infile: 272 | outfile.write(line) 273 | 274 | infile.close() 275 | outfile.close() 276 | #%% 277 | """ 278 | Exercise: 279 | Write a function write_to_file(filename,myname,myage,major) that opens the 280 | file and writes 3 lines in it using the data given. Here is a sample 281 | of what could be in the file. Call the file 'namefile.txt', so that it is 282 | identifiable as a text file: 283 | 284 | My name is George 285 | My age is 21 286 | I am majoring in Physics 287 | Tips: 288 | 1. write() can take only a string and, in fact, only one. So whatever you 289 | write has to be put together into one string (using +, for example). 290 | 2. Add +"\n" on the end of each write to put a newline at the end of each 291 | line. Otherwise, everything will be jammed together on one line. 292 | 3. Convert your age (a number) to a string -- use str() to do that. Then join 293 | it to the other parts of the string before writing. 294 | 4. When running the function, use quotes around every argument except the 295 | number. 296 | 297 | Use notepad (on pc) or textedit (on Mac) to look at the file to confirm it. An 298 | outline of what needs to be done is given as comments. 299 | """ 300 | #%% 301 | def write_to_file(filename, myname, myage, major): 302 | # open file first 303 | outfile.write("My name is "+ myname + " \n") 304 | # write out the age and major in two lines 305 | # close the file 306 | 307 | 308 | #%% 309 | def write_to_file(filename, myname, myage, major): 310 | outfile = open(filename,'w') 311 | outfile.write("My name is "+ myname + " \n") 312 | outfile.write("My age is "+ str(myage) + " \n") 313 | outfile.write("I am majoring in "+ major + " \n") 314 | outfile.close() 315 | 316 | """ 317 | RUNNING STANDALONE SCRIPTS OR PROGAMS. 318 | 319 | So far we have been writing Python functions and running them. Now let's 320 | write a Python program (actually Python calls them 'scripts'). 321 | 322 | To run from command line open a command window in one of two ways: 323 | On windows, from the Start Menu, enter cmd.exe 324 | -- in this case use cd to change to the directory with print_file.py in it 325 | or 326 | From Spyder, go to menu Tools>Open command prompt 327 | -- in this case you should be sure that print_file.py is in the directory at 328 | -- the top of the screen (Global working directory) or do as in the 329 | -- cmd.exe case and use cd to get there. 330 | 331 | Once you are in the correct directory, enter the following command at the 332 | ">" prompt: python printfile.py 333 | 334 | """ 335 | """ 336 | NOTE: SOME OF YOUR COMPUTERS MAY HAVE PYTHON 2.7 INSTALLED ON THEM. THE PATHS 337 | ARE SET TO RUN VERSION 2.7. WITHOUT RESETTING THE PATH, THOSE COMPUTERS MAY 338 | ATTEMPT TO RUN PROGRAMS USING PYTHON 2.7 INSTEAD OF PYTHON 3.4. Macintoshes, 339 | for example, come with Python 2.7 installed and will have this issue. The 340 | following works from the Spyder Command prompt regardless, so we will use that. 341 | The environment can be set to python 3, but I'm not going into that right now. 342 | """ 343 | #%% # Note the following cell can NOT be executed by Ctrl-Enter. Copy to a file. 344 | # - print_file.py *- coding: utf-8 -*- 345 | """ Opens file and prints its contents line by line. """ 346 | 347 | import sys # we need this library to deal with operating system 348 | 349 | filename = sys.argv[1] 350 | 351 | infile = open(filename) 352 | 353 | for line in infile: 354 | print(line,end="") # the file has "\n" at the end of each line already 355 | 356 | infile.close() 357 | #%% 358 | """ 359 | Exercise: 360 | Now take copy_file from above and convert it to a stand alone program called 361 | copy_file.py. Actually, I've provided you a starter file named copy_file.py. 362 | Open it and modify it. Then save it and run it in a terminal or command 363 | window. Now modify it by adding the import statement above. Since you have two 364 | filenames now, you will need to use sys.argv[1] and sys.argv[2] to 365 | get them. Here is copy_file.py that you need to rework: 366 | """ 367 | #%% 368 | # -copy_file.py *- coding: utf-8 -*- 369 | """ 370 | Exercise: Convert this function to a standalone program or script that 371 | takes two file names from the command line and copies one to the other. 372 | 373 | Steps: 374 | 1. Delete "Def" line. You don't need it. 375 | 2. Use Edit menu of Spyder to Unindent all the lines. 376 | 3. import the system library sys 377 | 4. sys.argv is a list of the filenames following the program name. 378 | sys.argv[0] is the program name, sys.argv[1] is first argument, etc. 379 | Get the infilename and outfilename from this list. 380 | 5. Save the program 381 | 6. Run the program from a terminal window (Mac) a cmd.exe window (PC) or 382 | a command prompt within Spyder (use Tools>Open command prompt) 383 | 384 | Here is how running it should look: 385 | >python copy_file.py humptydumpty.txt newhumpty.txt 386 | """ 387 | 388 | def copy_file(infilename, outfilename): 389 | """ Opens two files and copies one into the other line by line. """ 390 | infile = open(infilename) 391 | outfile = open(outfilename,'w') 392 | 393 | for line in infile: 394 | outfile.write(line) 395 | 396 | infile.close() 397 | outfile.close() 398 | #%% 399 | 400 | """ 401 | Solution is in copy_file_worked.py 402 | """ 403 | """ 404 | lwc.py below is a program that counts the number of lines, words, and 405 | characters in a text file. Similar to linux wc command. 406 | Copy this to a separate file named lwc.py or download ours. 407 | """ 408 | #%% 409 | # - lwc.py *- coding: utf-8 -*- 410 | import sys 411 | 412 | filename = sys.argv[1] 413 | # print("\n",filename,"\n") # You can check that the filename is correct 414 | 415 | text_file = open(filename) # open the file for reading 416 | 417 | # initialize line, word, and char counters to 0 418 | linect = 0 419 | wordct = 0 420 | charct = 0 421 | 422 | for line in text_file: # step through each line in the text file 423 | linect = linect + 1 424 | for word in line.split(): # split into a list of words 425 | wordct = wordct + 1 426 | charct = charct + len(line) 427 | 428 | text_file.close() 429 | 430 | print(linect, wordct, charct ) 431 | #%% 432 | """ 433 | Reads through a text file and counts the number of different words. 434 | Uses a dict (dictionary data type) 435 | d = {key1:value1, key2:value2, key3:value3} 436 | d[key2] gives value2, etc. 437 | The key in this case is a word and the value is the number of times it occurs. 438 | 439 | The plan is to read through a text file, split each line into its constituent 440 | words, add each word to a dictionary, then add one to the number of times the 441 | word occurs in the dictionary. Finally, we sort the dictionary and print it 442 | out listing each word (key) and its count (value). 443 | """ 444 | #%% 445 | def count_words(filename): 446 | """ Makes a list of the words in the file filename and the number of times 447 | each word appears. This program is modified from one by Mark Summerfield in 448 | his excellent book, "Programming in Python 3" """ 449 | 450 | text_file = open(filename) # open the file for reading 451 | 452 | # Set up an empty dictionary to start a standard design pattern loop 453 | words_dic = {} 454 | 455 | # This loop adds each word to the dictionary and updates its count. Change 456 | # all words to lower case so Horse and horse are seen as the same word. 457 | for line in text_file: # step through each line in the text file 458 | for word in line.lower().split(): # split into a list of words 459 | word = word.strip("'?,.;!-/\"") # strip out the stuff we ignore 460 | if word not in words_dic: 461 | words_dic[word] = 0 # add word to words with 0 count 462 | words_dic[word] = words_dic[word] + 1 # add 1 to the count 463 | 464 | text_file.close() 465 | 466 | # Sorts the dictionary words into a list and then print them out 467 | print("List of words in the file with number of times each appears.") 468 | word_list = sorted(words_dic) 469 | for word in word_list: 470 | print(words_dic[word], word) 471 | 472 | #%% 473 | """ 474 | Exercise: 475 | Save this cell as a separate file called count_words.py (or download 476 | count_words.py) and run as instructed below. This is a standalone version of 477 | the above function. 478 | NOTE: THIS WILL WORK FROM SPYDER COMMAND PROMPT, BUT MAY NOT ON A MAC FROM 479 | TERMINAL WINDOW. SEE RUNNING STANDALONE PROGRAMS ABOVE. 480 | """ 481 | #%% 482 | # -count_words.py *- coding: utf-8 -*- 483 | """ 484 | Reads through a text file and counts the number of appearances of each word. 485 | 486 | To run from command line open a command window in one of two ways: 487 | On windows, from the Start Menu, enter cmd.exe 488 | -- in this case use cd to change to the directory with count_words.py in it 489 | or 490 | From Spyder, go to menu Tools>Open Command prompt 491 | -- in this case you should be sure that count_words is in the directory at 492 | -- the top of the screen (Global working directory) or do as in the 493 | -- cmd.exe case and use cd to get there. 494 | 495 | Once you are in the correct directory, enter the following command at the 496 | ">" prompt: 497 | 498 | python count_words.py 499 | 500 | where is the name of a file (in quotes if it contains spaces) 501 | 502 | """ 503 | # -count_words.py *- coding: utf-8 -*- 504 | import sys 505 | 506 | filename = sys.argv[1] 507 | # print("\n",filename,"\n") # You can check that the filename is correct 508 | 509 | text_file = open(filename) # open the file for reading 510 | 511 | # Set up an empty dictionary to start a standard design pattern loop 512 | words_dic = {} 513 | 514 | # This loop adds each word to the dictionary and updates its count. Change 515 | # all words to lower case so Horse and horse are seen as the same word. 516 | for line in text_file: # step through each line in the text file 517 | for word in line.lower().split(): # split into a list of words 518 | word = word.strip("'?,.;!-/\"") # strip out the stuff we ignore 519 | if word not in words_dic: 520 | words_dic[word] = 0 # add word to words with 0 count 521 | words_dic[word] = words_dic[word] + 1 # add 1 to the count 522 | 523 | text_file.close() 524 | 525 | # Sorts the dictionary words into a list and then print them out 526 | print("List of words in the file with number of times each appears.") 527 | word_list = sorted(words_dic) 528 | for word in word_list: 529 | print(words_dic[word], word) 530 | 531 | # Sorts the dictionary words into a list and then print them out 532 | print("List of words in the file with number of times each appears.") 533 | word_list = sorted(words_dic) 534 | for word in word_list: 535 | print(words_dic[word], word) 536 | #%% 537 | 538 | """ 539 | CSV FILES 540 | """ 541 | """ 542 | We now turn to reading/writing CSV files, that is Comma Separated Value files. 543 | Text files lack the structure that we need for certain applications. CSV files 544 | can be read or written by spreadsheet programs such as Excel. They may be the 545 | most common way of transferring files from one application to another. 546 | Summary of CSV file statements: 547 | 548 | import csv 549 | 550 | infile = open(filename) # For reading. Also infile = open(filename,'r') 551 | infile.close() # An open file locks other applications out 552 | rows = csv.reader(infile) # Read row 553 | 554 | f = open(filename, 'w', newline='') # Open for writing 555 | csv.writer(f).writerows(rowlist) # Write all rows at once 556 | csv.writer(f).writerow(row) # Write one row 557 | f.close() 558 | 559 | """ 560 | """ 561 | Example of reading from a CSV file and writing each row as a list. 562 | """ 563 | #%% 564 | import csv 565 | 566 | def read_csv_file(filename): 567 | """Reads a CSV file and prints each row, which is a list. """ 568 | f = open(filename) 569 | for row in csv.reader(f): 570 | print(row) 571 | f.close() 572 | #%% 573 | """ 574 | Example of reading from a CSV file and appending to a list. 575 | """ 576 | #%% 577 | import csv 578 | 579 | def read_csv_file1(filename): 580 | """Reads a CSV file and print it as a list of rows.""" 581 | f = open(filename) 582 | data = [] 583 | for row in csv.reader(f): 584 | data.append(row) 585 | print(data) 586 | f.close() 587 | #%% 588 | """ 589 | Exercise: 590 | Rewrite read_csv_file(filename), call it read_csv_file2(filename), so that you 591 | print each row without the list bracket. You will print each item in the row 592 | separately instead of printing the whole row. This requires you to know 593 | before-hand how many columns are in the csv file. In the case of booksread.csv, 594 | there are 3 items in each row: How do you address each item in the row list 595 | named row? They are row[?] and row[??] and row[???], where you fill in the 596 | ?, ??, and ??? values. 597 | Here's what the output should look like: 598 | 599 | read_csv_file2("booksread.csv") 600 | Beckert, Sven Empire of Cotton history 601 | Buckley, Carla The Deepest Secret mystery 602 | Carcaterra, Lorenzo Chasers mystery 603 | Catton, Bruce The Army of the Potomac: The Glory Road military 604 | Cohen, Gabriel The Ninth Step mystery 605 | Darwin, Charles Origin of Species science 606 | Ho, Yong China: An Illustrated History history 607 | James, Henry Daisy Miller novel 608 | Larsson, Stieg The Girl who played with fire novel 609 | Lewis, Michael Liar's Poker: rising through the wreckage on Wall Street economics 610 | Messenger, Bill Elements of Jazz: From Cakewalks to Fusion music 611 | Paulos, John Allen Innumeracy mathematics 612 | Penzler, Otto, ed. Murder at the Racetrack mystery 613 | Pintoff, Stefanie Secret of the White Rose mystery 614 | Post, Robert C. Democracy, Expertise, Academic Freedom law 615 | Solzhenitsyn, Alexander One Day in the Life of Ivan Denisovich novel 616 | Torrence, Bruce F. and Eve A. The Student's Introduction to Mathematica mathematics 617 | Woods, Stewart Mounting Fears novel 618 | 619 | """ 620 | """ 621 | Solution Starter: 622 | """ 623 | #%% 624 | import csv 625 | 626 | def read_csv_file2(filename): 627 | """Reads a CSV file and prints each row without list brackets. """ 628 | f = open(filename) 629 | for row in csv.reader(f): 630 | print(row[0], row[1], row[2]) 631 | f.close() 632 | #%% 633 | """ 634 | End solution 635 | """ 636 | """ 637 | Example of writing to a CSV file from a list looping and writing one 638 | row at a time. newline='' keeps csv file from writing a newline at the end of 639 | each line. This keeps the file from being double spaced. 640 | """ 641 | #%% 642 | def write_csv(filename): 643 | import csv 644 | 645 | L = [['Date', 'Name', 'Notes'], 646 | ['2016/1/18', 'Martin Luther King Day', 'Federal Holiday'], 647 | ['2016/2/2','Groundhog Day', 'Observance'], 648 | ['2016/2/8','Chinese New Year', 'Observance'], 649 | ['2016/2/14','Valentine\'s Day', 'Obervance'], 650 | ['2016/5/8','Mother\'s Day', 'Observance'], 651 | ['2016/8/19','Statehood Day', 'Hawaii Holiday'], 652 | ['2016/10/28','Nevada Day', 'Nevada Holiday']] 653 | 654 | f = open(filename, 'w', newline='') 655 | for item in L: 656 | csv.writer(f).writerow(item) 657 | f.close() 658 | #%% 659 | """ 660 | We can see that it has been written, by double-clicking it in File Explorer in 661 | Windows (or in the Finder on a Mac) so that our spreadsheet program opens it. 662 | We can also see it by entering !type in the IPython Console 663 | (!cat on a Mac), where filename is the name we gave in the function 664 | call above. 665 | """ 666 | """ 667 | Exercise: 668 | This is a modification of write_csv(filename). Instead of getting the data 669 | from a list, we're going to input it from the keyboard. This new function 670 | name_phone(csv_filename) will put a friend's name and his/her phone number 671 | into a csv file. Here is a start. We are going to add features to the program 672 | so that each step is manageable and we don't get confused. 673 | 1) Run this program and see that you can enter names and they'll print. 674 | To exit, you enter a blank name (i.e., just press return or enter). 675 | Note the loop runs forever, so we have to use 'break' to get out. 676 | 2) Add an input statement to collect a phone number and a line to print the 677 | phone number. Carefully place these so that the program runs nicely; that 678 | is, don't print anything until you have the phone number and don't get the 679 | phone number until you know the user isn't quiting. 680 | 3) Now add writing to a CSV file. After each step you can try running the 681 | function to make sure everything works. We're "growing" the program making 682 | sure that we have a working program each step of the way. You can check 683 | the work by double clicking on the created file and using Excel to peek into 684 | it. In the following be careful to put the right statements inside the loop 685 | and the others outside the loop. 686 | a) First add any necessary import statements. 687 | b) Add a line opening the csv file for writing and a line closing the file. 688 | c) As each line written to the CSV file must be a list, create an empty list 689 | like this: line = []. Note this should be inside the loop. Why? 690 | d) append the name to line; append the phone to line 691 | e) write the line to the CSV file 692 | """ 693 | """ 694 | Solution starter: 695 | """ 696 | #%% 697 | def name_phone(csv_filename): 698 | import csv 699 | # open the csv file here 700 | csvfile = open(csv_filename, "w", newline="") 701 | 702 | while True: 703 | nextname = input("Enter a friend's name, press return to end: ") 704 | if nextname == "": 705 | break # break jumps out of the loop 706 | nextphone = input("Enter your friend's phone: ") 707 | print(nextname) 708 | print(nextphone) 709 | 710 | # add lines here to build a row (that is, a list) and append these 711 | line = [] 712 | # two pieces of data to it. Write to the csv file 713 | line.append(nextname) 714 | line.append(nextphone) 715 | csv.writer(csvfile).writerow(line) 716 | 717 | # don't forget to close the csv file 718 | csvfile.close() 719 | 720 | #%% 721 | """ 722 | Example run: 723 | name_phone("myphones.csv") 724 | 725 | Enter a friend's name, press return to end: Jerry Seinfeld 726 | 727 | Enter your friend's phone: (212) 434-1234 728 | Jerry Seinfeld 729 | (212) 434-1234 730 | 731 | Enter a friend's name, press return to end: Elaine Benes 732 | 733 | Enter your friend's phone: (212) 123-6543 734 | Elaine Benes 735 | (212) 123-6543 736 | 737 | Enter a friend's name, press return to end: 738 | 739 | !type myphones.csv 740 | Jerry Seinfeld,(212) 434-1234 741 | Elaine Benes,(212) 123-6543 742 | 743 | """ 744 | """ 745 | Updating a csv file 746 | 747 | Let us read a CSV file containing a person's daily weights and compute the 748 | average weight and write that into the csv file. 749 | Here we copy the old file to a new one and add an additional line that 750 | contains the average of all the weight values. 751 | Note that the first row has a header so we skip it. 752 | Note also that the values are read in as strings and we must convert to float 753 | (i.e., read number) before using a number for arithmetic. 754 | Note that we are writing a new line at the end that contains the average. 755 | 756 | In developing this program, we could somehow open a file and not manage to 757 | close it. In which case, we may have to get out of Spyder to unlock the file. 758 | Using a new name for the new file (we're writing to it), can also fix the 759 | problem. 760 | 761 | Here is my run on a PC. On a Mac, the command "type" should be "cat": 762 | update_csv("weights.csv","xweights.csv") 763 | 764 | !type xweights.csv 765 | Date,Weight 766 | 5/1/2016,142 767 | 5/2/2016,143 768 | 5/3/2016,140 769 | 5/4/2016,141 770 | 5/5/2016,142 771 | 5/6/2016,141 772 | 5/7/2016,143 773 | Average,141.71428571428572 774 | 775 | """ 776 | #%% 777 | def update_csv(old_name, new_name): 778 | import csv 779 | 780 | fin = open(old_name) 781 | fout = open(new_name,'w',newline = '') 782 | ct = 0 783 | tot_weight = 0.0 784 | for row in csv.reader(fin): 785 | if row[0]!="Date": 786 | ct = ct + 1 787 | tot_weight = tot_weight + float(row[1]) 788 | csv.writer(fout).writerow(row) 789 | row = ["Average", tot_weight/ct] 790 | csv.writer(fout).writerow(row) 791 | fin.close() 792 | fout.close() 793 | #%% -------------------------------------------------------------------------------- /Exercises/Exercises3/HumptyDumpty.txt: -------------------------------------------------------------------------------- 1 | Humpty Dumpty sat on a wall, 2 | Humpty Dumpty had a great fall. 3 | All the king's horses and all the king's men 4 | Couldn't put Humpty together again. -------------------------------------------------------------------------------- /Exercises/Exercises3/copy_file.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Tue Oct 18 15:10:45 2016 4 | 5 | @author: Abdullah A. Alam 6 | """ 7 | 8 | # -copy_file.py *- coding: utf-8 -*- 9 | """ 10 | Exercise: Convert this function to a standalone program or script that 11 | takes two file names from the command line and copies one to the other. 12 | 13 | Steps: 14 | 1. Delete "Def" line. You don't need it. 15 | 2. Use Edit menu of Spyder to Unindent all the lines. 16 | 3. import the system library sys 17 | 4. sys.argv is a list of the filenames following the program name. 18 | sys.argv[0] is the program name, sys.argv[1] is first argument, etc. 19 | Get the infilename and outfilename from this list. 20 | 5. Save the program as copy_file.py 21 | 6. Run the program from a terminal window (Mac), a cmd.exe window (PC,) or 22 | a command prompt within Spyder (use Tools>Open command prompt) 23 | 24 | Here is how running it should look: 25 | >python copy_file.py humptydumpty.txt newhumpty.txt 26 | """ 27 | 28 | """ Opens two files and copies one into the other line by line. """ 29 | import sys 30 | 31 | infilename = sys.argv[1] 32 | outfilename = sys.argv[2] 33 | 34 | infile = open(infilename) 35 | outfile = open(outfilename,'w') 36 | 37 | for line in infile: 38 | outfile.write(line) 39 | 40 | infile.close() 41 | outfile.close() -------------------------------------------------------------------------------- /Exercises/Exercises3/count_words.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Tue Oct 18 15:12:15 2016 4 | 5 | @author: Abdullah A. Alam 6 | """ 7 | 8 | # -count_words.py *- coding: utf-8 -*- 9 | import sys 10 | 11 | filename = sys.argv[1] 12 | # print("\n",filename,"\n") # You can check that the filename is correct 13 | 14 | text_file = open(filename) # open the file for reading 15 | 16 | # Set up an empty dictionary to start a standard design pattern loop 17 | words_dic = {} 18 | 19 | # This loop adds each word to the dictionary and updates its count. Change 20 | # all words to lower case so Horse and horse are seen as the same word. 21 | for line in text_file: # step through each line in the text file 22 | for word in line.lower().split(): # split into a list of words 23 | word = word.strip("'?,.;!-/\"") # strip out the stuff we ignore 24 | if word not in words_dic: 25 | words_dic[word] = 0 # add word to words with 0 count 26 | words_dic[word] = words_dic[word] + 1 # add 1 to the count 27 | 28 | text_file.close() 29 | 30 | # Sorts the dictionary words into a list and then print them out 31 | print("List of words in the file with number of times each appears.") 32 | word_list = sorted(words_dic) 33 | for word in word_list: 34 | print(words_dic[word], word) -------------------------------------------------------------------------------- /Exercises/Exercises3/holidays.csv: -------------------------------------------------------------------------------- 1 | Date,Name,Notes 2 | 1/18/2016,Martin Luther King Day,Federal Holiday 3 | 2/2/2016,Groundhog Day,Observance 4 | 2/8/2016,Chinese New Year,Observance 5 | 2/14/2016,Valentine's Day,Obervance 6 | 5/8/2016,Mother's Day,Observance 7 | 8/19/2016,Statehood Day,Hawaii Holiday 8 | 10/28/2016,Nevada Day,Nevada Holiday 9 | -------------------------------------------------------------------------------- /Exercises/Exercises3/lwc.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Tue Oct 18 15:11:38 2016 4 | 5 | @author: Abdullah A. Alam 6 | """ 7 | 8 | # - lwc.py *- coding: utf-8 -*- 9 | import sys 10 | 11 | filename = sys.argv[1] 12 | # print("\n",filename,"\n") # You can check that the filename is correct 13 | 14 | text_file = open(filename) # open the file for reading 15 | 16 | # initialize line, word, and char counters to 0 17 | linect = 0 18 | wordct = 0 19 | charct = 0 20 | 21 | for line in text_file: # step through each line in the text file 22 | linect = linect + 1 23 | for word in line.split(): # split into a list of words 24 | wordct = wordct + 1 25 | charct = charct + len(line) 26 | 27 | text_file.close() 28 | 29 | print(linect, wordct, charct ) -------------------------------------------------------------------------------- /Exercises/Exercises3/menu.csv: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/abdullahaalam/Python-Programming-A-Concise-Introduction/c2ee40818860c53d9d73eb494af315527c7a853f/Exercises/Exercises3/menu.csv -------------------------------------------------------------------------------- /Exercises/Exercises3/myphones.csv: -------------------------------------------------------------------------------- 1 | Elaine Benes,(212) 123-6543 2 | Jerry Seinfeld,(212) 434-1234 3 | Cosmo Kramer,(212) 184-1234 4 | -------------------------------------------------------------------------------- /Exercises/Exercises3/phones.csv: -------------------------------------------------------------------------------- 1 | george,836-6025 2 | jackson,837-6501 3 | emma,617-4378 4 | sophia,539-8147 5 | aiden,213-4567 6 | olivia,782-3737 7 | liam,347-9038 8 | -------------------------------------------------------------------------------- /Exercises/Exercises3/print_file.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Tue Oct 18 15:12:53 2016 4 | 5 | @author: Abdullah A. Alam 6 | """ 7 | 8 | # - print_file.py *- coding: utf-8 -*- 9 | """ Opens file and prints its contents line by line. """ 10 | 11 | import sys # we need this library to deal with operating system 12 | 13 | filename = sys.argv[1] 14 | 15 | infile = open(filename) 16 | 17 | for line in infile: 18 | print(line,end="") # the file has "\n" at the end of each line already 19 | 20 | infile.close() -------------------------------------------------------------------------------- /Exercises/Exercises3/weights.csv: -------------------------------------------------------------------------------- 1 | Date,Weight 2 | 5/1/2016,142 3 | 5/2/2016,143 4 | 5/3/2016,140 5 | 5/4/2016,141 6 | 5/5/2016,142 7 | 5/6/2016,141 8 | 5/7/2016,143 9 | -------------------------------------------------------------------------------- /Exercises/Exercises3/xhumpty.txt: -------------------------------------------------------------------------------- 1 | Humpty Dumpty sat on a wall, 2 | Humpty Dumpty had a great fall. 3 | All the king's horses and all the king's men 4 | Couldn't put Humpty together again. -------------------------------------------------------------------------------- /Exercises/Exercises3/xmajor: -------------------------------------------------------------------------------- 1 | My name is George 2 | My age is 21 3 | I am majoring in Physics 4 | -------------------------------------------------------------------------------- /Exercises/Exercises3/xweights.csv: -------------------------------------------------------------------------------- 1 | Date,Weight 2 | 5/1/2016,142 3 | 5/2/2016,143 4 | 5/3/2016,140 5 | 5/4/2016,141 6 | 5/5/2016,142 7 | 5/6/2016,141 8 | 5/7/2016,143 9 | Average,141.71428571428572 10 | -------------------------------------------------------------------------------- /Exercises/Exercises4/Exercises4.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Mon Oct 24 11:44:47 2016 4 | 5 | @author: Abdullah A. Alam 6 | """ 7 | 8 | # -Exercises4.py *- coding: utf-8 -*- 9 | """ 10 | @author: Bill 11 | """ 12 | """ 13 | LONG STRINGS 14 | """ 15 | #%% 16 | lstr1 = "A very long string can be tied together using " + \ 17 | "a backslash (also called the escape character)." 18 | lstr2 = ("A very long string can also be tied together using " 19 | "parentheses to enclose the various parts.") 20 | #%% 21 | """ 22 | BUILDING LISTS OF RANDOM NUMBERS; RETURNING FUNCTIONAL VALUES 23 | 24 | Sometimes you need a list of numbers. Here is a way to build a list of pseudo- 25 | random numbers. We again import the python library random. It furnishes a 26 | random integer generator called randint(). 27 | 28 | Note the basic loop design pattern reappears. 29 | 30 | The function make_random() below builds a list of random integers using the 31 | randint() function from the random library. Note that we do not print the list 32 | out as we usually do. Instead we use another function to call the make_random() 33 | function and print it in the calling function. 34 | """ 35 | #%% 36 | 37 | import random 38 | 39 | def make_random(): 40 | """ Make a list of 10 random integers between 1 and 100. """ 41 | numlis = [] 42 | for i in range(0,10): 43 | numlis.append(random.randint(1,100)) 44 | return numlis 45 | 46 | def call_make_random(): 47 | """ Uses make_random to get a list of random numbers """ 48 | random_integers = make_random() 49 | print("The list of random numbers is",random_integers) 50 | #%% 51 | 52 | """ 53 | For testing your program, however, it can be deadly to have a different set of 54 | random numbers each time it is run. That's a formula for madness: sometimes 55 | your program may work and sometimes not, depending on the particular random 56 | numbers that happen to be generated on that run. Consequently, it can be very 57 | hard to track down the error. For testing purposes, you can generate the same 58 | random numbers over and over again by setting the random number generator's 59 | seed to the same value each time. 60 | """ 61 | #%% 62 | 63 | import random 64 | 65 | def make_same_random(): 66 | """ Make a list of 10 random integers that are the same each time """ 67 | numlis = [] 68 | random.seed(17) # set the seed from which random numbers are made 69 | for i in range(0,10): 70 | numlis.append(random.randint(1,100)) 71 | return numlis 72 | 73 | def call_make_random(): 74 | """ Uses make_same_random to get a list of random numbers """ 75 | random_integers = make_same_random() 76 | print(random_integers) 77 | random_integers1 = make_same_random() 78 | print(random_integers1) 79 | 80 | #%% 81 | """ 82 | Exercise: 83 | Write a function make_random_real() that uses random.random() in place of 84 | random.randint() to build a list of 10 random reals and returns that list. 85 | random.random() generates a random number between 0 and 1. 86 | Note: we want to return a list not print it. 87 | Here is my run. Your list of random reals will likely be different from mine: 88 | In [2]: make_random_real() 89 | Out[2]: 90 | [0.6069930611672794, 91 | 0.9812910762564292, 92 | 0.4290994419220008, 93 | 0.9957161016532591, 94 | 0.005874475115656863, 95 | 0.5329633233660277, 96 | 0.7662656130982124, 97 | 0.8460145442822357, 98 | 0.05511562729749986, 99 | 0.009731494763540849] 100 | 101 | """ 102 | """ 103 | Solution: 104 | """ 105 | #%% 106 | 107 | import random 108 | 109 | def make_random_real(): 110 | """ Make a list of 10 random reals that are the same each time """ 111 | numlis = [] 112 | for i in range(0,10): 113 | numlis.append(random.random()) 114 | return numlis 115 | 116 | 117 | 118 | 119 | 120 | 121 | #%% 122 | """ 123 | End solution 124 | """ 125 | 126 | """ 127 | Exercise: 128 | Rewrite make_random_real() using random.seed() to get the same random reals 129 | each time. Run the function twice to show that you get the same set of 130 | "random" numbers. A correct solution will display the same list each time it 131 | is run. Return the list of random numbers rather than printing them. 132 | Here are a couple of my runs using 17 as the seed: 133 | make_same_random_real() 134 | Out[45]: 135 | [0.5219839097124932, 136 | 0.8066907771186791, 137 | 0.9604947743238768, 138 | 0.2896253777644655, 139 | 0.7661074377979527, 140 | 0.7042198668434126, 141 | 0.6613830572238304, 142 | 0.11016204891721182, 143 | 0.026936778790526805, 144 | 0.3841711045442975] 145 | 146 | make_same_random_real() 147 | Out[46]: 148 | [0.5219839097124932, 149 | 0.8066907771186791, 150 | 0.9604947743238768, 151 | 0.2896253777644655, 152 | 0.7661074377979527, 153 | 0.7042198668434126, 154 | 0.6613830572238304, 155 | 0.11016204891721182, 156 | 0.026936778790526805, 157 | 0.3841711045442975] 158 | 159 | """ 160 | """ 161 | Solution: 162 | """ 163 | #%% 164 | 165 | 166 | import random 167 | 168 | def make_same_random_real(): 169 | """ Make a list of 10 random reals that are the same each time """ 170 | numlis = [] 171 | random.seed(17) # set the seed from which random numbers are made 172 | for i in range(0,10): 173 | numlis.append(random.random()) 174 | return numlis 175 | 176 | 177 | 178 | 179 | 180 | 181 | 182 | 183 | #%% 184 | """ 185 | End solution 186 | """ 187 | """ 188 | SORTING LISTS 189 | 190 | Exercise: Sorting lists, including numbers as well as lower and upper case 191 | letters and strings. 192 | 193 | Do with me. Use the line of code below to create a list. 194 | """ 195 | #%% 196 | numlist = [67, 54, 39, 47, 38, 23, 99, 91, 91, 70] 197 | #%% 198 | """ 199 | We use a method of lists to sort numlist. It permanently reorders the list. 200 | """ 201 | print(numlist) 202 | numlist.sort() 203 | print(numlist) 204 | #%% 205 | """ 206 | Note that we already have a way of doing this sort. This doesn't permanently 207 | change the list. 208 | """ 209 | print(sorted(numlist)) 210 | #%% 211 | """ 212 | Below we make a random list of 10 letters of the alphabet. By setting the 213 | random seed, we insure that it generates the same list every time it is run. 214 | """ 215 | #%% 216 | def make_alpha_list(): 217 | import random 218 | alphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o', 219 | 'p','q','r','s','t','u','v','w','x','y','z'] 220 | random.seed(17) 221 | 222 | alpha_list = [] 223 | for i in range(0,10): 224 | alpha_list.append(random.choice(alphabet)) 225 | return alpha_list 226 | #%% 227 | """ 228 | Here we give the variable alphlist the value returned by make_alpha_list() 229 | """ 230 | alphlist = make_alpha_list() 231 | #%% 232 | alphlist = ['q', 'n', 'z', 'j', 'l', 'j', 'f', 'y', 'w', 'w'] 233 | #%% 234 | print(alphlist) 235 | alphlist.sort() 236 | print(alphlist) 237 | #%% 238 | Alphlist = ['e', 'F', 'h', 'A', 'D', 'F', 'b', 'D', 'b', 'J'] 239 | #%% 240 | # notice following is unsatisfactory for sorting mixed upper/lower case 241 | print(Alphlist) 242 | Alphlist.sort() 243 | print(Alphlist) 244 | #%% 245 | # specifying the proper key fixes the problem 246 | print(Alphlist) 247 | Alphlist.sort(key=str.lower) 248 | print(Alphlist) 249 | #%% 250 | strlist = ['now', 'is', 'the', 'time', 'for', 'all', 251 | 'good','men', 'to', 'come', 'to', 'the','aid', 'of', 'their', 'country'] 252 | #%% 253 | print(strlist) 254 | strlist.sort() 255 | print(strlist) 256 | #%% 257 | Strlist = ['Now', 'is', 'The', 'time', 'For', 'All', 258 | 'Good','men', 'To', 'come', 'to', 'the','aid', 'of', 'Their', 'country'] 259 | #%% 260 | # Note that all capital letters sort before lower case 261 | print(Strlist) 262 | Strlist.sort() 263 | print(Strlist) 264 | #%% 265 | # this treats all capital letters as if they were lower case 266 | print(Strlist) 267 | Strlist.sort(key=str.lower) 268 | print(Strlist) 269 | #%% 270 | 271 | """ 272 | DESCRIPTIVE STATISTICS 273 | 274 | Go to docs.python.org/3/ and search statistics. Go to that library. 275 | You can alternatively, go to Help>Python Documention in Spyder and search 276 | statistics in the index. You see the same thing. 277 | """ 278 | #%% 279 | nlist = [2, 4, 13, 3, 7, 8, 5] 280 | nlisteven = nlist + [9] 281 | rlist = [3.14, 2.71, -8.43, 5.25, 10.11, -23.78, 44.45] 282 | rlisteven = rlist + [90.3] 283 | #%% 284 | import statistics 285 | #%% 286 | statistics.mean(nlist) 287 | #%% 288 | statistics.mean(rlist) 289 | #%% 290 | print(nlist) 291 | print(sorted(nlist)) # print sorted version of nlisteven to see median 292 | #%% 293 | statistics.median(nlist) 294 | #%% 295 | print(nlisteven) 296 | print(sorted(nlisteven)) # print sorted version of nlisteven to see median 297 | #%% 298 | statistics.median(nlisteven) # note that it averages the two middle values 299 | #%% 300 | print(rlist) 301 | print(sorted(rlist)) # print sorted version of rlist to see median 302 | #%% 303 | statistics.median(rlist) 304 | #%% 305 | print(rlisteven) 306 | print(sorted(rlisteven)) # print sorted version of rlisteven to see median 307 | #%% 308 | statistics.median(rlisteven) # note that it averages the two middle values 309 | #%% 310 | mlist = [2, 3, 4, 5, 4, 5, 3, 6, 1, 3, 4, 3] 311 | #%% 312 | print(mlist) 313 | print(sorted(mlist)) # print sorted version of mlist to see mode 314 | #%% 315 | statistics.mode(mlist) 316 | #%% 317 | statistics.stdev(rlist) 318 | #%% 319 | statistics.variance(rlist) 320 | #%% 321 | """ 322 | list functions --- max, min, sum 323 | """ 324 | #%% 325 | nlis = [3.14,-4,25,8,106,32] 326 | print("the maximum of nlis is",max(nlis)) 327 | print("the minimum of nlis is",min(nlis)) 328 | print("the sum of nlis is",sum(nlis)) 329 | #%% 330 | """ 331 | USING DESCRIPTIVE STATISTICS; TRY/EXCEPT ERROR HANDLING 332 | Example: Compute the statistics for the following list 333 | """ 334 | """ First let's generate a 100 random reals between 5000 and 6000 """ 335 | #%% 336 | import random 337 | stat_list = [] 338 | for i in range(0,100): 339 | stat_list.append(1000*random.random()+5000) 340 | 341 | ilis = [3, 1, 5, 2, 1, 3, 7, 3] 342 | #%% 343 | def my_stats(slis): 344 | import statistics 345 | print("Mean: ", statistics.mean(slis)) 346 | print("Median: ", statistics.median(slis)) 347 | # print("Mode: ", statistics.mode(slis)) 348 | try: 349 | print("Mode: ", statistics.mode(slis)) 350 | except statistics.StatisticsError as e: 351 | print("Mode error: ", e) 352 | print("Standard Deviation: ", statistics.stdev(slis)) 353 | print("Variance: ", statistics.variance(slis)) 354 | 355 | #%% 356 | """ 357 | A simple example of try/except error catching. If the user inputs a number 358 | then all is fine; if the user enters a non-number, then the exception is 359 | caught and printed out. 360 | """ 361 | #%% 362 | def test_try(): 363 | numb = input("Enter a number: ") 364 | print(type(numb)) 365 | try: 366 | num = float(numb) 367 | print(num) 368 | except Exception as e: 369 | print("Exception was: ", e) 370 | #%% 371 | """ 372 | Exercise: 373 | Write a function temp_stat(temps) to compute the average, median, standard 374 | deviation and variance of the temperatures in the table. Print each out. 375 | The following code generates the same temperatures each time because the seed 376 | is set. Print the temperature list as the first line of the function. 377 | 378 | Here is what my run on the table of temperatures built below looks like: 379 | 380 | temp_stat(temperatures) 381 | [52, 61, 45, 50, 44, 34, 57, 80, 91, 50, 38, 91, 84, 20, 55, 23, 83, 42, 44, 84] 382 | Mean: 56.4 383 | Median: 51.0 384 | Standard deviation: 22.04397518836526 385 | Variance: 485.9368421052631 386 | 387 | """ 388 | #%% 389 | import random 390 | random.seed(77) 391 | temperatures = [] 392 | for i in range(0,20): 393 | temperatures.append(random.randint(20,95)) 394 | #%% 395 | """ 396 | Solution: 397 | """ 398 | #%% 399 | def temp_stat(temps): 400 | """ prints the average, median, std dev, and variance of temps """ 401 | pass # replace this pass (a do-nothing) statement with your code 402 | #%% 403 | """ 404 | Solution: 405 | """ 406 | #%% 407 | def temp_stat(temps): 408 | """ prints the average, median, std dev, and variance of temps """ 409 | import statistics 410 | print(temps) 411 | print("Mean: ", statistics.mean(temps)) 412 | print("Median: ", statistics.median(temps)) 413 | 414 | print("Standard deviation: ", statistics.stdev(temps)) 415 | print("Variance: ", statistics.variance(temps)) 416 | 417 | 418 | 419 | 420 | 421 | 422 | 423 | 424 | 425 | 426 | 427 | 428 | #%% 429 | """ 430 | End solution 431 | """ 432 | """ 433 | Exercise: 434 | Add computing 'mode' to your solution to last exercise. In the temperature 435 | list that we constructed, there is no unique mode, so that the program will 436 | crash unless you use try/except error handling. See if you can add this 437 | feature to your solution. 438 | 439 | Note: if you change the seed to 277, then you will get a list that does have 440 | a unique mode. You might like to try that. 441 | 442 | Here is a run of my solution: 443 | 444 | temp_stat(temperatures) 445 | [52, 61, 45, 50, 44, 34, 57, 80, 91, 50, 38, 91, 84, 20, 55, 23, 83, 42, 44, 84] 446 | Mean: 56.4 447 | Median: 51.0 448 | Standard deviation: 22.04397518836526 449 | Variance: 485.9368421052631 450 | Mode error: no unique mode; found 4 equally common values 451 | 452 | """ 453 | """ 454 | Solution: 455 | """ 456 | #%% 457 | def temp_stat(temps): 458 | """ computes the average, median, std dev, and variance of temps """ 459 | pass # replace this pass (a do-nothing) statement with your code 460 | 461 | #%% 462 | """ 463 | Solution: 464 | """ 465 | #%% 466 | def temp_stat(temps): 467 | """ computes the average, median, std dev, and variance of temps """ 468 | import statistics 469 | print(temps) 470 | print("Mean: ", statistics.mean(temps)) 471 | print("Median: ", statistics.median(temps)) 472 | 473 | print("Standard deviation: ", statistics.stdev(temps)) 474 | print("Variance: ", statistics.variance(temps)) 475 | try: 476 | print("Mode: ", statistics.mode(temps)) 477 | except statistics.StatisticsError as e: 478 | print("Mode error: ", e) 479 | 480 | 481 | 482 | 483 | 484 | 485 | 486 | #%% 487 | 488 | """ 489 | FORMATING -- A BRIEF INTRODUCTION 490 | 491 | Let's define a string and use the format method of strings to make a spiffier 492 | printout. Suppose we wanted to print a person's name, age, and weight. Here is 493 | a very brief introduction using name, age, and weight to illustrate. 494 | """ 495 | #%% 496 | nam1 = '"Teddy" Roosevelt' 497 | nam2 = 'Theodore "Teddy" Roosevelt' 498 | age = 60 499 | wt = 199.1515115 500 | #%% 501 | # minimal formating -- {n} represents data item n --- notice misalignment 502 | out1 = "name: {0} age: {1} weight: {2}" 503 | #%% 504 | print("name: {0} age: {1} weight: {2}".format(nam1,age,wt)) 505 | print("name: {0} age: {1} weight: {2}".format(nam2,age,wt)) 506 | #%% 507 | # better formatting > means right align (< and ^ would be left and center) 508 | # the numbers represent the minimum characters occupied by the datum. 509 | out2 = "name: {0:>26} age: {1:>4} weight: {2:>10}" 510 | #%% 511 | print("name: {0:>26} age: {1:>4} weight: {2:>10}".format(nam1,age,wt)) 512 | print("name: {0:>26} age: {1:>4} weight: {2:>10}".format(nam2,age,wt)) 513 | #%% 514 | # for the float (real number), allocate 5 spaces with 2 to the right of "." 515 | out3 = "name: {0:>26} age: {1:>4} weight: {2:>5.2f}" 516 | #%% 517 | print("name: {0:>26} age: {1:>4} weight: {2:>5.2f}".format(nam1,age,wt)) 518 | print("name: {0:>26} age: {1:>4} weight: {2:>5.2f}".format(nam2,age,wt)) 519 | #%% 520 | """ 521 | Note: we can use the string variable out3 in the print statement: 522 | """ 523 | #%% 524 | print(out3.format(nam1,age,wt)) 525 | print(out3.format(nam2,age,wt)) 526 | #%% 527 | s = "my short string" 528 | n = 5.1234 529 | #%% 530 | print("Start||{0:25}||End".format(s)) 531 | #%% 532 | #%% 533 | print("Start||{0:25}||End".format(n)) 534 | #%% 535 | """ 536 | Exercise: 537 | Execute the following string and use it to try some of the following in the 538 | print("Start||{???}||End".format(s)) statement that would enable you to see 539 | what the format has done. You can change what is in the {0: } quickly, 540 | Ctrl-Enter to execute and see the result. Or you can up-arrow and modify 541 | the previous version. 542 | a) Use {0} to just print the string with no formating; {} does the same thing 543 | b) Use {0:25} to print the string allowing a width of 25 characters for it 544 | c) Use {0:>25} to print the string right-aligned in a space of 25 characters 545 | d) Use {0:<25} to print the string left-aligned in a space of 25 characters 546 | e) Use {0:^25} to print the string centered in a space of 25 characters 547 | 548 | Here is what my output looked like: 549 | Start||hello, there||End 550 | Start||hello, there ||End - minimum width 25 551 | Start|| hello, there||End - width 25, right aligned 552 | Start||hello, there ||End - width 25, left aligned 553 | Start|| hello, there ||End - width 25, centered 554 | """ 555 | #%% 556 | """ Execute this. It is the string to work with: """ 557 | #%% 558 | s = "hello, there" 559 | #%% 560 | """ The format statement to modify and work with: """ 561 | #%% 562 | print("Start||{}||End".format(s)) 563 | #%% 564 | """ 565 | Solution: 566 | """ 567 | s = "hello, there" 568 | #%% 569 | """ 570 | Solution: 571 | """ 572 | s = "hello, there" 573 | print("Start||{0}||End".format(s)) # a 574 | print("Start||{0:25}||End - minimum width 25".format(s)) #b 575 | print("Start||{0:>25}||End - width 25, right aligned".format(s)) #c 576 | print("Start||{0:<25}||End - width 25, left aligned".format(s)) #d 577 | print("Start||{0:^25}||End - width 25, centered".format(s)) #e 578 | 579 | 580 | 581 | 582 | """ 583 | End Solution 584 | """ 585 | #%% 586 | 587 | """ 588 | A SMALL DATABASE APPLICATION USING WHAT WE'VE LEARNED. 589 | 590 | The following uses a CSV file to store the data for a small telephone directory. 591 | It is menu driven. That is, it presents a menu of choices. These choices are 592 | to show the whole directory, create a new entry for the directory, delete an 593 | entry from the directory, and edit an entry in the directory. 594 | """ 595 | #%% 596 | # -phones.py *- coding: utf-8 -*- 597 | """ 598 | This was written as a basic program that did little at first. Additional 599 | features were added until it was finished. 600 | Here is a first version. 601 | phones.py 602 | Version 1 -- builds the menu -- functions are empty 603 | """ 604 | 605 | def delete_phone(): 606 | print("Deleting") 607 | 608 | def edit_phone(): 609 | print("Editing") 610 | 611 | def save_phone_list(): 612 | print("Saving") 613 | 614 | def load_phone_list(): 615 | print("Loading") 616 | 617 | def show_phones(): 618 | print("Showing phones") 619 | 620 | def create_phone(): 621 | print("Adding a phone") 622 | 623 | def menu_choice(): 624 | """ Find out what the user wants to do next. """ 625 | print("Choose one of the following options?") 626 | print(" s) Show") 627 | print(" n) New") 628 | print(" d) Delete") 629 | print(" e) Edit") 630 | print(" q) Quit") 631 | choice = input("Choice: ") 632 | if choice.lower() in ['n','d', 's','e', 'q']: 633 | return choice.lower() 634 | else: 635 | print(choice +"?" + " That is an invalid option!!!") 636 | return None 637 | 638 | 639 | def main_loop(): 640 | 641 | load_phone_list() 642 | 643 | while True: 644 | choice = menu_choice() 645 | if choice == None: 646 | continue 647 | if choice == 'q': 648 | print( "Exiting...") 649 | break # jump out of while loop 650 | elif choice == 'n': 651 | create_phone() 652 | elif choice == 'd': 653 | delete_phone() 654 | elif choice == 's': 655 | show_phones() 656 | elif choice == 'e': 657 | edit_phone() 658 | else: 659 | print("Invalid choice.") 660 | 661 | save_phone_list() 662 | 663 | 664 | # The following makes this program start running at main_loop() 665 | # when executed as a stand-alone program. 666 | if __name__ == '__main__': 667 | main_loop() 668 | #%% 669 | # -phones.py *- coding: utf-8 -*- 670 | """ 671 | Version 2 -- show phones so we can see that the other functions work 672 | """ 673 | 674 | phones = [['Jerry Seinfeld', '(212) 344-3784'], 675 | ['Cosmo Kramer', '(212) 559-8185']] 676 | name_pos = 0 677 | phone_pos = 1 678 | phone_header = [ 'Name', 'Phone Number'] 679 | 680 | 681 | def delete_phone(): 682 | print("Deleting") 683 | 684 | def edit_phone(): 685 | print("Editing") 686 | 687 | 688 | def save_phone_list(): 689 | print("saving") 690 | 691 | def load_phone_list(): 692 | print("loading") 693 | 694 | def show_phones(): 695 | show_phone(phone_header, "") 696 | index = 1 697 | for phone in phones: 698 | show_phone(phone, index) 699 | index = index + 1 700 | print() 701 | 702 | def show_phone(phone, index): 703 | outputstr = "{0:>3} {1:<20} {2:>16}" 704 | print(outputstr.format(index, phone[name_pos], phone[phone_pos])) 705 | 706 | def create_phone(): 707 | print("adding a phone") 708 | 709 | def menu_choice(): 710 | """ Find out what the user wants to do next. """ 711 | print("Choose one of the following options?") 712 | print(" s) Show") 713 | print(" n) New") 714 | print(" d) Delete") 715 | print(" e) Edit") 716 | print(" q) Quit") 717 | choice = input("Choice: ") 718 | if choice.lower() in ['n','d', 's','e', 'q']: 719 | return choice.lower() 720 | else: 721 | print(choice +"?" + " That is an invalid option!!!") 722 | return None 723 | 724 | def main_loop(): 725 | 726 | load_phone_list() 727 | 728 | while True: 729 | choice = menu_choice() 730 | if choice == None: 731 | continue 732 | if choice == 'q': 733 | print( "Exiting...") 734 | break # jump out of while loop 735 | elif choice == 'n': 736 | create_phone() 737 | elif choice == 'd': 738 | delete_phone() 739 | elif choice == 's': 740 | show_phones() 741 | elif choice == 'e': 742 | edit_phone() 743 | else: 744 | print("Invalid choice.") 745 | 746 | save_phone_list() 747 | 748 | 749 | # The following makes this program start running at main_loop() 750 | # when executed as a stand-alone program. 751 | if __name__ == '__main__': 752 | main_loop() 753 | #%% 754 | # -phones.py *- coding: utf-8 -*- 755 | """ 756 | Version 3 -- create phone; delete phone 757 | """ 758 | 759 | phones = [['Jerry Seinfeld', '(212) 344-3784'], 760 | ['Cosmo Kramer', '(212) 559-8185']] 761 | name_pos = 0 762 | phone_pos = 1 763 | phone_header = [ 'Name', 'Phone Number'] 764 | 765 | def proper_menu_choice(which): 766 | if not which.isdigit(): 767 | print ("'" + which + "' needs to be the number of a phone!") 768 | return False 769 | which = int(which) 770 | if which < 1 or which > len(phones): 771 | print ("'" + str(which) + "' needs to be the number of a phone!") 772 | return False 773 | return True 774 | 775 | def delete_phone(which): 776 | if not proper_menu_choice(which): 777 | return 778 | which = int(which) 779 | 780 | del phones[which-1] 781 | print( "Deleted phone #", which) 782 | 783 | def edit_phone(): 784 | print("Editing") 785 | 786 | 787 | def save_phone_list(): 788 | print("saving") 789 | 790 | def load_phone_list(): 791 | print("loading") 792 | 793 | def show_phones(): 794 | show_phone(phone_header, "") 795 | index = 1 796 | for phone in phones: 797 | show_phone(phone, index) 798 | index = index + 1 799 | print() 800 | 801 | def show_phone(phone, index): 802 | outputstr = "{0:>3} {1:<20} {2:>16}" 803 | print(outputstr.format(index, phone[name_pos], phone[phone_pos])) 804 | 805 | def create_phone(): 806 | print("Enter the data for a new phone:") 807 | newname = input("Enter name: ") 808 | newphone_num = input("Enter phone number: ") 809 | phone = [newname,newphone_num] 810 | phones.append(phone) 811 | print() 812 | 813 | def menu_choice(): 814 | """ Find out what the user wants to do next. """ 815 | print("Choose one of the following options?") 816 | print(" s) Show") 817 | print(" n) New") 818 | print(" d) Delete") 819 | print(" e) Edit") 820 | print(" q) Quit") 821 | choice = input("Choice: ") 822 | if choice.lower() in ['n','d', 's','e', 'q']: 823 | return choice.lower() 824 | else: 825 | print(choice +"?" + " That is an invalid option!!!") 826 | return None 827 | 828 | 829 | def main_loop(): 830 | 831 | load_phone_list() 832 | 833 | while True: 834 | choice = menu_choice() 835 | if choice == None: 836 | continue 837 | if choice == 'q': 838 | print( "Exiting...") 839 | break # jump out of while loop 840 | elif choice == 'n': 841 | create_phone() 842 | elif choice == 'd': 843 | which = input("Which item do you want to delete? ") 844 | print("which is ", which) 845 | delete_phone(which) 846 | elif choice == 's': 847 | show_phones() 848 | elif choice == 'e': 849 | edit_phone() 850 | else: 851 | print("Invalid choice.") 852 | 853 | save_phone_list() 854 | 855 | 856 | # The following makes this program start running at main_loop() 857 | # when executed as a stand-alone program. 858 | if __name__ == '__main__': 859 | main_loop() 860 | #%% 861 | # -phones.py *- coding: utf-8 -*- 862 | """ 863 | Version 4 -- edits a phone 864 | """ 865 | 866 | phones = [['Jerry Seinfeld', '(212) 344-3784'], 867 | ['Cosmo Kramer', '(212) 559-8185']] 868 | name_pos = 0 869 | phone_pos = 1 870 | phone_header = [ 'Name', 'Phone Number'] 871 | 872 | def proper_menu_choice(which): 873 | if not which.isdigit(): 874 | print ("'" + which + "' needs to be the number of a phone!") 875 | return False 876 | which = int(which) 877 | if which < 1 or which > len(phones): 878 | print ("'" + str(which) + "' needs to be the number of a phone!") 879 | return False 880 | return True 881 | 882 | def delete_phone(which): 883 | if not proper_menu_choice(which): 884 | return 885 | which = int(which) 886 | 887 | del phones[which-1] 888 | print( "Deleted phone #", which) 889 | 890 | def edit_phone(which): 891 | if not proper_menu_choice(which): 892 | return 893 | which = int(which) 894 | 895 | phone = phones[which-1] 896 | print("Enter the data for a new phone. Press to leave unchanged.") 897 | 898 | print(phone[name_pos]) 899 | newname = input("Enter phone name to change or press return: ") 900 | if newname == "": 901 | newname = phone[name_pos] 902 | 903 | print(phone[phone_pos]) 904 | newphone_num = input("Enter new phone number to change or press return: ") 905 | if newphone_num == "": 906 | newphone_num = phone[phone_pos] 907 | 908 | phone = [newname, newphone_num] 909 | phones[which-1] = phone 910 | 911 | 912 | def save_phone_list(): 913 | print("saving") 914 | 915 | def load_phone_list(): 916 | print("loading") 917 | 918 | def show_phones(): 919 | show_phone(phone_header, "") 920 | index = 1 921 | for phone in phones: 922 | show_phone(phone, index) 923 | index = index + 1 924 | print() 925 | 926 | def show_phone(phone, index): 927 | outputstr = "{0:>3} {1:<20} {2:>16}" 928 | print(outputstr.format(index, phone[name_pos], phone[phone_pos])) 929 | 930 | def create_phone(): 931 | print("Enter the data for a new phone:") 932 | newname = input("Enter name: ") 933 | newphone_num = input("Enter phone number: ") 934 | phone = [newname,newphone_num] 935 | phones.append(phone) 936 | 937 | def menu_choice(): 938 | """ Find out what the user wants to do next. """ 939 | print("Choose one of the following options?") 940 | print(" s) Show") 941 | print(" n) New") 942 | print(" d) Delete") 943 | print(" e) Edit") 944 | print(" q) Quit") 945 | choice = input("Choice: ") 946 | if choice.lower() in ['n','d', 's','e', 'q']: 947 | return choice.lower() 948 | else: 949 | print(choice +"?" + " That is an invalid option!!!") 950 | return None 951 | 952 | 953 | def main_loop(): 954 | 955 | load_phone_list() 956 | 957 | while True: 958 | choice = menu_choice() 959 | if choice == None: 960 | continue 961 | if choice == 'q': 962 | print( "Exiting...") 963 | break # jump out of while loop 964 | elif choice == 'n': 965 | create_phone() 966 | elif choice == 'd': 967 | which = input("Which item do you want to delete? ") 968 | print("which is ", which) 969 | delete_phone(which) 970 | elif choice == 's': 971 | show_phones() 972 | elif choice == 'e': 973 | which = input("Which item do you want to edit? ") 974 | print("which is ", which) 975 | edit_phone(which) 976 | else: 977 | print("Invalid choice.") 978 | 979 | save_phone_list() 980 | 981 | 982 | # The following makes this program start running at main_loop() 983 | # when executed as a stand-alone program. 984 | if __name__ == '__main__': 985 | main_loop() 986 | #%% 987 | # -phones.py *- coding: utf-8 -*- 988 | """ 989 | Version 5 -- saves to a csv file called myphones.csv 990 | """ 991 | import csv 992 | 993 | 994 | phones = [['Jerry Seinfeld', '(212) 344-3784'], 995 | ['Cosmo Kramer', '(212) 559-8185']] 996 | name_pos = 0 997 | phone_pos = 1 998 | phone_header = [ 'Name', 'Phone Number'] 999 | 1000 | def proper_menu_choice(which): 1001 | if not which.isdigit(): 1002 | print ("'" + which + "' needs to be the number of a phone!") 1003 | return False 1004 | which = int(which) 1005 | if which < 1 or which > len(phones): 1006 | print ("'" + str(which) + "' needs to be the number of a phone!") 1007 | return False 1008 | return True 1009 | 1010 | def delete_phone(which): 1011 | if not proper_menu_choice(which): 1012 | return 1013 | which = int(which) 1014 | 1015 | del phones[which-1] 1016 | print( "Deleted phone #", which) 1017 | 1018 | def edit_phone(which): 1019 | if not proper_menu_choice(which): 1020 | return 1021 | which = int(which) 1022 | 1023 | phone = phones[which-1] 1024 | print("Enter the data for a new phone. Press to leave unchanged.") 1025 | 1026 | print(phone[name_pos]) 1027 | newname = input("Enter phone name to change or press return: ") 1028 | if newname == "": 1029 | newname = phone[name_pos] 1030 | 1031 | print(phone[phone_pos]) 1032 | newphone_num = input("Enter new phone number to change or press return: ") 1033 | if newphone_num == "": 1034 | newphone_num = phone[phone_pos] 1035 | 1036 | phone = [newname, newphone_num] 1037 | phones[which-1] = phone 1038 | 1039 | 1040 | def save_phone_list(): 1041 | 1042 | f = open("myphones.csv", 'w', newline='') 1043 | for item in phones: 1044 | csv.writer(f).writerow(item) 1045 | f.close() 1046 | 1047 | def load_phone_list(): 1048 | print("loading") 1049 | 1050 | def show_phones(): 1051 | show_phone(phone_header, "") 1052 | index = 1 1053 | for phone in phones: 1054 | show_phone(phone, index) 1055 | index = index + 1 1056 | print() 1057 | 1058 | def show_phone(phone, index): 1059 | outputstr = "{0:>3} {1:<20} {2:>16}" 1060 | print(outputstr.format(index, phone[name_pos], phone[phone_pos])) 1061 | 1062 | def create_phone(): 1063 | print("Enter the data for a new phone:") 1064 | newname = input("Enter name: ") 1065 | newphone_num = input("Enter phone number: ") 1066 | phone = [newname,newphone_num] 1067 | phones.append(phone) 1068 | 1069 | def menu_choice(): 1070 | """ Find out what the user wants to do next. """ 1071 | print("Choose one of the following options?") 1072 | print(" s) Show") 1073 | print(" n) New") 1074 | print(" d) Delete") 1075 | print(" e) Edit") 1076 | print(" q) Quit") 1077 | choice = input("Choice: ") 1078 | if choice.lower() in ['n','d', 's','e', 'q']: 1079 | return choice.lower() 1080 | else: 1081 | print(choice +"?" + " That is an invalid option!!!") 1082 | return None 1083 | 1084 | 1085 | def main_loop(): 1086 | 1087 | load_phone_list() 1088 | 1089 | while True: 1090 | choice = menu_choice() 1091 | if choice == None: 1092 | continue 1093 | if choice == 'q': 1094 | print( "Exiting...") 1095 | break # jump out of while loop 1096 | elif choice == 'n': 1097 | create_phone() 1098 | elif choice == 'd': 1099 | which = input("Which item do you want to delete? ") 1100 | print("which is ", which) 1101 | delete_phone(which) 1102 | elif choice == 's': 1103 | show_phones() 1104 | elif choice == 'e': 1105 | which = input("Which item do you want to edit? ") 1106 | print("which is ", which) 1107 | edit_phone(which) 1108 | else: 1109 | print("Invalid choice.") 1110 | 1111 | save_phone_list() 1112 | 1113 | 1114 | # The following makes this program start running at main_loop() 1115 | # when executed as a stand-alone program. 1116 | if __name__ == '__main__': 1117 | main_loop() 1118 | 1119 | #%% 1120 | # -phones.py *- coding: utf-8 -*- 1121 | """ 1122 | This program maintains a database of names and phone numbers in a csv 1123 | file called myphones.csv. It is run from the command line and is menu 1124 | driven. To start it, save it in a directory and from the terminal run 1125 | >python phones.py 1126 | It can also be run from this editor in the usual way. 1127 | Version FINAL: 1128 | """ 1129 | import os 1130 | import csv 1131 | 1132 | 1133 | phones = [] 1134 | name_pos = 0 1135 | phone_pos = 1 1136 | phone_header = [ 'Name', 'Phone Number'] 1137 | 1138 | def proper_menu_choice(which): 1139 | if not which.isdigit(): 1140 | print ("'" + which + "' needs to be the number of a phone!") 1141 | return False 1142 | which = int(which) 1143 | if which < 1 or which > len(phones): 1144 | print ("'" + str(which) + "' needs to be the number of a phone!") 1145 | return False 1146 | return True 1147 | 1148 | def delete_phone(which): 1149 | if not proper_menu_choice(which): 1150 | return 1151 | which = int(which) 1152 | 1153 | del phones[which-1] 1154 | print( "Deleted phone #", which) 1155 | 1156 | def edit_phone(which): 1157 | if not proper_menu_choice(which): 1158 | return 1159 | which = int(which) 1160 | 1161 | phone = phones[which-1] 1162 | print("Enter the data for a new phone. Press to leave unchanged.") 1163 | 1164 | print(phone[name_pos]) 1165 | newname = input("Enter phone name to change or press return: ") 1166 | if newname == "": 1167 | newname = phone[name_pos] 1168 | 1169 | print(phone[phone_pos]) 1170 | newphone_num = input("Enter new phone number to change or press return: ") 1171 | if newphone_num == "": 1172 | newphone_num = phone[phone_pos] 1173 | 1174 | phone = [newname, newphone_num] 1175 | phones[which-1] = phone 1176 | 1177 | 1178 | def save_phone_list(): 1179 | 1180 | f = open("myphones.csv", 'w', newline='') 1181 | for item in phones: 1182 | csv.writer(f).writerow(item) 1183 | f.close() 1184 | 1185 | def load_phone_list(): 1186 | if os.access("myphones.csv",os.F_OK): 1187 | f = open("myphones.csv") 1188 | for row in csv.reader(f): 1189 | phones.append(row) 1190 | f.close() 1191 | 1192 | def show_phones(): 1193 | show_phone(phone_header, "") 1194 | index = 1 1195 | for phone in phones: 1196 | show_phone(phone, index) 1197 | index = index + 1 1198 | print() 1199 | 1200 | def show_phone(phone, index): 1201 | outputstr = "{0:>3} {1:<20} {2:>16}" 1202 | print(outputstr.format(index, phone[name_pos], phone[phone_pos])) 1203 | 1204 | def create_phone(): 1205 | print("Enter the data for a new phone:") 1206 | newname = input("Enter name: ") 1207 | newphone_num = input("Enter phone number: ") 1208 | phone = [newname,newphone_num] 1209 | phones.append(phone) 1210 | 1211 | def menu_choice(): 1212 | """ Find out what the user wants to do next. """ 1213 | print("Choose one of the following options?") 1214 | print(" s) Show") 1215 | print(" n) New") 1216 | print(" d) Delete") 1217 | print(" e) Edit") 1218 | print(" q) Quit") 1219 | choice = input("Choice: ") 1220 | if choice.lower() in ['n','d', 's','e', 'q']: 1221 | return choice.lower() 1222 | else: 1223 | print(choice +"?") 1224 | print("Invalid option") 1225 | return None 1226 | 1227 | 1228 | def main_loop(): 1229 | 1230 | load_phone_list() 1231 | 1232 | while True: 1233 | choice = menu_choice() 1234 | if choice == None: 1235 | continue 1236 | if choice == 'q': 1237 | print( "Exiting...") 1238 | break # jump out of while loop 1239 | elif choice == 'n': 1240 | create_phone() 1241 | elif choice == 'd': 1242 | which = input("Which item do you want to delete? ") 1243 | print("which is ", which) 1244 | delete_phone(which) 1245 | elif choice == 's': 1246 | show_phones() 1247 | elif choice == 'e': 1248 | which = input("Which item do you want to edit? ") 1249 | print("which is ", which) 1250 | edit_phone(which) 1251 | else: 1252 | print("Invalid choice.") 1253 | 1254 | save_phone_list() 1255 | 1256 | 1257 | # The following makes this program start running at main_loop() 1258 | # when executed as a stand-alone program. 1259 | if __name__ == '__main__': 1260 | main_loop() 1261 | #%% -------------------------------------------------------------------------------- /Exercises/Exercises4/myphones.csv: -------------------------------------------------------------------------------- 1 | Jerry Seinfeld,(212) 344-3784 2 | George Costanza,(212) 345-8485 3 | -------------------------------------------------------------------------------- /Exercises/Exercises4/phones.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Tue Oct 25 15:46:48 2016 4 | 5 | @author: Abdullah A. Alam 6 | """ 7 | 8 | #%% 9 | # -phones.py *- coding: utf-8 -*- 10 | """ 11 | This program maintains a database of names and phone numbers in a csv 12 | file called myphones.csv. It is run from the command line and is menu 13 | driven. To start it, save it in a directory and from the terminal run 14 | >python phones.py 15 | It can also be run from this editor in the usual way. 16 | Version FINAL: 17 | """ 18 | import os 19 | import csv 20 | 21 | 22 | phones = [] 23 | name_pos = 0 24 | phone_pos = 1 25 | phone_header = [ 'Name', 'Phone Number'] 26 | 27 | def proper_menu_choice(which): 28 | if not which.isdigit(): 29 | print ("'" + which + "' needs to be the number of a phone!") 30 | return False 31 | which = int(which) 32 | if which < 1 or which > len(phones): 33 | print ("'" + str(which) + "' needs to be the number of a phone!") 34 | return False 35 | return True 36 | 37 | def delete_phone(which): 38 | if not proper_menu_choice(which): 39 | return 40 | which = int(which) 41 | 42 | del phones[which-1] 43 | print( "Deleted phone #", which) 44 | 45 | def edit_phone(which): 46 | if not proper_menu_choice(which): 47 | return 48 | which = int(which) 49 | 50 | phone = phones[which-1] 51 | print("Enter the data for a new phone. Press to leave unchanged.") 52 | 53 | print(phone[name_pos]) 54 | newname = input("Enter phone name to change or press return: ") 55 | if newname == "": 56 | newname = phone[name_pos] 57 | 58 | print(phone[phone_pos]) 59 | newphone_num = input("Enter new phone number to change or press return: ") 60 | if newphone_num == "": 61 | newphone_num = phone[phone_pos] 62 | 63 | phone = [newname, newphone_num] 64 | phones[which-1] = phone 65 | 66 | 67 | def save_phone_list(): 68 | 69 | f = open("myphones.csv", 'w', newline='') 70 | for item in phones: 71 | csv.writer(f).writerow(item) 72 | f.close() 73 | 74 | def load_phone_list(): 75 | if os.access("myphones.csv",os.F_OK): 76 | f = open("myphones.csv") 77 | for row in csv.reader(f): 78 | phones.append(row) 79 | f.close() 80 | 81 | def show_phones(): 82 | show_phone(phone_header, "") 83 | index = 1 84 | for phone in phones: 85 | show_phone(phone, index) 86 | index = index + 1 87 | print() 88 | 89 | def show_phone(phone, index): 90 | outputstr = "{0:>3} {1:<20} {2:>16}" 91 | print(outputstr.format(index, phone[name_pos], phone[phone_pos])) 92 | 93 | def create_phone(): 94 | print("Enter the data for a new phone:") 95 | newname = input("Enter name: ") 96 | newphone_num = input("Enter phone number: ") 97 | phone = [newname,newphone_num] 98 | phones.append(phone) 99 | 100 | def menu_choice(): 101 | """ Find out what the user wants to do next. """ 102 | print("Choose one of the following options?") 103 | print(" s) Show") 104 | print(" n) New") 105 | print(" d) Delete") 106 | print(" e) Edit") 107 | print(" q) Quit") 108 | choice = input("Choice: ") 109 | if choice.lower() in ['n','d', 's','e', 'q']: 110 | return choice.lower() 111 | else: 112 | print(choice +"?") 113 | print("Invalid option") 114 | return None 115 | 116 | 117 | def main_loop(): 118 | 119 | load_phone_list() 120 | 121 | while True: 122 | choice = menu_choice() 123 | if choice == None: 124 | continue 125 | if choice == 'q': 126 | print( "Exiting...") 127 | break # jump out of while loop 128 | elif choice == 'n': 129 | create_phone() 130 | elif choice == 'd': 131 | which = input("Which item do you want to delete? ") 132 | print("which is ", which) 133 | delete_phone(which) 134 | elif choice == 's': 135 | show_phones() 136 | elif choice == 'e': 137 | which = input("Which item do you want to edit? ") 138 | print("which is ", which) 139 | edit_phone(which) 140 | else: 141 | print("Invalid choice.") 142 | 143 | save_phone_list() 144 | 145 | 146 | # The following makes this program start running at main_loop() 147 | # when executed as a stand-alone program. 148 | if __name__ == '__main__': 149 | main_loop() 150 | #%% -------------------------------------------------------------------------------- /Programming-Assignment/Problem-Set-3/HumptyDumpty.txt: -------------------------------------------------------------------------------- 1 | Humpty Dumpty sat on a wall, 2 | Humpty Dumpty had a great fall. 3 | All the king's horses and all the king's men 4 | Couldn't put Humpty together again. -------------------------------------------------------------------------------- /Programming-Assignment/Problem-Set-3/ProblemSet3.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Wed Oct 19 13:00:43 2016 4 | 5 | @author: Abdullah A. Alam 6 | """ 7 | 8 | # - ProblemSet3.py *- coding: utf-8 -*- 9 | """ 10 | Problem 3_1: 11 | Write a function that reads a text file and counts the number of letters in it. 12 | Print both the text file and the number of letters. Do this so that the 13 | printout isn't doubled space (use an end= argument in the print statement). 14 | Also, skip a line before printing the count. Note that it is easy to get the 15 | number of letters in each line using the len() function. 16 | Here is my run for HumptyDumpty.txt. Your output should look just like this 17 | for the autograder: 18 | 19 | problem3_1("humptydumpty.txt") 20 | Humpty Dumpty sat on a wall, 21 | Humpty Dumpty had a great fall. 22 | All the king's horses and all the king's men 23 | Couldn't put Humpty together again. 24 | 25 | There are 141 letters in the file. 26 | 27 | """ 28 | #%% 29 | def problem3_1(txtfilename): 30 | """ Opens file and prints its contents line by line. """ 31 | infile = open(txtfilename) 32 | 33 | sum = 0 34 | 35 | for line in infile: 36 | sum = sum + len(line) 37 | print(line, end="") # the file has "\n" at the end of each line already 38 | 39 | print("\n\nThere are", sum, "letters in the file.") 40 | 41 | infile.close() 42 | 43 | 44 | #%% 45 | """ 46 | Problem 3_2: 47 | Below you see three objects which are of collection data type: a list, a tuple, 48 | and a string. Although different in many ways, you can write a 'for' loop that 49 | steps through a "collection" and it will work with all three. This problem 50 | is started for you. Finish it by writing the loop that will step through the 51 | collection and print out its items, one per line. Test it and make sure that 52 | it works for all three of the following data objects. 53 | 54 | Be sure that your code does not include the name of any one of these data 55 | collections. That would stop it from being general enough to deal with a 56 | different collection. 57 | 58 | There is a printout of my run after the problem starter. 59 | """ 60 | #%% 61 | nlis = [23,64,23,46,12,24] # list 62 | atup = ("c","e","a","d","b") # tuple 63 | str1 = "Rumplestilskin" # string 64 | 65 | #%% 66 | def problem3_2(collection): 67 | for i in range(0, len(collection)): 68 | print(collection[i]) 69 | #%% 70 | """ 71 | My runs 72 | problem3_2(nlis) 73 | 23 74 | 64 75 | 23 76 | 46 77 | 12 78 | 24 79 | 80 | problem3_2(atup) 81 | c 82 | e 83 | a 84 | d 85 | b 86 | 87 | problem3_2(str1) 88 | R 89 | u 90 | m 91 | p 92 | l 93 | e 94 | s 95 | t 96 | i 97 | l 98 | s 99 | k 100 | i 101 | n 102 | 103 | """ 104 | """ 105 | Problem 3_3: 106 | Write a function that will convert a date from one format to another. 107 | Specifically, 06/10/2016 should convert to June 17, 2016. Actually, you 108 | will input the 6, the 17, and the 2016 as separate integers (numbers) and 109 | the function will assemble and print the date as June 17, 2016. I suggest 110 | that you create a tuple months = ("January", "February", "March", ...) to 111 | store the names of the months. Then it is easy to access the name February 112 | as months[1] and so on. 113 | 114 | Here is printout of my run. 115 | problem3_3(6,17,2016) 116 | June 17, 2016 117 | 118 | *** Note: for simplicity use 6 and not 06 for numbers; otherwise, the 119 | function will confuse Python and will have to be more complex to work. *** 120 | """ 121 | #%% 122 | def problem3_3(month, day, year): 123 | """ Takes date of form mm/dd/yyyy and writes it in form June 17, 2016 124 | Example6: problem3_5(6, 17, 2016) gives June 17, 2016 """ 125 | 126 | months = ("January", "February", "March", "April", "May", "June", "July", \ 127 | "August", "September", "October", "November", "December") 128 | monthStr = int(month) - 1 129 | print(months[monthStr], str(day) + ",", year) 130 | 131 | 132 | #%% 133 | """ 134 | Problem 3_4: 135 | Write a function that is complementary to the one in the previous problem that 136 | will convert a date such as June 17, 2016 into the format 6/17/2016. I 137 | suggest that you use a dictionary to convert from the name of the month to the 138 | number of the month. For example months = {"January":1, "February":2, ...}. 139 | Then it is easy to look up the month number as months["February"] and so on. 140 | Note that the grader will assume that month names begin with capital letters. 141 | 142 | Here is a printout of my run for June 17, 2016. 143 | 144 | problem3_4("July",17, 2016) 145 | 7/17/2016 146 | 147 | """ 148 | #%% 149 | def problem3_4(mon, day, year): 150 | """ Takes date such as July 17, 2016 and write it as 7/17/2016 """ 151 | months = {"January":1, "February":2, "March":3, "April":4, "May":5, \ 152 | "June":6, "July":7, "August":8, "September":9, "October":10, \ 153 | "November":11, "December":12} 154 | print(str(months[mon]), str(day), year, sep='/') 155 | 156 | 157 | #%% 158 | """ 159 | 160 | Problem 3_5: 161 | Write a function that will look up a phone number given a name. Use this 162 | dictionary of phone numbers in your program, so that the grader will know 163 | what phone numbers are available. In it's simplest form, the program will 164 | crash if a name that isn't in its dictionary is asked for. 165 | 166 | Here is a printout of one of my runs. 167 | 168 | problem3_5("james") 169 | (212) 567-8149 170 | 171 | Below is the start of the program including the dictionary. 172 | """ 173 | #%% 174 | 175 | def problem3_5(name): 176 | """ Looks up the phone number of the person whose name is name """ 177 | 178 | phone_numbers = {"abbie":"(860) 123-4535", "beverly":"(901) 454-3241", \ 179 | "james": "(212) 567-8149", "thomas": "(795) 342-9145"} 180 | dictionary = (phone_numbers[name]) 181 | print(dictionary) 182 | 183 | #%% 184 | """ 185 | Problem 3_6: 186 | Write a program (not just a function, but a stand alone program or script) that 187 | reads through a file and writes another file that gives the length of each line 188 | in the first file. If line is the line that you've read into your program, use 189 | line.strip("\n") to strip away the invisible newline character at the end of 190 | each line. Otherwise, your count will be one higher than the autograder's. 191 | Note that since this is a program running from the Command Window (or terminal 192 | or cmd.exe), it won't be runnable as our usual functions are by entering 193 | Shift-Enter. You should use the File menu in Spyder to create you own file. 194 | But, if you prefer, there is a starter file called problem3_6starter.py. 195 | 196 | Here is a run of my solution program using the HumptyDumpty.txt file. The run 197 | is followed by a printout of HumptyDumpty.txt and the written file 198 | HumptyLength.txt. 199 | 200 | C:>python problem3_6.py humptydumpty.txt humptylength.txt 201 | 202 | C:>type humptydumpty.txt 203 | Humpty Dumpty sat on a wall, 204 | Humpty Dumpty had a great fall. 205 | All the king's horses and all the king's men 206 | Couldn't put Humpty together again. 207 | C:>type humptylength.txt 208 | 28 209 | 31 210 | 44 211 | 35 212 | 213 | 214 | Problem 3_7: 215 | Write a function that would read a CSV file that looks like this, flowers.csv: 216 | 217 | petunia,5.95 218 | alyssum,3.95 219 | begonia,5.95 220 | sunflower,5.95 221 | coelius,4.95 222 | 223 | and look up the price of a flower. Remember to import the necessary library. 224 | 225 | Here is my run on the above CSV file: 226 | problem3_7("flowers.csv","alyssum") 227 | 3.95 228 | 229 | Solution starter: 230 | """ 231 | #%% 232 | import csv 233 | def problem3_7(csv_pricefile, flower): 234 | infile = open(csv_pricefile) 235 | reader = csv.reader(infile) 236 | for row in reader: 237 | if row[0] == flower: 238 | print(row[1]) 239 | 240 | #%% -------------------------------------------------------------------------------- /Programming-Assignment/Problem-Set-3/flowers.csv: -------------------------------------------------------------------------------- 1 | petunia,5.95 2 | alyssum,3.95 3 | begonia,5.95 4 | sunflower,5.95 5 | coelius,4.95 6 | -------------------------------------------------------------------------------- /Programming-Assignment/Problem-Set-3/humptylength.txt: -------------------------------------------------------------------------------- 1 | 28 2 | 31 3 | 44 4 | 35 5 | -------------------------------------------------------------------------------- /Programming-Assignment/Problem-Set-3/problem3_6.py: -------------------------------------------------------------------------------- 1 | """ 2 | Problem 3_6: 3 | Write a program (not just a function, but a stand alone program or script) that 4 | reads through a file and writes another file that gives the length of each line 5 | in the first file. If line is the line that you've read into your program, use 6 | line.strip("\n") to strip away the invisible newline character at the end of 7 | each line. Otherwise, your count will be one higher than the autograder's. 8 | Note that since this is a program running from the Command Window (or terminal 9 | or cmd.exe), it won't be runnable as our usual functions are by entering 10 | Shift-Enter. You should use the File menu in Spyder to create you own file. 11 | But, if you prefer, there is a starter file called problem3_6starter.py. 12 | 13 | Here is a run of my solution program using the HumptyDumpty.txt file. The run 14 | is followed by a printout of HumptyDumpty.txt and the written file 15 | HumptyLength.txt. 16 | 17 | C:>python problem3_6.py humptydumpty.txt humptylength.txt 18 | 19 | C:>type humptydumpty.txt 20 | Humpty Dumpty sat on a wall, 21 | Humpty Dumpty had a great fall. 22 | All the king's horses and all the king's men 23 | Couldn't put Humpty together again. 24 | C:>type humptylength.txt 25 | 28 26 | 31 27 | 44 28 | 35 29 | """ 30 | import sys 31 | 32 | infile = sys.argv[1] 33 | outfile = sys.argv[2] 34 | 35 | infile = open(infile) 36 | outfile = open(outfile, 'w') 37 | 38 | for line in infile: 39 | line = line.strip("\n") 40 | outfile.write(str(len(line)) + "\n") 41 | 42 | infile.close() 43 | outfile.close() -------------------------------------------------------------------------------- /Programming-Assignment/ProblemSet1.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Sat Oct 15 22:19:59 2016 4 | 5 | @author: Abdullah A. Alam 6 | """ 7 | 8 | # - ProblemSet1.py *- coding: utf-8 -*- 9 | """ 10 | Each problem will be a function to write. 11 | 12 | Remember that you can execute just the code between the #%% signs by clicking 13 | somewhere in that space and then using Ctrl-Enter (Cmd-Return on a Mac). An 14 | alternative is to use the second toolbar green triangle or Menu>Run>Run cell. 15 | 16 | On loops especially, you can make an error that causes the program to run 17 | forever. If you don't get immediate response, then this is probably happening. 18 | In that case, try Ctrl-C. If that doesn't stop it click your IPython console 19 | away and open a new one from the Consoles menu. Look over your code and see 20 | why the termination condition can't be met and fix it. Then run again. 21 | 22 | You can submit your work in two ways. One is simply to upload this file. This 23 | is the easiest way to go provided that you haven't corrupted it. To make sure 24 | that it isn't corrupted, run the whole file by clicking the left green triangle 25 | above. If it is corrupted, you can fix it or submit just your function as 26 | described next. 27 | To submit only a single function, copy the material between the two #%% into 28 | a text file (don't use a word processor, use a text editor such as Notepad in 29 | Windows orTextEdit on the Mac) and save it as problemx.py (where x is the 30 | problem number). Upload this file to Coursera. Note that the grading program 31 | is going to run the function with the name specified, so don't change the 32 | function name. 33 | 34 | Note: each of the function below is made runnable by adding the statement 35 | pass. This is a do-nothing statement. You should replace it with your code, 36 | but its present doesn't affect how your code runs. 37 | """ 38 | 39 | """ 40 | Problem 1_1: 41 | Write a function problem1_1() that prints "Problem Set 1". 42 | 43 | Tip: Be careful that your program outputs this exact phrase with no additional 44 | characters. It will be graded automatically and must be precise. 45 | """ 46 | #%% 47 | def problem1_1(): 48 | print ("Problem Set 1") 49 | 50 | 51 | #%% 52 | 53 | """ 54 | Problem 1_2: 55 | Write a function problem1_2(x,y) that prints the sum and product of the 56 | numbers x and y on separate lines, the sum printing first. 57 | """ 58 | #%% 59 | def problem1_2(x,y): 60 | print (x+y) 61 | print (x*y) 62 | 63 | 64 | #%% 65 | """ 66 | Test run. Note that the grader program will use different numbers: 67 | 68 | problem1_2(3,5) 69 | 8 70 | 15 71 | """ 72 | """ 73 | Problem 1_3: 74 | Write a function problem1_3(n) that adds up the numbers 1 through n and 75 | prints out the result. You should use either a 'while' loop or a 'for' loop. 76 | Be sure that you check your answer on several numbers n. Be careful that your 77 | loop steps through all the numbers from 1 through and including n. 78 | 79 | Tip: As this involves a loop you could make an error that causes it to run 80 | forever. Usually Control-C will stop it. See suggestions at the beginning of 81 | this document. With loops take care that your first and last iterations are 82 | what you expect. A print statement can be inserted in the loop to monitor it, 83 | but be sure this isn't in the submitted function. 84 | """ 85 | #%% 86 | def problem1_3(n): 87 | my_sum = 0 88 | for number in range(n+1): 89 | my_sum = my_sum + number 90 | print (my_sum) 91 | 92 | 93 | #%% 94 | """ 95 | Test run. Note that the grader program will use different numbers: 96 | 97 | problem1_3(6) 98 | 21 99 | """ 100 | """ 101 | Problem 1_4: 102 | Write a function 'problem1_4(miles)' to convert miles to feet. There are 103 | 5280 feet in each mile. Make the print out a statement as follows: 104 | "There are 10560 feet in 2 miles." Except for the numbers this state should 105 | be exactly as written. 106 | 107 | Tip: Watch the spacing before and after your numbers. Just one space or the 108 | auto-grader may not give you credit. 109 | """ 110 | #%% 111 | def problem1_4(miles): 112 | feet = 5280*miles 113 | print("There are", feet, "feet in", miles, "miles.") 114 | 115 | 116 | 117 | #%% 118 | """ 119 | Test run. Note that the grader program will use different numbers: 120 | 121 | problem1_4(5) 122 | There are 26400 feet in 5 miles. 123 | """ 124 | """ 125 | Problem 1_5: 126 | Write a function 'problem1_5(age)'. This function should use if-elif-else 127 | statement to print out "Have a glass of milk." for anyone under 7; "Have 128 | a coke." for anyone under 21, and "Have a martini." for anyone 21 or older. 129 | 130 | Tip: Be careful about the ages 7 (a seven year old is not under 7) and 21. 131 | Also be careful to make the phrases exactly as shown for the auto-grader. 132 | """ 133 | #%% 134 | def problem1_5(age): 135 | if age < 7: 136 | print ("Have a glass of milk.") 137 | elif age < 21: 138 | print ("Have a coke.") 139 | else: 140 | print ("Have a martini.") 141 | 142 | 143 | 144 | 145 | 146 | #%% 147 | """ 148 | Test runs (3 of them). Note that the grader program will use different numbers: 149 | problem1_5(5) 150 | Have a glass of milk. 151 | 152 | problem1_5(10) 153 | Have a coke. 154 | 155 | problem1_5(25) 156 | Have a martini. 157 | 158 | """ 159 | """ 160 | Problem 1_6: 161 | Write a function 'problem1_6()' that prints the odd numbers from 1 through 100. 162 | Make all of these numbers appear on the same line (actually, when the line 163 | fills up it will wrap around, but ignore that.). In order to do this, your 164 | print statement should have end=" " in it. For example, print(name,end=" ") 165 | will keep the next print statement from starting a new line. Be sure there is a 166 | space between these quotes or your numbers will run together. Use a single 167 | space as that is what the grading program expects. Use a 'for' loop 168 | and a range() function. 169 | 170 | Things to be careful of that might go wrong: You print too many numbers, you 171 | put too much or too little space between them, you print each number on its 172 | own line, you print even numbers or all numbers, your first number isn't 1 or 173 | your last number isn't 99. Always check first and last outputs when you write 174 | a loop. 175 | """ 176 | #%% 177 | def problem1_6(): 178 | for oddNumber in range(1, 100, 2): 179 | print(oddNumber, end=" ") 180 | 181 | 182 | 183 | 184 | #%% 185 | """ 186 | Test run (I've inserted a newline here to cause wrapping in the editor): 187 | 188 | problem1_6() 189 | 1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49 51 53 55 190 | 57 59 61 63 65 67 69 71 73 75 77 79 81 83 85 87 89 91 93 95 97 99 191 | """ 192 | """ 193 | Problem 1_7: 194 | Write a function problem1_7() that computes the area of a trapezoid. Here is the 195 | formula: A = (1/2)(b1+b2)h. In the formula b1 is the length of one of the 196 | bases, b2 the other. The height is h and the area is A. Basically, this 197 | takes the average of the two bases times the height. For a rectangle b1 = b2, 198 | so this reduces to b1*h. This means that you can do a pretty good test of the 199 | correctness of your function using a rectangle (that way you can compute the 200 | answer in your head). Use input statements to ask for the bases and the height. 201 | Convert these input strings to real numbers using float(). Print the output 202 | nicely exactly like mine below. 203 | 204 | Tip: Be careful that your output on the test case below is exactly as shown 205 | so that the auto-grader judges your output correctly. See the other test run 206 | below. 207 | 208 | In[105]: 209 | 210 | problem1_7() 211 | 212 | Enter the length of one of the bases: 3 213 | 214 | Enter the length of the other base: 4 215 | 216 | Enter the height: 8 217 | The area of a trapezoid with bases 3.0 and 4.0 and height 8.0 is 28.0 218 | 219 | """ 220 | #%% 221 | def problem1_7(): 222 | pass # replace this pass (a do-nothing) statement with your code 223 | b1 = float(input("Enter the length of one of the bases: ")) 224 | b2 = float(input("Enter the length of the other base: ")) 225 | h = float(input("Enter the height: ")) 226 | A = (1/2)*(b1+b2)*h 227 | print("The area of a trapezoid with bases",b1,"and",b2,"and height",h, "is", A) 228 | 229 | 230 | 231 | 232 | 233 | 234 | 235 | #%% 236 | """ 237 | Test run. In grading, expect different input numbers to be used. 238 | 239 | problem1_7() 240 | 241 | Enter the length of one of the bases: 10 242 | 243 | Enter the length of the other base: 11 244 | 245 | Enter the height: 12 246 | The area of a trapezoid with bases 10.0 and 11.0 and height 12.0 is 126.0 247 | 248 | """ 249 | 250 | -------------------------------------------------------------------------------- /Programming-Assignment/ProblemSet2.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Sun Oct 16 23:50:53 2016 4 | 5 | @author: Abdullah A. Alam 6 | """ 7 | 8 | # -ProblemSet2.py *- coding: utf-8 -*- 9 | """ 10 | Each problem will be a function to write. 11 | 12 | Remember that you can execute just the code between the #%% signs by clicking 13 | somewhere in that space and the using Ctrl-Enter (Cmd-Enter on Mac). An 14 | alternative is to use the second toolbar green triangle or Menu>Run>Run cell. 15 | 16 | On loops especially, you can make an error that causes the program to run 17 | forever. If you don't get immediate response, then this is probably happening. 18 | In that case, try Ctrl-C. If that doesn't stop it click your IPython console 19 | away and open a new one. Look over you code and see why the termination 20 | condition can't be met and fix it. Then run again. 21 | 22 | """ 23 | """ 24 | Problem 2_1: 25 | Write a function 'problem2_1()' that sets a variable lis = list(range(20,30)) and 26 | does all of the following, each on a separate line: 27 | (a) print the element of lis with the index 3 28 | (b) print lis itself 29 | (c) write a 'for' loop that prints out every element of lis. Recall that 30 | len() will give you the length of such a data collection if you need that. 31 | Use end=" " to put one space between the elements of the list lis. 32 | """ 33 | #%% 34 | def problem2_1(): 35 | lis = list(range(20,30)) 36 | print(lis[3]) 37 | print(lis) 38 | 39 | for i in lis: 40 | print(i, end = " ") 41 | 42 | 43 | 44 | 45 | 46 | 47 | #%% 48 | """ 49 | Test run: 50 | 51 | problem2_1() 52 | 23 53 | [20, 21, 22, 23, 24, 25, 26, 27, 28, 29] 54 | 20 21 22 23 24 25 26 27 28 29 55 | 56 | """ 57 | """ 58 | Problem 2_2: 59 | Write a function 'problem2_2()' that creates a list called alist. Actually, I've 60 | started the function for you below. Your function should do all of the 61 | following, each on a separate line. Recall that lists start numbering with 0. 62 | 0) print the whole list (this doesn't require a while or for loop) 63 | 1) print the item with index 0 64 | 2) print the last item in the list 65 | 3) print the items with indexes 3 through 5 but not including 5 66 | 4) print the items up to the one with index 3 but not including item 3 67 | 5) print the items starting at index 3 and going through the end. 68 | 6) print the length of the list ( use len() ) 69 | 7) Use the append() method of a list to append the letter "z" onto alist. 70 | Print the list with z appended. 71 | 72 | Make sure that your function also works with blist below. For this to work, 73 | you cannot use alist as a variable inside your function. 74 | """ 75 | #%% 76 | 77 | alist = ["a","e","i","o","u","y"] 78 | blist = ["alpha", "beta", "gamma", "delta", "epsilon", "eta", "theta"] 79 | 80 | def problem2_2(my_list): 81 | print(my_list) 82 | print(my_list[0]) 83 | print(my_list[-1]) 84 | print(my_list[3:5]) 85 | print(my_list[0:3]) 86 | print(my_list[3:]) 87 | print(len(my_list)) 88 | my_list.append("z") 89 | print(my_list) 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | #%% 100 | """ 101 | Test run, two of them. The same function should work with either list. The 102 | grader function will use different lists. 103 | 104 | problem2_2(alist) 105 | ['a', 'e', 'i', 'o', 'u', 'y'] 106 | a 107 | y 108 | ['o', 'u'] 109 | ['a', 'e', 'i'] 110 | ['o', 'u', 'y'] 111 | 6 112 | ['a', 'e', 'i', 'o', 'u', 'y', 'z'] 113 | 114 | problem2_2(blist) 115 | ['alpha', 'beta', 'gamma', 'delta', 'epsilon', 'eta', 'theta'] 116 | alpha 117 | theta 118 | ['delta', 'epsilon'] 119 | ['alpha', 'beta', 'gamma'] 120 | ['delta', 'epsilon', 'eta', 'theta'] 121 | 7 122 | ['alpha', 'beta', 'gamma', 'delta', 'epsilon', 'eta', 'theta', 'z'] 123 | 124 | 125 | """ 126 | 127 | """ 128 | Problem 2_3: 129 | Write a function problem2_3() that should have a 'for' loop that steps 130 | through the list below and prints the name of the state and the number of 131 | letters in the state's name. You may use the len() function. 132 | Here is the output from mine: 133 | In [70]: problem2_3(newEngland) 134 | Maine has 5 letters. 135 | New Hampshire has 13 letters. 136 | Vermont has 7 letters. 137 | Rhode Island has 12 letters. 138 | Massachusetts has 13 letters. 139 | Connecticut has 11 letters. 140 | 141 | The function is started for you. 142 | """ 143 | #%% 144 | newEngland = ["Maine","New Hampshire","Vermont", "Rhode Island", 145 | "Massachusetts","Connecticut"] 146 | 147 | def problem2_3(ne): 148 | for i in range(0, len(ne)): 149 | print(ne[i], "has", len(ne[i]), "letters.") 150 | 151 | 152 | 153 | #%% 154 | """ 155 | Problem 2_4: 156 | random.random() generates pseudo-random real numbers between 0 and 1. But what 157 | if you needed other random reals? Write a program to use random.random() but 158 | generate list of random reals between 30 and 35. This is a simple matter of 159 | multiplication and addition. Print out the list (in list form). 160 | """ 161 | #%% 162 | import random 163 | 164 | def problem2_4(): 165 | """ Make a list of 10 random reals between 30 and 35 """ 166 | random.seed(70) 167 | num_lis = [] 168 | for i in range(10): 169 | n = (random.random() * 5 + 30) 170 | num_lis.append(n) 171 | print(num_lis) 172 | 173 | #%% 174 | """ 175 | COMMENT: Note that this uses a pseudorandom number generator. That means 176 | that the list will be different for each person. But all elements of the list 177 | need to be between 30 and 35 inclusive. How do we do that with the Coursera 178 | grader? 179 | One way to handle this is to issue the command random.seed(70) inside 180 | problem2_4(). Then the list generated will that one given below --- always. 181 | You should use random.random() to generate a random number between 0 and 1 and 182 | then use arithmetic to convert that to a random number in the required range. 183 | 184 | Test run: 185 | 186 | problem2_4() 187 | [34.54884618961936, 31.470395203793395, 32.297169396656095, 30.681793552717807, 188 | 34.97530360173135, 30.773219981037737, 33.36969776732032, 32.990127772708405, 189 | 33.57311858494461, 32.052629620057274] 190 | """""" 191 | Problem 2_5: 192 | Let's do a small simulation. Suppose that you rolled a die repeatedly. Each 193 | time that you roll the die you get a integer from 1 to 6, the number of pips 194 | on the die. Use random.randint(a,b) to simulate rolling a die 10 times and 195 | printout the 10 outcomes. The function random.randint(a,b) will 196 | generate an integer (whole number) between the integers a and b inclusive. 197 | Remember each outcome is 1, 2, 3, 4, 5, or 6, so make sure that you can get 198 | all of these outcomes and none other. Print the list. Make sure that it has 199 | 10 items and they are all in the range 1 through 6. Here is one of my runs. In 200 | the problem below I ask you to set the seed to 171 for the benefit of the 201 | auto-grader. In this example, that wasn't done and so your numbers will be 202 | different. 203 | 204 | problem2_5() 205 | 4 206 | 5 207 | 3 208 | 1 209 | 4 210 | 3 211 | 5 212 | 1 213 | 6 214 | 3 215 | 216 | """ 217 | """ 218 | Problem 2_5: 219 | """ 220 | import random 221 | 222 | def problem2_5(): 223 | """ Simulates rolling a die 10 times.""" 224 | # Setting the seed makes the random numbers always the same 225 | # This is to make the auto-grader's job easier. 226 | random.seed(171) # don't remove when you submit for grading 227 | for i in range(10): 228 | print(random.randint(1,6)) 229 | 230 | #%% 231 | """ 232 | Problem 2_6: 233 | Let's continue with our simulation of dice by rolling two of them. This time 234 | each die can come up with a number from 1 to 6, but you have two of them. The 235 | result or outcome is taken to be the sum of the pips on the two dice. Write a 236 | program that will roll 2 dice and produce the outcome. This time let's roll 237 | the two dice 100 times. Print the outcomes one outcome per line. 238 | """ 239 | #%% 240 | import random 241 | 242 | def problem2_6(): 243 | """ Simulates rolling 2 dice 100 times """ 244 | # Setting the seed makes the random numbers always the same 245 | # This is to make the auto-grader's job easier. 246 | random.seed(431) # don't remove when you submit for grading 247 | for i in range(100): 248 | print(random.randint(1,6) + random.randint(1,6)) 249 | 250 | 251 | 252 | 253 | 254 | #%% 255 | """ 256 | Test run with seed 82: 257 | 258 | problem2_6() 259 | 6 260 | 8 261 | 4 262 | 9 263 | 3 264 | 8 265 | 6 266 | 5 267 | 7 268 | 5 269 | 7 270 | 6 271 | 5 272 | 6 273 | 3 274 | 9 275 | 4 276 | 8 277 | 11 278 | ' 279 | ' 280 | ' 281 | 9 282 | 6 283 | 7 284 | 10 285 | 4 286 | 287 | """ 288 | 289 | """ 290 | Problem 2_7: 291 | Heron's formula for computing the area of a triangle with sides a, b, and c is 292 | as follows. Let s = .5(a + b + c) --- that is, 1/2 of the perimeter of the 293 | triangle. Then the area is the square root of s(s-a)(s-b)(s-c). You can compute 294 | the square root of x by x**.5 (raise x to the 1/2 power). Use an input 295 | statement to get the length of the sides. Don't forget to convert this input 296 | to a real number using float(). Adjust your output to be just like what you 297 | see below. Here is a run of my program: 298 | 299 | problem2_7() 300 | 301 | enter length of side one:3 302 | 303 | enter length of side two:4 304 | 305 | enter length of side three:5 306 | Area of a triangle with sides 3.0 4.0 5.0 is 6.0 307 | 308 | """ 309 | #%% 310 | 311 | def problem2_7(): 312 | """ computes area of triangle using Heron's formula. """ 313 | a = float(input("enter length of side one:")) 314 | b = float(input("enter length of side two:")) 315 | c = float(input("enter length of side three:")) 316 | s = ((.5)*(a+b+c)) 317 | area = ((s*(s-a)*(s-b)*(s-c))**0.5) 318 | print("Area of a triangle with sides",a,b,c,"is",area) 319 | 320 | 321 | #%% 322 | """ 323 | Problem 2_8: 324 | The following list gives the hourly temperature during a 24 hour day. Please 325 | write a function, that will take such a list and compute 3 things: average 326 | temperature, high (maximum temperature), and low (minimum temperature) for the 327 | day. I will test with a different set of temperatures, so don't pick out 328 | the low or the high and code it into your program. This should work for 329 | other hourly_temp lists as well. This can be done by looping (interating) 330 | through the list. I suggest you not write it all at once. You might write 331 | a function that computes just one of these, say average, then improve it 332 | to handle another, say maximum, etc. Note that there are Python functions 333 | called max() and min() that could also be used to do part of the jobs. 334 | """ 335 | #%% 336 | hourly_temp = [40.0, 39.0, 37.0, 34.0, 33.0, 34.0, 36.0, 37.0, 38.0, 39.0, \ 337 | 40.0, 41.0, 44.0, 45.0, 47.0, 48.0, 45.0, 42.0, 39.0, 37.0, \ 338 | 36.0, 35.0, 33.0, 32.0] 339 | #%% 340 | def problem2_8(temp_list): 341 | sum = 0 342 | for i in range(0, len(temp_list)): 343 | sum = sum+temp_list[i] 344 | average = sum/len(temp_list) 345 | print("Average:",average) 346 | print("High:",max(temp_list)) 347 | print("Low:",min(temp_list)) 348 | 349 | 350 | #%% 351 | """ 352 | Sample run using the list hourly_temp. Note that the grader will use a 353 | different hourly list. Be sure that you function works on this list and test 354 | it on at least one other list of your own construction. 355 | problem2_8(hourly_temp) 356 | Average: 38.791666666666664 357 | High: 48.0 358 | Low: 32.0 359 | """ -------------------------------------------------------------------------------- /Programming-Assignment/ProblemSet3.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Wed Oct 19 13:00:43 2016 4 | 5 | @author: Abdullah A. Alam 6 | """ 7 | 8 | # - ProblemSet3.py *- coding: utf-8 -*- 9 | """ 10 | Problem 3_1: 11 | Write a function that reads a text file and counts the number of letters in it. 12 | Print both the text file and the number of letters. Do this so that the 13 | printout isn't doubled space (use an end= argument in the print statement). 14 | Also, skip a line before printing the count. Note that it is easy to get the 15 | number of letters in each line using the len() function. 16 | Here is my run for HumptyDumpty.txt. Your output should look just like this 17 | for the autograder: 18 | 19 | problem3_1("humptydumpty.txt") 20 | Humpty Dumpty sat on a wall, 21 | Humpty Dumpty had a great fall. 22 | All the king's horses and all the king's men 23 | Couldn't put Humpty together again. 24 | 25 | There are 141 letters in the file. 26 | 27 | """ 28 | #%% 29 | def problem3_1(txtfilename): 30 | """ Opens file and prints its contents line by line. """ 31 | infile = open(txtfilename) 32 | 33 | sum = 0 34 | 35 | for line in infile: 36 | sum = sum + len(line) 37 | print(line, end="") # the file has "\n" at the end of each line already 38 | 39 | print("\n\nThere are", sum, "letters in the file.") 40 | 41 | infile.close() 42 | 43 | 44 | #%% 45 | """ 46 | Problem 3_2: 47 | Below you see three objects which are of collection data type: a list, a tuple, 48 | and a string. Although different in many ways, you can write a 'for' loop that 49 | steps through a "collection" and it will work with all three. This problem 50 | is started for you. Finish it by writing the loop that will step through the 51 | collection and print out its items, one per line. Test it and make sure that 52 | it works for all three of the following data objects. 53 | 54 | Be sure that your code does not include the name of any one of these data 55 | collections. That would stop it from being general enough to deal with a 56 | different collection. 57 | 58 | There is a printout of my run after the problem starter. 59 | """ 60 | #%% 61 | nlis = [23,64,23,46,12,24] # list 62 | atup = ("c","e","a","d","b") # tuple 63 | str1 = "Rumplestilskin" # string 64 | 65 | #%% 66 | def problem3_2(collection): 67 | for i in range(0, len(collection)): 68 | print(collection[i]) 69 | #%% 70 | """ 71 | My runs 72 | problem3_2(nlis) 73 | 23 74 | 64 75 | 23 76 | 46 77 | 12 78 | 24 79 | 80 | problem3_2(atup) 81 | c 82 | e 83 | a 84 | d 85 | b 86 | 87 | problem3_2(str1) 88 | R 89 | u 90 | m 91 | p 92 | l 93 | e 94 | s 95 | t 96 | i 97 | l 98 | s 99 | k 100 | i 101 | n 102 | 103 | """ 104 | """ 105 | Problem 3_3: 106 | Write a function that will convert a date from one format to another. 107 | Specifically, 06/10/2016 should convert to June 17, 2016. Actually, you 108 | will input the 6, the 17, and the 2016 as separate integers (numbers) and 109 | the function will assemble and print the date as June 17, 2016. I suggest 110 | that you create a tuple months = ("January", "February", "March", ...) to 111 | store the names of the months. Then it is easy to access the name February 112 | as months[1] and so on. 113 | 114 | Here is printout of my run. 115 | problem3_3(6,17,2016) 116 | June 17, 2016 117 | 118 | *** Note: for simplicity use 6 and not 06 for numbers; otherwise, the 119 | function will confuse Python and will have to be more complex to work. *** 120 | """ 121 | #%% 122 | def problem3_3(month, day, year): 123 | """ Takes date of form mm/dd/yyyy and writes it in form June 17, 2016 124 | Example6: problem3_5(6, 17, 2016) gives June 17, 2016 """ 125 | 126 | months = ("January", "February", "March", "April", "May", "June", "July", \ 127 | "August", "September", "October", "November", "December") 128 | monthStr = int(month) - 1 129 | print(months[monthStr], str(day) + ",", year) 130 | 131 | 132 | #%% 133 | """ 134 | Problem 3_4: 135 | Write a function that is complementary to the one in the previous problem that 136 | will convert a date such as June 17, 2016 into the format 6/17/2016. I 137 | suggest that you use a dictionary to convert from the name of the month to the 138 | number of the month. For example months = {"January":1, "February":2, ...}. 139 | Then it is easy to look up the month number as months["February"] and so on. 140 | Note that the grader will assume that month names begin with capital letters. 141 | 142 | Here is a printout of my run for June 17, 2016. 143 | 144 | problem3_4("July",17, 2016) 145 | 7/17/2016 146 | 147 | """ 148 | #%% 149 | def problem3_4(mon, day, year): 150 | """ Takes date such as July 17, 2016 and write it as 7/17/2016 """ 151 | months = {"January":1, "February":2, "March":3, "April":4, "May":5, \ 152 | "June":6, "July":7, "August":8, "September":9, "October":10, \ 153 | "November":11, "December":12} 154 | print(str(months[mon]), str(day), year, sep='/') 155 | 156 | 157 | #%% 158 | """ 159 | 160 | Problem 3_5: 161 | Write a function that will look up a phone number given a name. Use this 162 | dictionary of phone numbers in your program, so that the grader will know 163 | what phone numbers are available. In it's simplest form, the program will 164 | crash if a name that isn't in its dictionary is asked for. 165 | 166 | Here is a printout of one of my runs. 167 | 168 | problem3_5("james") 169 | (212) 567-8149 170 | 171 | Below is the start of the program including the dictionary. 172 | """ 173 | #%% 174 | 175 | def problem3_5(name): 176 | """ Looks up the phone number of the person whose name is name """ 177 | 178 | phone_numbers = {"abbie":"(860) 123-4535", "beverly":"(901) 454-3241", \ 179 | "james": "(212) 567-8149", "thomas": "(795) 342-9145"} 180 | dictionary = (phone_numbers[name]) 181 | print(dictionary) 182 | 183 | #%% 184 | """ 185 | Problem 3_6: 186 | Write a program (not just a function, but a stand alone program or script) that 187 | reads through a file and writes another file that gives the length of each line 188 | in the first file. If line is the line that you've read into your program, use 189 | line.strip("\n") to strip away the invisible newline character at the end of 190 | each line. Otherwise, your count will be one higher than the autograder's. 191 | Note that since this is a program running from the Command Window (or terminal 192 | or cmd.exe), it won't be runnable as our usual functions are by entering 193 | Shift-Enter. You should use the File menu in Spyder to create you own file. 194 | But, if you prefer, there is a starter file called problem3_6starter.py. 195 | 196 | Here is a run of my solution program using the HumptyDumpty.txt file. The run 197 | is followed by a printout of HumptyDumpty.txt and the written file 198 | HumptyLength.txt. 199 | 200 | C:>python problem3_6.py humptydumpty.txt humptylength.txt 201 | 202 | C:>type humptydumpty.txt 203 | Humpty Dumpty sat on a wall, 204 | Humpty Dumpty had a great fall. 205 | All the king's horses and all the king's men 206 | Couldn't put Humpty together again. 207 | C:>type humptylength.txt 208 | 28 209 | 31 210 | 44 211 | 35 212 | """ 213 | 214 | import sys 215 | 216 | infile = sys.argv[1] 217 | outfile = sys.argv[2] 218 | 219 | infile = open(infile) 220 | outfile = open(outfile, 'w') 221 | 222 | for line in infile: 223 | line = line.strip("\n") 224 | outfile.write(str(len(line)) + "\n") 225 | 226 | infile.close() 227 | outfile.close() 228 | 229 | """ 230 | Problem 3_7: 231 | Write a function that would read a CSV file that looks like this, flowers.csv: 232 | 233 | petunia,5.95 234 | alyssum,3.95 235 | begonia,5.95 236 | sunflower,5.95 237 | coelius,4.95 238 | 239 | and look up the price of a flower. Remember to import the necessary library. 240 | 241 | Here is my run on the above CSV file: 242 | problem3_7("flowers.csv","alyssum") 243 | 3.95 244 | 245 | Solution starter: 246 | """ 247 | #%% 248 | import csv 249 | def problem3_7(csv_pricefile, flower): 250 | infile = open(csv_pricefile) 251 | reader = csv.reader(infile) 252 | for row in reader: 253 | if row[0] == flower: 254 | print(row[1]) 255 | 256 | #%% -------------------------------------------------------------------------------- /Programming-Assignment/ProblemSet4/ProblemSet4.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Mon Oct 24 22:37:16 2016 4 | 5 | @author: Abdullah A. Alam 6 | """ 7 | 8 | # - ProblemSet4.py *- coding: utf-8 -*- 9 | """ 10 | Problem 4_1: 11 | Write a program that will sort an alphabetic list (or list of words) into 12 | alphabetical order. Make it sort independently of whether the letters are 13 | capital or lowercase. First print out the wordlist, then sort and print out 14 | the sorted list. 15 | Here is my run on the list firstline below (note that the wrapping was added 16 | when I pasted it into the file -- this is really two lines in the output). 17 | 18 | problem4_1(firstline) 19 | ['Happy', 'families', 'are', 'all', 'alike;', 'every', 'unhappy', 'family', 20 | 'is', 'unhappy', 'in', 'its', 'own', 'way.', 'Leo Tolstoy', 'Anna Karenina'] 21 | ['alike;', 'all', 'Anna Karenina', 'are', 'every', 'families', 'family', 22 | 'Happy', 'in', 'is', 'its', 'Leo Tolstoy', 'own', 'unhappy', 'unhappy', 'way.'] 23 | 24 | """ 25 | #%% 26 | firstline = ["Happy", "families", "are", "all", "alike;", "every", \ 27 | "unhappy", "family", "is", "unhappy", "in", "its", "own", \ 28 | "way.", "Leo Tolstoy", "Anna Karenina"] 29 | #%% 30 | def problem4_1(wordlist): 31 | """ Takes a word list prints it, sorts it, and prints the sorted list """ 32 | print(wordlist) 33 | wordlist.sort(key=str.lower) 34 | print(wordlist) 35 | 36 | #%% 37 | """ 38 | Problem 4_2: 39 | Write a function that will compute and print the mean and standard deviation 40 | of a list of real numbers (like the following). Of course, the length of the 41 | list could be different. Don't forget to import any libraries that you might 42 | need. 43 | Here is my run on the list of 25 floats create below: 44 | 45 | problem4_2(numList) 46 | 51.528 47 | 30.81215290541488 48 | 49 | """ 50 | #%% 51 | import random 52 | numList = [] 53 | random.seed(150) 54 | for i in range(0,25): 55 | numList.append(round(100*random.random(),1)) 56 | #%% 57 | def problem4_2(ran_list): 58 | """ Compute the mean and standard deviation of a list of floats """ 59 | import statistics 60 | print(statistics.mean(ran_list)) 61 | print(statistics.stdev(ran_list)) 62 | 63 | #%% 64 | """ 65 | Problem 4_3: 66 | Write a function problem4_3(product, cost) so that you can enter the product 67 | and its cost and it will print out nicely. Specifically, allow 25 characters 68 | for the product name and left-justify it in that space; allow 6 characters for 69 | the cost and right justify it in that space with 2 decimal places. Precede the 70 | cost with a dollar-sign. There should be no other spaces in the output. 71 | 72 | Here is how one of my runs looks: 73 | problem4_3("toothbrush",2.6) 74 | toothbrush $ 2.60 75 | 76 | """ 77 | #%% 78 | def problem4_3(product, cost): 79 | """ Prints the product name in a space of 25 characters, left-justified 80 | and the price in a space of 6 characters, right-justified""" 81 | print('{0:<25}'.format(product) + '$' +'{0:>6.2f}'.format(cost)) 82 | 83 | 84 | #%% 85 | """ 86 | Problem 4_4: 87 | This problem is to build on phones.py. You add a new menu item 88 | r) Reorder 89 | This will reorder the names/numbers in the phone list. This may sound difficult 90 | at first thought, but it really is straight forward. You need to add two 91 | lines to the main_loop, one line to menu_choice to print out the new menu 92 | option (and add 'r' to the list of acceptable choices). In addition you 93 | need to add a new function to do the reordering: I called my reorder_phones(). 94 | Here is a start for this very short function: 95 | 96 | def reorder_phones(): 97 | global phones # this insures that we use the one at the top 98 | pass # replace this pass (a do-nothing) statement with your code 99 | 100 | 101 | Note: The auto-grader will run your program, choose menu items s, r, s, and q 102 | in that order. It will provide an unsorted CSV file and see if your program 103 | reorders it appropriately. The grader will provided a version of myphones.csv 104 | that has a different set of names in it from the ones we used in the lesson. 105 | But the result of this added function is shown using the names used in class. 106 | 107 | Before: 108 | Choice: s 109 | Name Phone Number 110 | 1 Jerry Seinfeld (212) 842-2527 111 | 2 George Costanza (212) 452-8145 112 | 3 Elaine Benes (212) 452-8723 113 | After: 114 | Choice: s 115 | Name Phone Number 116 | 1 Elaine Benes (212) 452-8723 117 | 2 George Costanza (212) 452-8145 118 | 3 Jerry Seinfeld (212) 842-2527 119 | 120 | """ -------------------------------------------------------------------------------- /Programming-Assignment/ProblemSet4/myphones.csv: -------------------------------------------------------------------------------- 1 | Elaine Benis,(212) 437-8793 2 | George Costanza,(212) 345-8485 3 | Jerry Seinfeld,(212) 344-3784 4 | -------------------------------------------------------------------------------- /Programming-Assignment/ProblemSet4/phones.py: -------------------------------------------------------------------------------- 1 | #%% 2 | """ 3 | Problem 4_4: 4 | This problem is to build on phones.py. You add a new menu item 5 | r) Reorder 6 | This will reorder the names/numbers in the phone list. This may sound difficult 7 | at first thought, but it really is straight forward. You need to add two 8 | lines to the main_loop, one line to menu_choice to print out the new menu 9 | option (and add 'r' to the list of acceptable choices). In addition you 10 | need to add a new function to do the reordering: I called my reorder_phones(). 11 | Here is a start for this very short function: 12 | 13 | def reorder_phones(): 14 | global phones # this insures that we use the one at the top 15 | pass # replace this pass (a do-nothing) statement with your code 16 | 17 | 18 | Note: The auto-grader will run your program, choose menu items s, r, s, and q 19 | in that order. It will provide an unsorted CSV file and see if your program 20 | reorders it appropriately. The grader will provided a version of myphones.csv 21 | that has a different set of names in it from the ones we used in the lesson. 22 | But the result of this added function is shown using the names used in class. 23 | 24 | Before: 25 | Choice: s 26 | Name Phone Number 27 | 1 Jerry Seinfeld (212) 842-2527 28 | 2 George Costanza (212) 452-8145 29 | 3 Elaine Benes (212) 452-8723 30 | After: 31 | Choice: s 32 | Name Phone Number 33 | 1 Elaine Benes (212) 452-8723 34 | 2 George Costanza (212) 452-8145 35 | 3 Jerry Seinfeld (212) 842-2527 36 | 37 | """ 38 | import os 39 | import csv 40 | 41 | 42 | phones = [] 43 | name_pos = 0 44 | phone_pos = 1 45 | phone_header = [ 'Name', 'Phone Number'] 46 | 47 | def proper_menu_choice(which): 48 | if not which.isdigit(): 49 | print ("'" + which + "' needs to be the number of a phone!") 50 | return False 51 | which = int(which) 52 | if which < 1 or which > len(phones): 53 | print ("'" + str(which) + "' needs to be the number of a phone!") 54 | return False 55 | return True 56 | 57 | def delete_phone(which): 58 | if not proper_menu_choice(which): 59 | return 60 | which = int(which) 61 | 62 | del phones[which-1] 63 | print( "Deleted phone #", which) 64 | 65 | def edit_phone(which): 66 | if not proper_menu_choice(which): 67 | return 68 | which = int(which) 69 | 70 | phone = phones[which-1] 71 | print("Enter the data for a new phone. Press to leave unchanged.") 72 | 73 | print(phone[name_pos]) 74 | newname = input("Enter phone name to change or press return: ") 75 | if newname == "": 76 | newname = phone[name_pos] 77 | 78 | print(phone[phone_pos]) 79 | newphone_num = input("Enter new phone number to change or press return: ") 80 | if newphone_num == "": 81 | newphone_num = phone[phone_pos] 82 | 83 | phone = [newname, newphone_num] 84 | phones[which-1] = phone 85 | 86 | 87 | def save_phone_list(): 88 | 89 | f = open("myphones.csv", 'w', newline='') 90 | for item in phones: 91 | csv.writer(f).writerow(item) 92 | f.close() 93 | 94 | def load_phone_list(): 95 | if os.access("myphones.csv",os.F_OK): 96 | f = open("myphones.csv") 97 | for row in csv.reader(f): 98 | phones.append(row) 99 | f.close() 100 | 101 | def show_phones(): 102 | show_phone(phone_header, "") 103 | index = 1 104 | for phone in phones: 105 | show_phone(phone, index) 106 | index = index + 1 107 | print() 108 | 109 | def show_phone(phone, index): 110 | outputstr = "{0:>3} {1:<20} {2:>16}" 111 | print(outputstr.format(index, phone[name_pos], phone[phone_pos])) 112 | 113 | def reorder_phones(): 114 | global phones # this insures that we use the one at the top 115 | pass # replace this pass (a do-nothing) statement with your code 116 | phones.sort() 117 | 118 | def create_phone(): 119 | print("Enter the data for a new phone:") 120 | newname = input("Enter name: ") 121 | newphone_num = input("Enter phone number: ") 122 | phone = [newname,newphone_num] 123 | phones.append(phone) 124 | 125 | def menu_choice(): 126 | """ Find out what the user wants to do next. """ 127 | print("Choose one of the following options?") 128 | print(" s) Show") 129 | print(" r) Reorder") 130 | print(" n) New") 131 | print(" d) Delete") 132 | print(" e) Edit") 133 | print(" q) Quit") 134 | choice = input("Choice: ") 135 | if choice.lower() in ['r','n','d', 's','e', 'q']: 136 | return choice.lower() 137 | else: 138 | print(choice +"?") 139 | print("Invalid option") 140 | return None 141 | 142 | 143 | def main_loop(): 144 | 145 | load_phone_list() 146 | 147 | while True: 148 | choice = menu_choice() 149 | if choice == None: 150 | continue 151 | if choice == 'q': 152 | print( "Exiting...") 153 | break # jump out of while loop 154 | elif choice == 'n': 155 | create_phone() 156 | elif choice == 'd': 157 | which = input("Which item do you want to delete? ") 158 | print("which is ", which) 159 | delete_phone(which) 160 | elif choice == 's': 161 | show_phones() 162 | elif choice == 'r': 163 | reorder_phones() 164 | elif choice == 'e': 165 | which = input("Which item do you want to edit? ") 166 | print("which is ", which) 167 | edit_phone(which) 168 | else: 169 | print("Invalid choice.") 170 | 171 | save_phone_list() 172 | 173 | 174 | # The following makes this program start running at main_loop() 175 | # when executed as a stand-alone program. 176 | if __name__ == '__main__': 177 | main_loop() 178 | #%% 179 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Python-Programming-A-Concise-Introduction 2 | Python Programming A Concise Introduction 3 | --------------------------------------------------------------------------------