Reference material :
The author Python Learning is mainly based on 《Python Programming : From introduction to practice 》 This book is mainly , The idea of notes refers to the context in the book . Secondly, the author saw Professor Song Tian of Beili in Mu class a year ago Python Course . Professor Song Tian's class is very good , The biggest feature is that each section has complete sample code . But may not be very friendly to novice Xiaobai , Some unusual functions are easy to confuse .《Python Programming : From introduction to practice 》 It is more suitable for zero basic learning , There will be some interworking programming ideas and Python The format of .
Combined with common functions 、 Method :
Because the author has Java The basis of programming , Therefore, only Python Follow Java Different places and some easy to forget points and difficulties , Focus on Python The grammatical basis of . For novice friends, it's better to read first . combination 《Python Common functions 、 Method example summary (API)》 It may be better to see .
.py Point out that this is a Python Program , Editor Will use Python Interpreter Run it ;traceback.traceback It's a record , Indicates when the interpreter attempts to run code , Where are you in trouble ;\n Line break ( The cursor goes down to the beginning );\r enter ( The cursor returns to the beginning of the line );\t tabs ,\n\t Represents a line break and adds a tab at the beginning of the next line ;\b Back off ;print Statement contains parentheses , Some do not contain ;3 ** 2 == 9;\ Delete the decimal part directly .Python3 Keep decimals in . But in Python2 in :3.0 / 2 == 1.5;import this Can get ;bicycles = [ 'trek', 'cannondale', 'redline']. Be careful square brackets And comma ; Print list example :print(bicycles); Access list elements :bicycles[0] --- > trek; Access the penultimate... In the list x Elements :bicycles[-x] --- > When x=1 Time output :redline; Use for Loop through the list :for object in list: print(object)list = [num**2 for num in range(1s, 11)] ---> Output 1 To 10 The square of ;for object in list[firstNum: lastNum]:;list[:] To copy the list ;() or tuple() Or do not use parentheses ; and list Use [] or list();bicycles = { 'trek', 'cannondale', 'redline'}. Be careful Curly braces And comma ;```
s = set(list) # Take advantage of the feature that the set has no duplicate elements to duplicate
l = list(s) # Convert a collection back to a list
```
and and or Express and with or , instead of && and ||;if(object in list), It can also be used. if(object not in list);if list:alien0 = {'color': 'green', 'points': 5}for key, value in map.items():for object in map.keys(): or for object in map:, Because traversing the dictionary traverses all keys by default ;for object in sorted(map.keys()):for object in map.values():for object in set(map.values()):input() Method , And in the Python 2.7 Use in raw_input() Method ;while conditional_test:break Keyword exit loop , The cycle here includes while and for loop ;continue Keywords continue to cycle ;while object in list:```
def greet_user(username, age=1): #username No default value is set. It must be placed at the beginning of the formal parameter list
""" Show simple greetings """
print("hello, " + username.title() + ", age is " + str(age))greet_user('jesse', 18) # Location parameter greet_user(age=18, username='jesse') # Keyword arguments
greet_user('jesse') # Use the default value age=1```
* Second behavior ** Document string comments **, Describe what functions do ; * The following is the function call ; Example of function definition with normal return value :
```
def greet_user(username, age=1): #username No default value is set. It must be placed at the beginning of the formal parameter list
""" Show simple greetings """
print("hello, " + username.title() + ", age is " + str(age))return username.title()
```
```
def build_person(first_name, last_name): #username No default value is set. It must be placed at the beginning of the formal parameter list
""" Return dictionary """
person = {'first': first_name, 'last': last_name}return person
```
```
def greet_users(names):
""" The passed in parameter is list """
for name in names:
msg = "Hello, " + name.title() + "!"
print(mas)
usermanes = ['margot', 'hannah', 'ty']
greet_users(usernames)
```
def greet_users(names[:]):```
def make_pizza(*toppings):
""" Print all the ingredients that the customer ordered """
print(toppings)
make_pizza('pepperoni')make_pizza('mushrooms', 'green peppers', 'etra cheese')```
* Python Create a file called toppings Empty tuples of ; Use a combination of positional arguments and any number of arguments :def make_pizza(size, *toppings):Formal parameters that accept any number of arguments must be*toppingsIn the last ; Use any number of keyword arguments :\user_info** It can be understood as a dictionary ;
```
def build_profile(name, **user_info):
""" Create a dictionary , It contains everything we know about users """
profile = {}profile['name'] = name
for key, value in user_info.items():
profile[key] = value
return profile
user_profile = build_profile('albert', location='princeton', field='physics')print(user_profile)
```
as Give the function an alias :from model import function as fn; Use later fn() You can call function function ;as Assign an alias to a module :import model as md; Use later md.function() You can call the function ;from model import *; Use it directly later model The function in function() You can call the function ;global Keyword declares that the variable is a global variable ;< Function name > = lambda < Parameters > : < expression >;* Example : ```
>>> f = lambda x, y : x + y
>>> f(10, 15)
25
```
> > > f = lambda : "lambda expression " > > > print(f()) > > > lambda expression ```
dog.py```
""" Represents the class of dog and electronic dog """
class Dog():
""" Simulated dog """
def __init__(self, name):
""" Initialize instance """
self.name = name
self.age = 1 # Specify a default value for the property
def get_age(self):
""" Back to age """
return self.age
def set_age(self, age):
""" Set the age """
self.age = age
def sit(self):
""" Simulate a puppy crouching when ordered """
print(self.name.title() + " is now sitting.")
class TinyDog(Dog):
""" Dogs are a subclass of dogs """
def __init__(self, name)
""" Initializes the properties of the parent class """
super().__init__(name)
```
* `__init__()` Method : Shape parameter self essential , And must be preceded by other parameters ; * establish Dog When an instance , Arguments are automatically passed in self. Each method call associated with a class automatically passes arguments self, It is an application that points to the instance itself , Gives instances access to properties and methods in the class ; * `self.` Prefixed variables are available to all methods in the class , Variables that can be accessed through instances like this are called properties ; About parent-child classes :
* Subclasses and superclasses must be included in the current file , The parent class must precede the child class ;
* The parent class name must be specified in parentheses of the subclass definition ;
* `super()` It's a special function , Associate a parent class with a subclass ;
* stay Python 2.7 in ,`super()` Method needs to pass two arguments :** Subclass name ** and **self**, And specify the field in parentheses of the parent class definition **object**; stay Python 2.7 When creating a class in , You need to include the word... In the bracket class object:class ClassName(object):```
class Dog():
--snip--
my_dog = Dog('willie')dog_name = my_dog.name # get attribute
dog_name = my_dog.get_age() # Get properties through methods
my_dog.name = 'jucy' # Modify properties directly
my_dog.set_age = 18 # Modifying properties through methods
my_dog.sit() # Calling method
```
from dog import Dog, TinyDog;import dog;OrderedDict. The instance behavior of this class is almost the same as that of a dictionary , The difference is that it records Key value pair The order of ;```
with open('xxx.txt') as file_object:contents = file_object.read()
print(contents)
```
* Open file `open()` And close the file `close()` Can be used at the same time , But when there is bug when `close()` Failure to execute will cause the file to fail to close . Don't write `close()` Will be made by Python Determine whether to close the file ; * `with` Keyword close the file after it is no longer needed to access it ; * Print directly contents There will be one more blank line , You can print `print(contens.rstrip())`; About the absolute path of the file :Linux and OS X:file_path = '/home/.../xxx.txt';Windows:file_path = C:\...\xxx.txt; It is recommended to store the data file in the directory where the program file is located , Or the next level folder of the directory where the program files are located ; Read line by line :
```
with open(filename) as file_object:
for line in file_object:
print(line)
```
* Empathy , Print directly contents There will be one more blank line , You can print `print(line.rstrip())`; UsewithWhen a keyword ,open()The returned object is only in with Code blocks are available in ; When dealing with files, pay attention tostrip()orrstrip()Remove the spaces on both sides of the string ;Python Interpret all text as strings ;open('xxx.txt', 'w'): Open the file as a write ; Other parameters arerRead 、aadditional 、r+Reading and writing ;aadditional : Append content to the end of the file , Instead of covering the original contents of the file ; WithwBe careful when opening files in write mode , If the specified file name already exists ,Python The file will be emptied before returning the object ;Python Only strings can be written to text files ;
```
try:
print(5/0)
except ZeroDivisionError:
print(' Capture to ZeroDivisionError abnormal ')else:
print(' Uncaught exception ')finally:
print(' Whether there is an exception or not, it will execute ')```
* Can be found in `except` Add keywords to the indented block of **pass** Skip error capture ; * among ,`else` and `finally` Some code blocks can save ;
unittest To test ;```
import unittest
from model_name import function_name
class TestCase(unittest.TestCase):
""" Test functions function_name"""
def setUp(self):
""" Build preconditions """
def test_function(self):
run_result = function_name(parameter)
self.assertEqual(run_result, correct_result)
unittest.main()
```
* Import module first `unittest` And the method being tested `function_name`; * Then create `TestCase` class , It contains a variety of specific unit test methods . Inheritance of such kind `unittest.TestCase` class ; * `setUp()` Method is used to create a precondition ; * Write test methods `test_function`, Method names must be `test_` Lead ; * Use assertion `assertEqual()` Judge the difference between the execution result of the function and the expected result ; * `unittest.main()` Give Way Python Run the tests in this file ;unittest It is commonly used in 6 An assertion method, see ; Every time you complete a test ,Python Will print a character : The test passes by printing a period.; The test raises an error and prints aE; The test causes the assertion to fail, printing aF;