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)) ''' |
Showing posts with label notes. Show all posts
Showing posts with label notes. Show all posts
Python | Notes ... 3?
Python | Notes 2
just a 'couple' of notes from ncss ;)
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 | # Two kinds of numbers #There are two types of numbers in Python. #Whole numbers (or integers) have the type 'int', and fractional or decimal numbers have the type 'float'. #You can convert between types by casting using the 'int' and 'float' functions: x = 3.5 print(x) # 3.5 print(int(x)) # 3 #Notice that when you cast from a float to an int the result is truncated (not rounded like you are used to in maths). #In Python 3, division alwats returns a float (even when both the original numbers are integers). #For example: correct = 12 total = 15 mark = correct/total print(mark) # 0.8 print(type(mark)) # <class 'float'> #A float is returned even when the result is a whole number: correct = 15 total = 15 mark = correct/total print(mark) # 1.0 print(type(mark)) # <class 'float'> print() # Letters and Words #String are a sequence of characters. String are enclosed in either single or double quotes. #For example print('Hello World') print("Grok's World") #If you need to escape a special character within a string, you can do it by using the backslash. print('Grok\'s world') #You can access a character by indexing or a sequence of characters by slicing: hello = 'Hello World' grok = "Grok's world" print(hello[0], hello[-1], hello[6]) print(grok[5:9], grok[-5:], grok[:4]) #You can check wether a string occurs in another using 'in', for example: hello = 'Hello World' grok = "Grok's world" print('World' in hello) print('cat' in grok) #Some of the arithmetic operators also apply to strings. Addition concatenates strings, and miltiplication #duplicates the string: print('Hello' + 'World') print('Hello'*5 + 'World'*2) #Finally, you can find the length of a string using 'len' msg1 = 'Hello World' print(len(msg1)) # 11 print() # Manipulating strings #Strings come with a wide range builtin methods that allow you to manipulate #and tansform the. We're going to give some examples of some of the most useful one here #You can change the case of a string: msg = 'Hello World' print(msg.upper()) print(msg.lower()) #You can also check the case of a string using isupper and islower. #You can replace substrings within a string: msg = 'Hello World' print(msg.replace('l', 'X')) #And you can count how many times a substring appears within a string: msg = 'Hello World' print(msg.count('l')) #Some other fun methods you might want to try are title, swapcase, startswith and endswith. #Note that srings are immutable, meaning that once the strin is constructed, it cannot be modified. #For example, you cannot change a character in an existing string by assigning a new character to a subscript: msg = 'Hello World' msg[0] = 'X' #Instead, we'll have to creae a new string bu slicing ip the string and concatenating the pieces, and then #assigning the result back to the original variable: msg = 'Hello World' msg = 'X' + msg[1:] print(msg) # Making decisions #To control the flow of a program we often we often need to make decisions depending on whether a #particular condition is True or False. In Python we do this with if... elif... else. #elif is an abbreviation for else and if together. It works like this: x = 5 if x > 3: print('x is less than three') elif x == 3: print('x is equal to three') else: print('x is greater than three') #You can test as many cases as you want by using multiple elif(s). #You can nest if statement inside each other. For example, to do the above without using elif you can do: x = 5 if x < 3: print('x is less than three') else: if x == 3: print('x is equal to three') # Conditional expressions # Operation Operator # equal to == # not equal to != # less than < # less than or equal to <= # greater than > # greater than or equal to >= #You can use a print statement to test these operators in conditional expressions: x = 3 print(x < 10) #This print True because x is less than three x = 3 print(x > 10) #This prints False because 3 is not greater than 10. ##You are at a bake sale and want to choose your cake carefully based on the value for money. ##All the cakes are the same height, but come in different sized square tins, marked by their side lengths. # Enter your code for "Costly cake!" here. cake_len = float(input('Cake 1 side length (cm): ')) cake_cost = float(input('Cake 1 cost ($): ')) cake1 = cake_cost / cake_len**2 cake2_len = float(input('Cake 2 side length (cm): ')) cake2_cost = float(input('Cake 2 cost ($): ')) cake2 = cake2_cost / cake2_len**2 cm1 = round(cake_len**2) cm2 = round(cake2_len**2) print('Cake 1 costs ${:.2f} per cm2 for {} cm2'.format(cake1, cm1)) print('Cake 2 costs ${:.2f} per cm2 for {} cm2'.format(cake2, cm2)) if cake1 < cake2: print('Get cake 1!') elif cake2 < cake1: print('Get cake 2!') # Creating and modifying lists #Lists can be constructed from an existing string using the list builtin function print(list('Hamlet')) #Alternatively, you can create a list by splitting a string: line = "to be or not to be" words = line.split() print(words) #Lists in Python are mutable which means their elements can be changed: name = ['H', 'a', 'm', 'l', 'e', 't'] name[0] = 'Z' print(name) #You can use in to check if a word is in a list line = 'to be or not to be' words = line.split() print('be' in words) print('tree' in words) # Manipulating Lists #There are various list methods that can be used to modify lists. #The append method adds an item to the end of the list: pets = ['dog', 'mouse', 'fish'] pets.append('cat') print(pets) #The sort method sorts the items in order, e.g. strings in alphabetical order and numbers in ascending order. #The reverse method sorts the items in reverse order: pets = ['dog', 'mouse', 'fish', 'cat'] pets.sort() print(pets) pets.reverse() print(pets) #You can create a string from list elements using the join string method: pets = ['dog', 'mouse', 'fish', 'cat'] print(' '.join(pets)) # join on space print('-'.join(pets)) # join on hyphen #Note that the elements are joined by whatever character is in the string: #a space (' ') in the first example, and a hyphen ('-') in the second. # Repeating things #To iterate over a list or range of known length we typically use a for loop. #This executes the indented block of code each iteration. #For example, this program counts how many time the letter 'e' #appears in each word: colours = ['red','green','blue'] for w in colours: print(w, w.count('e')) #To loop over a range of numbers you can use the range function. #It takes three arguments: start, stop and step. #For example, to loop from 0 to the length of a string, in steps of 2 #(in other words, print out every second letter in the string), you can do: word = 'isotope' for i in range(0, len(word), 2): print(i, word[i]) # Repeating things (while) #To iterate while some condition is True we use while loops. #In this example we generate the Fibonacci numbers up to 10: a, b = 0, 1 while b < 30: print(b) a, b = b, a + b #Note that in this example the use of multiple assignment. #The code a, b = 0, 1 sets the variable a to a value of 0 and b to 1 #A common use of while loops is reading input from the user until they write #the correct answer. guess = input("What's the password? ") while guess != "Grok": guess = input("Nope! Try again: ") print("You got it.") #Dictionaries are a type of data structure in Python that store key: value pairs. #In an English dictionary if you look up a word you see that word's definition. #In a Python dictionary, looking up the key returns you the associated value. #This is MY way of writing dictionaries (not really my way) d = dict( DOG = 'bitch please' dog = 'someones calm!!!' this = 'is a dictionary....') ) f = input('sup: ') print(d[f]) #This example creates a small dictionary with silly definitions. #The dictionary associates the key 'dog' with the value 'a barker'. #A colon : is used to separate the keys and the values. ##Should always check if keyword is in dict BEFORE printing it. #There are three key-value pairs (called items) #in this dictionary, one for 'dog', 'cat' and 'bird'. #Notice that when the dictionary is printed, #the key-value pairs are in a different order. #That's because dictionaries don't keep track of the order things are added #(unlike a list) so you can't rely on them being in a particular order. #You can add/change items in a dictionary: animals = {'dog': 'a barker', 'cat': 'a meower', 'bird': 'a tweeter'} # change cat definition: animals['cat'] = 'a purrer' # add a new definition for mouse: animals['mouse'] = 'a squeaker' print(animals) # Creating a dictionary from input #One very common way of creating a dictionary is looping thougth a file #or input from the user. We start with an empt dictionary and add #key-value pairs. Here's an example: phonebook = {} line = input('Name and number: ') while line: name, number = line.split() phonebook[name] = int(number) line = input('Name and number: ') print(phonebook) #Notice how we split each line of input using the string method split #and then once we have each name and number we add an entry to the dictionary. |
Write a program that reads lines of input from the user. An empty line signifies the end of the input. Once your program has read in all of the lines, it should print each line out in the original order with each word reversed in place.
Your program should work like this:
Line: the quick brown fox jumped over the lazy dogs
Line: colourless green ideas sleep furiously
Line: richard of york gave battle in vain
Line:
eht kciuq nworb xof depmuj revo eht yzal sgod
sselruoloc neerg saedi peels ylsuoiruf
drahcir fo kroy evag elttab ni niav
Python | Notes/Classes
This is just something I might print when I get the chance.. ok
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 | #Replacing Text. (REGEX) import re #Defining the 're' module def main(): #Defining a function 'main' - (can be anything) try: #Trying function below, if it is true, it will execute. v = input('What file would you like to run: ') a = input('What text would you like to highlight: ') b = input('What would you like to change it to: ') fh = open (v) #Assigning the variable 'fh' to opening a file 'rotf.txt' pattern = re.compile(a, re.IGNORECASE) #Assigning 'pattern' to a function, which chooses the text and ignores case. for line in fh: #Printing a chosen object in a way defined below. if re.search(pattern, line): #If it finds 'pattern' excute code below it. print(pattern.sub(b, line), end='') #Prints the sentece containing 'pattern' and swaps chosen word with 'pattern.sub' except IOError as e: #If file is not found, print text below and type of error. print('Sorry, file not found!', e) #main() #Calling the 'main' function written above. #________________________________________________________________________________________________# #Checking file name, and if it exists. (RECURSION) def open_file(): #Defining the 're' module try: #If code below is true, try will excute file = input('What file would you like to open: ') #Assigning file to user's choice for line in readlines(file): print(line.strip()) #Printing the file except IOError as e: #If no such file, print this error print('sorry file not found!', e) #What will execute if 'file' is False except ValueError as e: #If bad file name. e.g. '.dic' when it's '.doc' print('bad filename!', e) #What will execute if bad file name def readlines(filename): #A function that will let the user choose a file if filename.endswith('.txt'): #Making sure the filename ends with '.txt' fh = open(filename) #Assigning 'fh' to what the users file choice is return fh.readlines() #Returning the file, with the readlines function else: raise ValueError('File name must end in .txt!') #If bad file name, this executes #open_file() #Calling the function above. #________________________________________________________________________________________________# #Classes class Animal: def talk(self): print('i have something to say') #Default function for 'talk' def walk(self): print('hey, im walking here') #Default function for 'walk' def clothes(self): print('i have nice clothes') #Default function for 'clothes' class Dog(Animal): #Calling a class named 'Dog' and telling it it's an animal def bark(self): #Default result for 'bark' print('woof!') def walk(self): #Default resault for 'walk' (in Dog() only!) super().walk() #Tells the function to use the Default result for walk print('strut!') class Duck(Animal): #Calling a class names dog and assigning it to 'Animal' def clothes(self): #Defining it's 'clothes' print('I have brown and white fur') def Main(): Max = Dog() #Assigning 'Max' to Dog() which can be used later on. Max.bark() #Max's bark Max.walk() #Max's walk Max.clothes() #Max's clothes donald = Duck() #Assigning 'donald' to Duck() donald.walk() #donald's walk donald.talk() #donald's talk donald.clothes() #donald's clothes #Main() #Calling the Main() function #________________________________________________________________________________________________# #Classes class Duck(): #Introduces the definition of a class. def __init__(self, **kwargs): #This is a constructor self.variables = kwargs def quack(self): #Function that prints a line of text. print('Quaaack!') def walk(self): #Function that prints a line of text. print('Walks like a duck.') def set_color(self, color): #Function that sets the color self.variables['color'] = color def get_color(self): #Function that gets the color return self.variables.get('color', None) def set_variable(self, k, v): #K and V represent the var and it's value self.variables[k] = v def get_variable(self, k): #Function that returns what is written return self.variables.get(k, None) def duck(): donald = Duck(feet = 2) #Setting the VAR 'feet' to '2' donald.set_variable('color', 'blue') #Setting the VAR 'color' to 'blue' print(donald.get_variable('feet')) #Printing 'feet' print(donald.get_variable('color')) #Printing 'color' #duck() #________________________________________________________________________________________________# #Classes class Duck: def quack(self): print('Quaaack!') def walk(self): print('Walks like a duck!') def bark(self): print('the duck can not bark!') def fur(self): print('the duck has feathers!') class Dog: def bark(self): print('woof') def fur(self): print('The dog has brown and black fur!') def walk(self): print('Walks like a dog!') def quack(self): print('The dog barks') def animal(): donald = Duck() fido = Dog() in_the_forest(donald) in_the_pond(fido) def in_the_forest(dog): dog.bark() dog.fur() def in_the_pond(duck): duck.quack() duck.walk() #animal() #________________________________________________________________________________________________# #Classes(generator) class inc_range: def __init__(self, *args): numargs = len(args) if numargs < 1: raise TypeError('requires at least one arg') elif numargs == 1: self.stop = args[0] self.start = 0 self.step = 1 elif numargs == 2: (self.start, self.stop) = args self.step = 1 elif numargs == 3: (self.start, self.stop, self.step) = args else: raise TypeError('expected at most 3 arguments, got {}'.format(numargs)) def __iter__(self): i = self.start while i <= self.stop: yield i i += self.step def main(): o = inc_range(0, 30000) for i in o: print(i, end = ' ') #main() #________________________________________________________________________________________________# #Decorators class Duck: def __init__(self, **kwargs): self.properties = kwargs def quack(self): print('Quaaack!') def walk(self): print('Walks like a duck.') def get_properties(self): return self.properties def get_property(self, key): return self.properties.get(key, None) @property def color(self): self.properties.get('color', None) @color.setter def color(self, c): self.properties['color'] = c @color.deleter def color(self): del self.properties['color'] def main(): donald = Duck() donald.color = 'blue' print(donald.color) if __name__ == "__main__": main() #main() #________________________________________________________________________________________________# |
