26 trang cheat sheet Python

26 0 0
26 trang cheat sheet Python

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

26 trang cheat sheet Python 26 trang cheat sheet Python Mình xin chia sẻ 1 cheat sheet rất thú vị về Python. Cheat sheet 26 trang này bao gồm 2 phần chính: • Cheat sheet dành cho các khái niệm, cú pháp cơ bản • Cheat sheet dành cho các thư viện, framework phổ biến trong Python Note: Cheat sheet này định hướng tổng quát chứ KHÔNG chỉ là về AI hay Data Science, Machine Learning các bạn nha

Beginners Python Cheat Sheet Dictionaries squares = [x**2 formation Each iam in a cicth for x in range(1, Slicing a list ‘bob’, 'ada', First_two = finishers{:2] Copyinga liet 2Œ copy_of_bikes Hello world print("Hello nonane List comprehensions finishers = [‘sam', Variables and Strings V Lists (cont.) 11)] A simple dictionary 'bea'] + bikes[:] msg = “Hello world!” print (msg) ‘albert’ last_name = ‘einstein’ name = first name + print (full_name) '° ' + last name TC Nhi Tooele ee, ARE TH ga: ROI equals Laie So I Das oy -N'/.- bikes = ['trek', ‘redline’, Get the first item in a list first_bike = bikes[@] Get the last item in a list last_bike = bikes{ -1] Looping through a list bike in bikes: print(bike) bikes bikes bikes bikes = [] append( ' trek ' ) append( ' redline' ) append( ' giant ' ) Making numerical lists squares = (] for x ín range(1, 'giant'] 11): squares append(x**2) x == 42 x l= 42 x > 42 less x < 42 than or equal to ‘trek’ 'color' ]) can votel”) lí-elif-else statements = ® = 16 ellie _price = 15 na TY sbửao ị xY “) name = input("What's your name? print("“Hello, “ + name + “!") Prompting for numerical input mà if ticket_price print(str(number) + ' is a favorite’) sừyad game_active = True can_edit « False elif age < 18: through all the values fav_numbers = {‘eric': 17, ‘ever’: 4} for number in fav_numbers.values(): x ‹= 42 Assigning boolean values if ageticket_price < 4: tee User input in bikes Sane if age >= 18: print("You An fav_numbers = {‘eric': 17, ‘ever’: 4} for name in fav_numbers.keys(): print(name + ' loves a number’) x >= 42 ‘surly’ not in bikes i Adding items to a list : is ” + alien[{ Looping through all keys Looping not equal greater than or equal to Make a list for dimensions = (1920, 1080) Condgitional tests Lists UC color fav_numbers = {'eric': 17, 'ever': 4} for name, number in fav_numbers.items(): print(name + ' loves ' + str(number)) Making a tuple Concatenation (combining strings) full ACSBESNIG' Value print("The alien's ‘points’: 5} Looping through all key-value pairs world!") = ‘green’, Aaiding anew kay-valie pair alien['x_position'] « @ Hello world with a variable first name alien = {'color': * ¬ input (* Rts St SNe eee pi = input(“What’s pi = float(pi) - the value of pi? Python Crash Course “) Covers Python 3andPython2 | nostarchpress.com/pythoncrashcourse |-*3% : lẻ = While loops ecm, Dp Working with files Classes e repeal se) A simple while loop Reading a file and storing its lines current_value = while current_value = 18: print("You‘re age « old enough to vote!") if age old enough to vote!”) 17 >= 18: print(”You = can"t vote yet,”) 12 age_@ or G19 age_@ age >>> >>> ~ @ age Ø @ « age False ef age < price elif age else: tit aA = price = 18 and age_1 >= 21 print("Your = 23 >= 21 and age >= 21 Conditional >= cost 1s $” + str(príce) + ”.”) tests with lists ndition COINS = 22 ee 18: price 21 heck multi Cục URE 4: & if ee ‘au ` ‘bmw 19 The if-elif-else chain >>> age >>> age@ True Checking for equality age 21 Using and to check multiple conditions if age Conditional Tests condltlonal = else: False true You can use while loops to let your programs run as long as your users want them to [rue age print(“You’re While loops run as long as certain conditions remain  a if-else statements rue lf statements allow you to examine the current state K ceDpern Simple if statement age t= 18 True What ee —— lf Statements and While Loops are if statements? tie Testing equality and inequality Cheat Sheet — What arpa Numerical comparisons Testing if a value is in a 21 or age + 18 >=?= 421 or age_1 e oe ~ >= 21 >= 21 >>> >>> players ‘al’ in z ['al', players list ‘bea’, ‘cyn’, 'dale'| True ea >>> ‘eric’ False in players Ignoring case when making a comparison >>> car = Boolean ‘Audi’ >>> car.lower() True «» Checking for inequality >>> topping >>> topping True = != values ‘audi’ ; ‘mushrooms ‘anchovies’ Simple boolean values game _ active = True can edit = False Python Crash Course PETER Covers Python and Python nostarchpress.com/pythoncrashcourse Conditional tests with lists (cont.) Testing if a value is not in a list banned_users = user « ‘erin’ f« if banned_users: user not [‘ann', in print(”You can if = ‘chad’, ‘dee’] prompt = prompt += “repeat prompt += "\nEnter message play!”) while else: = if have no player.title()) players input message “ + your name name? input("“How int(age) old += “repeat prompt += "\nEnter + if "\nrell message active you.” ‘quit’ to end the banned users I'1l prompt prompt program you? to you.” ‘quit’ to end the 1'11 = program vote!”) can't while vote else: # players.append(player) ‘quit’: False name = raw_input("What's print{"Hello, “ + name + your ”.") while = True: name = input("\nWho print("Nice to meet are you? you, + ”} name name? city == 'quit '; else: print("I've ”) been to + city Accepting input with Sublime Text “ el £?š + “!") Removing all cats from a list of pets pets while = ['dog’, 'cat', ‘rabbit’, ‘dog’, 'cat'] 'fish', current_number ‘cat’ in pets: nets.remove( 'cat ' ) print(pets) current_number = 18: print(“\nYou While f= = ”) Accepting numerical input = « to ‘quit': prompt active = True while active: message « input("What's print("Hello, age age and back input(prompt) prompt Simple input = I= = something, it Using a flag yet!") Vv name me print (message) player in players: print( "Player: + Accepting “" message message [] print("We if “\nTell players: for Using continue in a loop Letting the user choose when to quit Checking if a list is empty players While loops (cont (cont.) loops While More cheat sheets available at ehmatthes.github.io/pcc/ ‘cat’, Positional and keyword arguments Beginners Python Cheat Sheet — Return values Returning a single value Functions What def Using positional arguments are functions? def Functions are named blocks of code designed to one specific job Functions allow you to write code " need, 04g NA and returnthe information generate Using functions effectively makes your programs easier to write, read, test, and fix Defining , TH: rir they deal name < > name): oe sa) F si asp + exerarmeeg name + âä 11 is má “.") def build_person(first, last): "“""Return name): """Display print("\nI information about have a “ + animal print("“Its name " + a + name person pet.""" ",") + “.") musician name='harry ') animale ‘dog’) greeting.”” a single argument Using greet_user(username): """Display a simple greeting.””” “ + greet_user(' jesse’) greet_user( diana’ ) greet_user( ‘brandon’ ) username + ”!”) build person( def None to make a “ + animal + ”.") is “ + name + ".") a if have a name: tả ® print("Its name describe pet(‘hamster’, describe pet(‘ snake‘) + _ age=None): information = {'first': first, ‘last’: last} 'age' ] «= age person = _P : build -P person('jimi', ( ‘hendrix’, l2 ¿s06 anis ', (3 person 1⁄2 TH oplin J9P ) Visualizing functions ng optional animal ‘hendrix’) person print (musician) describe pet(animal, name=None): Display information about a — print("\nI last} age: musician '*hamster") an argument ‘last’: build person(first, last, “““Return a dictionary of musician build or3nt(sasiclan) describe pet(name, animal=‘ dog’): """Display information about a pet.”"” have name information jimi’, person[ print("\nI print("Its Sạn 2X ) Returning a dictionary with optional values if describe pet(‘willie’) print(“Hello, « print(musician) ` s5 y6 person def of first, person about describe _pet('harry', def = {'first': return Using a default value ; a dictionary about a person “one to a function name.’ ti) ‹ return Passing information full Returning a dictionary def greet_user() last): formatted < ies A226, e Default values Passing nm Sarees neatly owe describe_pet(animal, describe pet(names'willie', t("Hello!") en a print (musician) : peer Using keyword arguments describe _pet(animal='hamster’, Making a function def greet_user(): “" "Display a simple prin name(first, MUSA CT describe pet(‘hanster','willie') harry") is full “""Return return full name.title() describe pet('dog’, def a function F bie 2Q pei WR scodbis print("“Its once that can then be run whenever you need to 0/144 in ormation they describe pet(animal, get Python + a is “ + name + = “.”) some Of (nese Crash exa Course Covers Python and Python nostarchpress.com/pythoncrashcourse ‘harry') | | 27 ) Passing an arbitrary number of arguments Passing a list to a function Modules homes Passing a list as an argument Storing a function in a module def greet_users(names): “""Print a simple greeting for name in names: msg = “Hello, " + name to everyone.”"” + “!" print(msg) usernames = [‘hannah', greet_users(usernames) ‘ty’, ‘margot'] Allowing a function to modify a list The following example sends a list of models to a function for printing The original list is emptied, and the second list is filled def print_models(unprinted, printed): “""3d print a set of models.""" while unprinted: current_model = unprinted pop() print("Printing “ + current_model) printed append(current_model) # Store some unprinted designs, # and print each of them unprinted = [‘phone case’, ‘pendant’, printed « [] print_models(unprinted, printed) Collecting an arbitrary number of arguments def make_pizza(size, *toppings): ““"“Make a pizza.""" print("\nMaking a “ + size + “ pizza.") print( “Toppings: ”) for topping in toppings: print("- " + topping) # Make three pizzas with different toppings make _pizza('small', ‘pepperoni’) make_pizza('large’', ‘bacon bits’, 'pineapple') make_pizza('medium’, ‘mushrooms’, ‘peppers’, ‘onions’, ‘extra cheese’) Collecting an arbitrary number of keyword arguments def build profile(first, last, **user_info): “““Build a user's profile đictionary.”"" # Build a dict with the required keys profile = {'first'; first, ‘last’: last} # Add any other keys and values 'ring'] for print(“\nUnprinted:", unprinted) print("Printed:", printed) return Preventing a function from modifying a list The following example is the same as the previous one, except the onginal list is unchanged atter calling print_modets() def print_models{unprinted, printed): “""3d print a set of models.”"" while unprinted: current_model = unprinted pop() print("Printing " + current_model) printed append(current_model) # Store some unprinted designs, # and print each of them original = [‘phone case’, ‘pendant’, printed = [] print_models(original[:], printed) print("\nOriginal:", original) print(”Printed:”, printed) key, value in user_info.items(): profile[key] = value # Create two users with different kinds # of information user_@ = build profile(‘albert', ‘einstein’, location‘ princeton’ ) user = build profile('marie’, 'curie', location='paris', field='chemistry') print(user_9Ø) print(user_1) What's | ‘ring’] profile \ Ol, def make_pizza(size, *toppings): "“"Make a pizza.""" ~ print("\nMaking a “ + size print("Toppings:") for topping in toppings: print("- “ + topping) + " pizza.") Importing an entire module File: making_pizzas.py Every function in the module is available in the program file import pizza pizza.make_pizza( 'medium', ‘pepperoni’) pizza.make_pizza( 'small', ‘bacon’, 'pineapple') Importing a specific function Only the imported functions are available in the program file from pizza import make_pizza make_pizza('medium', ‘pepperoni’ ) make_pízza('small', ‘bacon’, ‘pineapple’) Giving a module an alias import pizza as p p.make_pizza('medium', ‘pepperoni') p.make_pizza('small', ‘bacon’, ‘pineapple') Giving a function an alias from pizza import make_pizza as mp mp('medium', ‘pepperoni’) mp('small', ‘bacon’, ‘pineapple') Importing all functions from a module Don't this, but recognize it when you see it in others’ code It the best way to Structure a function? : File: pizza py ; ; 1) 21 2, i can result in naming conflicts, which can cause errors from pizza import * make_pizza('medium’, ‘pepperoni’ ) make pizza('small', ‘bacon’, 'pineapple') More cheat sheets available at ehmatthes.github.|o/pcc/ Class importing Classes inheritance (cont Classes in Python dy Overriding parent methods ElectricCar(Car): snip-def fill_tank(self): ““"“Display an error message.””" print("This car has no fuel tank!”) Classes should inherit from object class class instances as attributes class A Battery class class Battery({): “"“"“A battery snip class Battery(): """A battery for an electric car.”"" def init_ (self, size=70): “"“Initialize battery attributes.""" # Capacity in kWh, charge level in % self.size = size self.charge_level = @ def get_range(self): “""Return the battery's if self.size == 7@: elif return 248 return 278 self.size == 85: electric attempt to model # Attribute specific to electric self.battery = Battery() for an electric Using the instance my_ecar.charge() print(my_ecar.battery.get_range()) my_ecar.drive() x', class ElectricCar(Car): def init (self, make, model, year): super(ElectricCar, self) init ( make, model, year) car.""" car.""" 2016) Storing objects in a list Importing individual classes from a module my_cars.py car import Car, ElectricCar ‘beetle’, 2016) = car.Car( *volkswagen', my_beetle.fill_tank() my_beetle.drive() ‘model s', = car.ElectricCar( 'tesla', ‘model s', my_tesla.charge() | tesla.drive() my_beetle import 2016) to hold 2016) ‘beetle’, ElectricCar a fleet of cars = [] # Fill the gas cars, and charge for car in gas_fleet: car.fill_tank() for ecar in electric_fleet: ecar.charge() electric cars print("Gas cars:", len(gas_fleet)) print("Electric cars:", len(electric_fleet)) * = Car( ‘volkswagen’, lists Car, # Make 508 gas cars and 2506 electric cars for _ in range(500); car = Car(‘ford’, ‘focus’, 2016) gas_fleet.append(car) for _ in range(250): ecar = ElectricCar( 'nissan', 'leaf', 2916) electric_fleet.append(ecar) Importing all classes from a module car # Make import electric_fleet (Don? this, but recognize it when you see it) from car gas_fleet = [] ‘beetle’, my_tesla A fleet of rental cars from car my_beetle cars class ChildClassName(ParentClass): def init (self): super(ClassName, self) init (} The ElectricCar class in Python 2.7 ElectricCar(Car): “""A simple model of an electric ~-snip import def charge(self): ““"Fully charge the vehicle.""" self battery.charge level = 100 print(”The vehicle is fully charged.") 'model a car.""" Importing an entire module def init (self, make, model, year): “""Initialize an electric car.""" super() init_ (make, model, year) Car(object): Child class init () method is different cars.""" my tesla = ElectricCar('tesla’, 2016) my_tesla.charge() my_tesla.drive() ElectricCar(Car): = ElectricCar('tesla', Car(): “""A simple ~-snip— and my_beetle = Car('volkswagen', my_beetle.fill_tank() my_beetle.drive() snip my_ecar class from range.””" Using an instance as an attribute class class car.py gas ClassName(object): The Car class in Python 2.7 Storing classes in a file “"“"Represent 2.7 2016) More cheat sheets available at ehmatthes.github.lo/pcc/ Beginners Python Cheat Sheet — Files and Exceptions What are files? What are exceptions? Your programs can read information in from files, and Reading from a file (cont.) File paths (cont.) Storing the lines in a Opening a file using an absolute path filename with = f_path ‘'siddhartha.txt' open(filename) lines for list « as f with obj: Opening a file on Windows line in lines: print(line.rstrip()) ssing the Ww Windows will sometimes interpret forward slashes incorrectly tf you run into this, use backsiashes in your file paths f path arourmen with files, and you can store Python structures such as lists in data files Exceptions are special objects that help your programs respond to errors in appropriate ways For example if your program tries to open a file that doesn't exist, you can use exceptions to display an informative error message instead of having the program crash with « with = f.write("I f.write("I Appending to a with Reading an entire file at once with = re a ce s try: = love love ‘w') as print(5/@) except #: creating new games.\n") f 'programming.txt' f.write("I f.write("I also love ‘'a') as can‘t divide by zero!”) Handling the FileNotFoundError exception file open(filename, ZeroDivisionError: print(“You programming! \n") name = 'siddhartha.txt° try: with f: love working with data.\n") making apps as well.\n") Pyti open(f lines name) as f oh]: = f_obj.readlines() except FileNotFoundError: msg = “Can't find file print(msg) File paths When LAI Handling the ZeroDivisionError exception 'siddhartha.txt" open(filename) as f obj: contents = f_obj.read() YUL ‘w') as f: programming!”") ‘programming.txt' open(filename, filename Vy! Writing multiple lines to an empty file Reading from a file filename iF ‘programming.txt' open(filename, f.write("I love filename “C:\Users\ehmatthes\books\alice.txt” The try-except block Writing to an empty file filename = open(f_path) as f_obj: lines = f_obj.readlines() you to work with a wide variety of information; writing to files allows users to pick up where they left off the next time they run your program You can write text to “/home/ehmatthes/books/alice.txt" open(f_path) as f_obj: lines f_obj.readlines() f_obj.readlines() Writing to a file they can write data to files Reading from files allows = {@}.".format(f_name) Knowing which exception to handle } np F fo Know wheal aind of ex: non in print(contents) Reading line by line Each line that's read trom the file has a newline character at the end of the line, and the print function adds its own newline character The rstrip() method gets rid of the the extra blank lines itis would result in when printing to the terminal filename with = ‘siddhartha.txt’ open(filename) as f_obj: for line in f obj: print(line.rstrip()) Opening a # path with file from a subfolder = open(f lines for “text_files/alice.txt" line path) = in as #_obj: f_obj.readlines() lines: print(line.rstrip()) Python Crash Course Covers Python and Python nostarchpress.com/pythoncrashcourse PYTHON CRASH COURSE The else block Failing silently Storing data with json The try block should only contain code that may cause an error Any code that depends on the try block running Successfully snould be piaced in the eise block Sometimes you want your program to just continue running when it encounters an error, without reporting the error to the user Using the pass statement in an else block allows eee enc) The json module allows you to dump simpie Python data structures into a file, and joad the data from that file the next time the program runs The JSON data format is not specitic to Python, so you can share this kind of data with people who work ín other languages as well Using an else block print(“Enter two numbers I'll divide them.”) x = input(“First number: “) y = input("Second number: “) try: result = int(x) / int(y) except ZeroDivisionError: print(“You can*t divide by else: print(result) zero!) Preventing crashes from user input Without the except block in the following example, the program wouild crash if the user tries to divide by zero, As written, it will handie the error gracefully and keep ninning "“""A& simple calculator print(“Enter print("Enter for division only.”"" two numbers I'll ‘q‘ to quit.”) divide them.”) while True: x = input("\nFirst number: “) if x == ‘gq’: break y = input("Second number: ”) if y == 'q': break try: result = int(x) / int(y) except ZeroDivisionError: else: print(“You can't divide by zero!”) print(result) Deciding which errors to report Well-wnitten, properly tested code is not very prone to internal errors such as syntax or logical errors But every time your program depends on something external such as user input or the existence of a file, there's a possibility of an exception being raised It's up to you how to communicate Sometimes users need ta know if a sometimes it’s better to handle the expenence will help you know how errors to your users, file is missing; error silently A little much to report, Using the pass statement in an else block f_names = ["alice,txt', 'siddhartha.txt', 'moby_dick.txt', 'little women.txt' ] for f name in f names; # Report the length of each file found try: with open(f_ name) as f_obj: lines = f_obj.readlines() except FileNotFoundError: # Just move on to the next file pass else: num_lines = len(lines) msg = "{Ø} has {1} lines.".format( f name, num_lines) print (msg) Avoid bare except blocks Exceptlon-handling code should catch specitic exceptions that you expect fo happen during your program's execution A bare except block will catch ail exceptions, including keyboard interrupts and system exits you might need when forcing a program to close lf you want !o use a trự block and you re not sure which exception to catch, use Exception It will catch most exceptions, but still allow you to interrupt programs Knowing how to manage exceptions is important when working with stored data You'll usually want to make sure the data you're trying to load exists before working with it Using json.dump({) to store data “""Store import some json numbers = [2, “""Load import some try: # Do something except Exception as e: print(e, type(e)) previously stored numbers.""" Making sure the stored data exists = Printing the exception 13] print(numbers) f name # Do something except Exception: pass 11, filename = ‘numbers json’ with open(filename) as f_obj: numbers = json load(f_obj) Don't use bare except blocks try: 7, json json Use Exception instead 5, Using json.load() to read data import # Do something except: pass 3, filename = 'numbers json ` wíth open(filename, 'w') as f_obj: json.dump(numbers, f_obj) intentionally try: numbers.""" try: ‘numbers json’ with except open(f_name) as f_obj: numbers = json load(f_obj) FileNotFoundError: msg = “Can’t find {@}.".format(f_name) else: print(msg) print(numbers) Practice with exceptions Take a program you've already written that prompts for user input, and add some error-handling code to the program More cheat sheets available at ehmatthes.github.| 0/pcc/ A failing test (cont.) Building a testcase with one unit test Running the test To build a test case, make a class that inherits from unittest TestCase and write methods that begin with test_ Save this as test_full_names.py class A unit test verifies that one specific aspect of your code works as it's supposed to A test case is a import ERROR: Test NamesTestCase(unittest.TestCase): “““Tests for names.py.""" def test_first_last(self): ""“"“Test names like Janis 1oplin.""" full_name = get_full_name('janis', *4oplin"'} self.assertEqual(full_ name, ‘Janis Joplin’) unittest.main() Running the test Python reports on each unit test in the test case The dot reports a single passing test Python informs us that it ran test in Jess than 0.001 seconds, and the OK lets us know that ail unit tests in the fest case passed Using the function from full_names import get full name janis = get full name('janis', print(janis) bob = get_full_name('bob', print (bob) 'joplin') 'đylan") like Janis Joplin „NamesTestCase) *joplin') TypeError: get_full_name() missing positional argument: ‘last’ test FAILED in required 9.901s (errors#1) Fixing the code When a test fails, the code needs to be modified until the test passes again (Don? make the mistake of rewriting your tests to fit your new code.) Here we can make the middie name aptional def get_full_name(first, last, middle=""): "““Return a full name,”** if middle: full name ô {đ} {1} {2}".format(first, middle, last) else: full_name = “{@} {1}".format(first, last) return full_name.title() A function to test Save this as full_names.py Save this as names.py test first last (_ main_ names Traceback (most recent call last): File “test_full_names.py”, line 16, in test_first_last Ran A passing test def get_full_name(first, last): "“"Return a full name.""" full name « “{@} {1}".format(first, return full name.title() 00 Hate atacaaet E get_full_name collection of unit tests which verify your code’s behavior in a wide variety of situations Testing a function: When you change your code, it's important to run your existing Đen TT'VN Bế Pa 002aThoe ia Chiara existing behavior Running the test Modifying the function last) Weil modify get_full_name() so it handles middle names, but well it in a way thal breaks existing behavior def get full name(first, middle, last): ““"Return a full name.”"" full name = “{@} {1} {2}".format(first, middle, last) return full_name.title() Now the test should pass again, which means our original functionality is still intact Ran test in 0.000s OK Using the function from full_names john import get_full_name = get_full_name( ' john', print(john} david = get_ full name( 'david', print(david) ‘lee’, ‘lee’, "hooker') ‘roth') Python Crash Course Covers Python and Python nostarchpress.com/pythoncrashcourse M import unittest from full_names Why test your code? When you write a function or a class, you can also write tests for that code Testing proves that your code works as it's supposed to in the situations it's designed to handle, and also when people use your programs in unexpected ways Writing tests gives you confidence that your code will work correctly as more people begin to use your programs You can also add new features to your programs and know that you haven't broken existing behavior s Beginners Python Cheat Sheet — Testing Your Code Testinga function (cont.) Adding new Testing a class tests A class to test Testing middie names We've shown that get_full_name() works for first and fast names Let's test that it works for middie names as well import unittest from full_names import Save as accountant py class get_full_name def test_first_last(self): “"““Test names like Janis Joplin.“"" full name = get full name( 'janis', *4oplin') self.assertEqual(full_ name, ‘Janis Joplin’) test_middle(self): “““Test names like David Lee Roth.""" full name = get_full_name( ‘david’, ‘roth’, ‘lee’) self.assertEqual(full_ name, "David Lee Roth’) def import unittest from accountant A variety of assert def test_initial_balance(self): # Default balance should be @ acc * Accountant(}) self.assertEqual(acc.balance, 8) methods b) Verify that x is True, or x is False assertTrue(x) assertFalse(x) Rum : Ran „ ning 100) the class Accountant.""" setUp(self): self.acc * Accountant() 100) def test_deposit(self): # Test single deposit self.acc.deposit (100) self assertEqual(self.acc.balance, 10@) # Test multiple deposits self.acc.deposit(100) self.acc.deposit( 100) self assertEqual(self.acc.balance, 300) # Test single withdrawal self.acc.deposit (1060) self.acc.withdraw(10@) self.assertEqual(self.acc.balance, in 6,00@s nai unittest main() Running the tes ee Ran tests in @.@@1s OK Verify an item is in a list, or not in a list assertIn(item, list) assertNotIn(item, list) @) def test_withdrawal(self): the test test for # Test non-default balance acc * Accountant(196) self.assertEqual(acc.balance, Accountant # Test non-default balance acc = Accountant(190) self.assertEqual(acc.balance, Accountant def test initial balance(self): # Default balance should be @ self.assertEqual(self.acc.balance, unittest.main() Verify that a==b, or a !=b assertEqual(a, b) assertNotEqual(a, import import TestAccountant(unittest.TestCase): “"“Tests def class TestAccountant(unittest.,TestCase): ""*Tests for the class Accountant.""" 0.000s OK class deposit(self, amount): self.balance += amount For the first test, we'll make sure we can start out with different initial balances Save this as test_accountant.py The two dots represent two passing tests in import unittest from accountant Building a testcase Running the tests tests Using stUp) to support multiple test The instance self acc can be used in each new test account.”"" def withdraw(self, amount): self.balance -= amount unittest.main() Ran Accountant(): ""*Manage a bank def init (self, balance«9): self.balance = balance class NamesTestCase(unittest.TestCase): “""Tests for names.py.""" def The setUp() method More cheat sheets available at ehmatthes github.jo/pcc/ 900) Beginner's Python Cheat Sheet - Pygame What is Pygame? Pygame is a framework for making games using Python Making games is fun, and it’s a great way to expand your programming skills and knowledge Pygame rect objects (cont.) Starting a game ee Useful rect attributes Once you have a rect object, there are a number of attributes that are useful when positioning objects and detecting relative positions of objects (You can find more attributes in the Pygame documentation.) An empty game window import sys import pygame def as # pg and set up screen screen aspects of your game that make it interesting # Start while main loop True: # Start for event $ $ sudo apt-get install python3-dev mercurial libsdl-imagel.2-dev libsdl2-dev libsdl-ttf2.0-dev pip install user hge+http: //bitbucket.org/pygame/pygame Pygame on OS X This assumes you've used Homebrew to install Python $ $ brew install hg sdl pip install user herhttp: sdl image sdl ttf //bitbucket.org/pygame/pygame Pygame on Windows run screen The display.set_mode() function accepts a tuple that defines the Screen size Colors are defined as a tuple of red, green, and blue values, value ranges from 0-255 «= (230, 2309, Each 230) color) rect objects If it’s a wehl file, use pip to install Pygame > python -m pip install user To test your instafatlon, open a terminal session and try to import Pygame if you dont get any error messages, your installation was successful $ python >>> >>> import pygame = (190, pg.Rect(199, 190, 199, 3, 15) 190) color, bullet_rect) Working with images Many lets f? 0arneE ãft Loading an image ship = pg.image load( '° images/ship bep ' ) Getting the rect object from an image ship_rect = ship.get_rect() Positioning an image With rects, it's easy to position an image wherever you want on the screen, or in relation to another object The following code positions a ship object al the bottom center of the screen ship rect.midbottom pygame -1., 9, 2a8-cp35-none-win32.whl Testing your installation s dim = (1200, 800) « pg.display.set_mode(screen_dim) Setting a custom background color Pygame rect color pe.draw.rect(screen, screen.fill(bg Find an installer af hitos//oitbucket org’ pygame pygamedownicads/ or http2//www.lic_ uci edu/~gohike’/pythoniibs/#pygame that matches your version of Python Run the installer file if it’s a exe or msi file screen_rect.centery screen_rect.height # Tuples screen_rect,center screen_rect.size bullet Setting a custom window size be color rect.width, object, a color, and a rect This function fills the given rect with the given color _game() screen screen screen_rect.bottom and height of the rect The draw.rect() function takes a screen pg.display.flip() Pygame on Linux values: You can create a rect object from scratch For example a small rect object that's filled in can represent a bullet in a game, The Rect() class takes the coordinates of the upper left comer, and the width event in pg.event.get(): if event.type == pg.QuIT: Refresh y screen_rect.right Creating a rect object loop sys.exit() # and rect.centerx, screen screen = pg.display.set_mode((1200, 89Ø)) pg.display.set_caption("Alien Invasion") in building games, which lets you focus on the x rect.left, screen_rect.top, run_pgame(): # Initialize pg.init() Pygame takes care of many of the lower-level tasks Individual screen = screen_rect.midbottom Getting the screen rect object We already have a screen object; we can easily access the rect object associated wilh the screen screen_rect = screen.get_rect() Finding the center of the screen Rect objects have a center attribute which stores the center point screen_center = screen_rect.center Python Crash Course PYTHON CRASH Covers Python and Python nostarchpress.com/pythoncrashcourse | COURSE Responding to mouse events Working with images (cont.) Pygame groups (cont.) Drawing an image to the screen Once an image is loaded and positioned, you can draw it to the screen with the biit() method, The biil() method acts on the screen object, and takes the image object and image rect as arguments *# Draw ship to screen screen.blit(ship, Game objects such as ships are often written as classes Then a biitme”) method is usually defined, which draws the object to the screen blitme(self): “"““DOraw ship at current location self screen.blit(self.image, “wn self.rect) Responding to keyboard input yoarne waiches Maa Responding to the mouse button for ship_rect) The blitme() method def Removing an item from a group game, so you dont waste memory and resources event in pg.event.get(): if event.type == pg.MOUSEBUTTONDOWN: ship.fire bullet() mouse pos = pg.mouse.get pos() Collisions between a single object and a group Clicking a button You nigh! want to know if the cursor is over an object such as a button The rect.collidepoint() method returns true when a point is inside a rect object if button_rect.collidepoint(mouse_pos): start game() keys for pg.sprite.spritecollideany(ship, ships left -= in < += len(collisions) * alien point value pg.event.get(): event.type == pg.KEYDOWN: if event.key == pg.K_ RIGHT: ship rect.x += elif event.key «= pg.K_LEFT: ship rect.x -= elif event.key == pg.K_SPACE: ship.fire_bullet() elif event.key == pg.K_q: sys.exit() Rendering text Making and filling a group An object that will be placed in a group must inherit from Sprite from def Responding to released keys pygame.sprite import Sprite, Group Bullet(Sprite): def draw def update(self): Displaying a message The following code defines a message, then a color for the text and the background color for the message A font is defined using the default system fort, with a font size of 48 The font.render() function is used fo create an image of the message, and we get the rect object associated with the image We then center the image on the screen and display it bullet(self): When the user releases a key, a KEYUP event is triggered event.type «= pg KEYUP: if event.key == pg.K_RIGHT: ship.moving right = False Pygame aliens): Collisions between two groups score event if if if collisions = pg.sprite.groupcollide( bullets, aliens, True, True) Pygame groups Ae - ei The spritecoliideany() function takes an object and a group, and returns True il the object overaps with any member of the group The sprite.groupcoliide() function takes two groups, and two booleans The function returns a dictionary containing information about the members that have collided The booleans tell Pygame whether to delete the members of either group tha! have collided pe-mouse,set_visible(False) Responding to key presses Detecting collisions The mouse position is returned as a tuple Hiding the mouse Pygame’s main event loop registers a KEYDOWN event any time a key is pressed When this happens, you can check for specific bullets.remove(bullet) Finding the mouse position leloe ME it's important to delete elements that will never appear again in the documentation bullets = new_bullet Group({) « Bullet() bullets.add(new The sprites() method returns all the members color “Play be color of a group bullet in bullets.sprites(): bullet.draw bullet() Calling update() on a group Calling update() on a group automatically calls update() on each member of the group bullets.update() « msg again?” = = (100, (236, 100, 230, 100) 230) bullet) Looping through the items in a group for msg f = pg.font.SysFont(None, 48) msg image = f.render(msg, True, msg color, bg color) msg image rect = msg image.get rect() msp image rect.center screen.blit(msg image, = screen_rect,.center msg image rect) More cheat sheets available at ehmatthes.github.|o/pcc/ Beginners Python Cheat Sheet — matplotlib What is matplotlib? Data visualization involves exploring data through visual representations The matplotlib package helps you make visually appealing representations of the data you're working with matplotlib is extremely flexible; these examples will help you get started with a few simple visualizations, ^ Customizing plots (cont.) Making a scatter plot Emphasizing points The scatier() function takes a list of x values and a list of y values, and a variety of optional arguments The s=18 argument controls the size of each point import matplotlib.pyplot Tỉ, plt.scatter(x_values, plt.show() tlh nn be install python3-matplotlib matplotlib.pyplot Start a terminal session and enter isport matplotlib fo see #f it's already installed on your system If not, try this command: pip install as plt user matplotlib matplotlib on Windows You first need to install Visual Studio, which you can from httpsv/dev.windows.cam/ The Community edition is free Then go fo https>/pypi.python.org/pypt'maiploltlib’ or httÐ:/Awww Wfđ uic edu/~qohike/pythonilbs/#@maiplotlib and download an appropriate installer file Numbers”, fontsize=24) 6, 116e000)) 5=16) plt.title("Square Numbers", squares[-1], s=100) x_ values matplotlib.pyplot « [@, 1, 2, 3, as 4, plt 5] squares = [@, 1, 4, 9, 16, 25] plit.plot(x_values, squares) pit.show() c=‘red', fontsize=24) snip each axis, and hide it plt.axes().get_xaxis().set_visible(False) plt.axes().get_yaxis().set_visible(False) Setting a custom figure size You can make your plot as big or small as you want Before plotting your data, add the following code The dpi argument is optional; if you don't know your system's resolution you cart omit the argument and adjust the figsize argument accordingly figsize=(10, 6)) A colormap varies the point colors from one shade to another, based on a certain value for each point The vaive used to determine the cotor of each point is passed to the c argument, and the cmap argument specifies which colormap to use The edgecolor="none" argument removes the black outline from each point values, squares, c=squares, edgecolor«‘none’, The matp(otitb viewer has an interactive save button, but you can also save your visualizations programmatically To so, replace plt.show() with plt.savefig() The bbox_inches='tight' argument tims extra whitespace from the plot plt.savefig( ' squares.png'ˆ; Online Bet: "2n bbox_inches='"tight') resources /'ociIin AT Making a line graph import c="green', Saving a plot Using a colormap cmapeplt.cm.Blues, Line graphs and scatter plots plt x values = list(range(100@)) squares = [x**2 for x in x_values] plt.scatter(x_values, squares, c#squares, cmap=plt.cm.Blues, edgecolor='none’, plt.figure(dpi=128, pit.show() s=19) as You can customize or remove axes entirely Here's how to access in x_values] Squares, $#10) labelsize=14) plt.scatter(x matplotlib.pyplot re- Removing axes l1ist(range(19096)) 1108, import plt.scatter(x_values[-1], edgecolor="none', S/0/n plit.axis([@, You can piot as much data as you want on one plot Here we plot the first and last points larger fo emphasize them plt.scatter(x values[@], squares[@], edgecolor='none', s=198) plt.xlabel("“Value", fontsize»18) plt.ylabel("Square of Value”, fontsize=18) plt.tick_params(axis="both', which="major', matplotlib on OS X $ s=10) Adding titles and labels, and scaling axes x values matplotlib on Linux apt-get squares, ; IV, plt.title("Square sudo pit Customizing plots squares = [x**2 for x plt.scatter(x_values, $ as x values = 1i1st(Frange(1988)) squares = [x**2 for x in x_values] import Installing matplotlib fii} Line graphs and scatter plots (cont.) Python Crash Course Covers Python and Python nostarchpress.com/pythoncrashcourse Working with dates and times Multipie plots ẻ (cont.) Muitiple plots in one figure Datetime formatting arguments The strftime() function generates a formatted string from a datetime object, and the strptime({) function Plotting two sets of data import matplotlib.pyplot as plt x_values = list(range(11)) squares = [x**2 for x in x_values] cubes « [x**3 for x in x_values] plt.scatter(x_values, squares, c='blue’, edgecolor='none', s=20) plt.scatter(x_values, cubes, c='red’, edgecolor='none', s=20) pit.axis([9, plt show( ) 11, 9, The fill_between() method fills the space between two data sets It takes a series of x-values and two series of y-values It also takes a facecolor to use for the fill, and an optional alpha argument that controls the color’s transparency plt.fill_between(x_values, cubes, squares, facecolor='blue', alpha=@.25) as dt 'Xm/Xd/XY') You can also generate a datetime object for any date and time you want The positional order of arguments is year, month, and day The hour, minute, second, and microsecond arguments are optional datetime new_years » dt(2017, 1, 1) fall_equinox = dt(year=2016, import datetime month=9, columns generated in the figure import matplotlib.pyplot as plt x_vals = list(range(i1)) squares = [x**2 for x in x_vals] cubes « [x**3 for x in x_vals] fig, axarr = plt.subplots(2, 1, axarr[1].scatter(x vals, cubes, axarr{[1].set_title( 'Cubes '} as dt To share a y-axis, we use the sharey*xTrue argumeni import matplotlib.pyplot x_vals = 1ist(range(11)) as plt squares = [x**2 for x in x_vals] cubes « [x**3 x in x_vals] axarr(@]).scatter(x_vals, squares) axarr[@].set_title('Squares '} 23), dt(2016, 6, 24), fig = plt.figure(dpi=128, figsize=(10,6)) plt.plot(dates, highs, c='red') plt.title("Daily High Temps", fontsize*24) plt.ylabel("Temp (F)", fontsize=16) x_axis = plt.axes().get_xaxis() x_axis.set_major_formatter( mdates.DateFormatter('%B pÌt show( ) axarr for ] 6, c='red') Sharing a y-axis fig, dt(2016, sharex=True) axarr(@]).scatter(x_vals, squares) axarr[@].set_title('Squares') dt(2016, 6, 21), dt(2@16, 6, 22), fig.autofmt_xdate() day=22) The following code plots a set of squares and a set of cubes on two separate graphs that share a common x-axis The pit subplots() function returns a figure object and a tuple of axes Each set of axes corresponds to a separate pilot in the figure The first two arguments control the number of rows and pÌt show( } = [ ) as dt %Y') The following code creates a list of dates and a corresponding list of high temperatures It then plots the high temperatures, with the date labels displayed in a specitic format highs = [57, 68, 64, 59] Generating a specific date import '%B %d, Plotting high temperatures dates today = dt.now() date_string = dt.strftime(today, print(date_string) from datetime ‘Xm/%d/%Y') import matplotlib.pyplot as plt from matplotlib import dates as mdates Generating the current date datetime ny_string = dt.strftime(new_years, print(ny_string) from datetime time: The datetime.now() function returns a datetime object representing the current date and time import Converting a string to a datetime object Converting a datetime object to a string Filling the space between data sets from datetime such as Monday « dt.strptime('1/1/2017', frre: Sharing an x-axis Month name, such as January Month, as a number (@1 to 12) Day of the month, as a number (@1 to 31) Four-digit year, such as 2016 Two-digit year, such as 16 Hour, in 24-hour format (@@ to 23) Hour, in 12-hour format (@1 to 12) AM or PM Minutes (@@ to 59) Seconds (@@ to 61) new_years 1190]) Working with dates and Weekday name, ReSRESLEGES Here we use plt.scatter() twice fo plot square numbers and cubes on the same figure Fe a = plt.subplots(1, 2, axarr[1].scatter(x_vals, cubes, axarr[1].set_title( 'Cubes ' ) sharey=True) c='red') pÌìt show( } %d %Y' }) More cheat sheets available at ehmatthes.github.lo/pcc/

Ngày đăng: 05/02/2024, 16:25

Từ khóa liên quan

Tài liệu cùng người dùng

Tài liệu liên quan