1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 | # Reading from files # Python makes reading input from a file (as opposed to the Python shell) very # simple. In fact, reading multiple lines from files is even easier than # reading them from the shell using input. # Before a program can read data from a file, it must tell the operating system # that it wants to access that file. Files sitting in the same directory as # the running program in IDLE can be reffered to just by using the filename # eg. text.txt. This is the setup we will use in the challenge. # Directories and paths # A directory is the technical name for a folder. Accessing files in other # directories requires extra directions to the file called a path. # There are two kinds of paths: absolute paths and relative paths. # An absolute path starts from a fixed (or absolute) location on disk # called the root(which on Windows is the drive name, like C:). # This means absolute paths can be accessed in the same way from any directory. # On windows, absolute paths therefore start with a drive letter. On Mac OS/X # and Linux, it means an absolute path starts with a forward slate, # Example: /usr/bin/python3.3 # A relative path starts from (that is, is relative to) the current directory # goes from there. The relative path... refers to the parent directory # so ../../data.txt goes up two levels to the parent directory, to find data.txt # Whereas data/colours/rainbox.txt goes down two levels from the current directory # inside data, and then colours to find rainbox.txt # An absolute path is like a set of directions that start from somewhere recognisable # while a relative path is like a set of directions that start from where the # person is standing now. # Opening files # The process of requesting access to a file is called opening a file # just like it is for users, and is done using the builtin function, open or file # This creates a Python file object which we can then read from. For instance: ''' f = open('ncss.txt') for i in f: print(i, end='') ''' # This angle bracket representation is used for types in Python that it doesn't # make sense to print (like the whole contnts of the file). But it lets you # know that the file exists and you've successfuly opened it. # Looping over files # Ok, now after all that it's easy to read from an opened file! # Here's our words.txt file: ''' f = open('ncss.txt') for line in f.readlines(): print(line.strip()) ''' # That's all there is to reading in a file! As you can see it is actually # shorter than using input in a while loop. Notice that we have put a strip # on the print line. That's because line still has the newline character # on the end. Try removing it to see what happens to the output. # Now we can actually make this a bit shorter because we don't need to put the # file in a seperate variable (f), so we can substitute it straight into the for # loop itself: ''' for line in open('ncss.txt'): print(line.strip()) ''' # This produces the same output as the example above and is the # recomended approach to read input from files. ''' with open('ncss.txt') as f: for line in f: print(line.strip()) ''' # Reading a list from a file # Reading from a file into a list is also pretty simple: ''' colours = [] for line in open('ncss.txt'): colours.append(line) print(colours) ''' # Notice that the newline characters are still attached to the end of the string. # To remove the newline characters we would have to chop them off either with # a slice line[:-1] or with a line.strip() which removes whitespace from the # right hand side of the string # Reading a dictionary from a file # Reading from a file into a dictionary is a little more complicated because we # not only want to read the lines, but we also need to split each line into # the key and the value: ''' numbers = {} for line in open('ncss.txt'): english, french = line.split() numbers[english] = french print(numbers['three'], numbers['two'], numbers['one']) ''' # Functions # A function is an independant, named chunk of code that performs a specific # operation. It can be run called by referring to it by name with any information # called arguments it needs to do its job. # By now you will have had lots of experience calling builtin functions like input # or in. Both input and in take a single argument, For input this is the message to # display to the user, eg. 'Enter a number: ', and for int it is the value # to be converted into an integer, eg. '10'. # Different languages (and textbooks) someitimes have different terms for # functions. They may also be called routines, subroutines, subprograms, procedures # messages for methods. Mant languages differentiate procedures from functions # by saying that functions return a value but procedures don't # Since languags like C/C++ and Java have a void or empty return type # (equivalent to None in Python) the distinction no longer makes sense. # Using functions in Python is easy - so east that we have been using them without # really bothering to properly introduce function calls. On the whole, defining # your own functions in Python is straight forward. How ever, there are a number # of tricks that can catch you out occasionally. We mention some of those # things over the next few notes. # The clever thing about functions is that the same bit of code can be called # again and again, rather than having to write out multiple times. If we need # to make a change to that code we only have to do it in one place rather than # each copy. Also, we can use functions to hide complicated code so we don't # have to think about it so carefully when we use it. # Function calls # To call a function you need to know how many arguments the function is expecting # and what type of values they are. For instance, the abs builtin function takes # one argument which must be an integer or float (or a complex number) ''' print(abs(4)) print(abs(-11)) print(abs(-3.14159)) ''' # Hopefully, if the function's purpose is well defined it will be obvious what # information the function needs and why. That is, unless you have a number, then # it is meaningless to ask about it's absolute value! # A function call consits of the function name, which may need to be preceded # (or qualified by the module name, followed by the arguments surrounded by # parentheses). A common mistake is to forget to put the brackets when the function # takes no argumnet # Unfortunately, abs without the parantheses is not an error since abs is a # variable which holds the actual code that performs the absolute value. Typing # abs, is asking to see the contents of the variable, not call the function. # Creating your own function # Functions in Python are created using a definition statement. The def creates # a function from the indented function body and assigns it to the name of the # function. ''' def hello(name): return 'Hello ' + name Name = input('Name: ') print(hello(Name)) ''' # A definition statement consits of the keyword def, followed by the function # name (here hello), and then a list of zero or more arguments in parentheses # (here just one, name). The parentheses must be present even when the function # takes no argument. The def line must end with a colon (like control statements) # The code block of the function must be intended as in control statements # A function to calculate factorials # Here is a function that performs factorial, that is for a number n it calculates # n!=n×(n−1)×(n−2)×…×2×1=∏i=1ni # so 5 factorial, written 5, is 5x4x3x2x1 ''' def fact(n): result = 1 while n > 1: result *= n n = n - 1 return result intt = int(input('Enter number to calculate in fact: ')) print(fact(intt)) ''' # As you can see those factorial numbers get very large vert quickly! # To define a function with more than one arg, you can list multiple arguments # in the parenthesis after the function name, comma seperated. ''' def add_two_nums(a,b): return a+b print(add_two_nums(5, 10)) # 15 ''' # The return statement # As we have seen, some function (such as fact above) need to give the result # of their execution back to the caller, This is done using a return statement. ''' def add(x, y): return x + y r = add(5, 10) print(r) ''' # A return statement immediately terminates the running function and control is # passed back to the called, that is, the line of code the function continues # If return is given an argument, then it is returned to the caller and can be # stored in a variable, used in an expression, or discarded. # If return is not given a value, then no value is returned to the caller # (None is required instead). This is the same as a function which has finished # executing and does not have a return statement. # Exiting a function early # Because a return statement terminates the execution immediately, it is ften used # to exit from a function before the last line of code. ''' def hi(): print('hello') return print('there') hi() ''' # In this example, print('there') will never get called because the return statement, # will cause the function to exit before the second print is reached. # As in the above examples, when a function needs to return an argument, the return # statement is followed by a single expression which is evaluated and returned to # the caller. A return statement can appear anywhere, including inside if, for # and while statements, in which the case the function immediately returns. ''' while 1: def day(name): if name in ['Saturday', 'Sunday']: return 'This is a weekend!' elif name in ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']: return 'This is a weekday!' else: return 'This is not a day!' nam = input('Enter week0finder: ').capitalize() print(day(nam)) ''' # More on function arguments # Another complication is that you can't change values that are passed into a # function: ''' def add_one(x): x += 1 y = 5 add_one(y) print(y) ''' # You might expect that we call this function on a variable, say y, then the value # of y would be incremented by one after the function call, However, running # this shows the value of y = 5 # Outside the function nothing has changed, but x inside the function would have # been incremented by one. This is because Python functions make a copy of # their arguments (called pass by value) rather than access the original variable. # So in the case above, a new local variable x has been created containing a copy # of the contents of the variable y that was passed in as an argument during the function # call. When we modify x inside the function we are only modifying that local # variable. # What this means is that if we want to modify a variable we need to pass it # in to the funtion and then return it, like this: ''' def add_one(x): return x + 1 y = 5 y = add_one(y) print(y) ''' # There is one final complication with passing by value, and that is that Python # data structures are stored as references. We don't want to go into details of # that means now, but the gotcha is that they can be modified (but not assigned) # inside a function call: ''' def append_one(x,c): x.append(1) y = [] append_one(y) print(y) append_one(y) print(y) ''' # More dictionary methods # Sometime you'll need to either retrieve the value for a particular key from the # dictionary, or use a default value if the key doesn't exist. This typically takes # 3 lines of Python. ''' val = 'default' if key in d: val = d[key] ''' # However, getting a key-value pair or default is so common, dictionaries provide the # get method to simplify this: ''' val = d.get(key, 'default') ''' # The first argument to get is the key. If the key is in the dictionary then the # corresponding value is returned, otherwise the second argument to get # (here'default') is returned # If you want to copy the key-value pairs from one dictionary to another, Python # provides the update method. ''' d1 = {'a': 1, 'b': 5} d2 = {'a': 4, 'c': 6} d1.update(d2) print(d1.sort()) ''' # Notice that not only does the new key 'c' have the value 6 from d2, but the # value for a has also been updated to the value from d2. # Miscellaneous string tricks # To make a couple of the questions a bit easier, here are a last couple of # miscellaneous tricks: # Firstly, the string module has some useful constants: ''' import string print(string.punctuation[5]) ''' # If you need to strip off all punctuation, you can now use: ''' x = 'Hello!' print(x.strip(string.punctuation)) ''' # Note that the .strip() method only strips off leading and trailing punctuation. ''' x = '- one - two - three -' print(x.strip(string.punctuation)) ''' |