preface
reference material:
The author's study of Python is mainly based on the book Python Programming: from introduction to actual combat. The ideas of notes refer to the context in the book. Secondly, there is the python course taught by Professor Song Tian of Beili, which the author saw in Mu class a year ago. Professor Song Tian's class is very good. The biggest feature is that each section has complete example code. But it may not be very friendly to novice Xiaobai, and some infrequently used functions are easy to confuse. Python Programming: from introduction to practice is more suitable for zero basic learning. It will mention some interworking programming ideas and python format specifications.
Combined with common functions and methods:
Because the author has the programming foundation of Java, here we only record the differences between Python and Java, as well as some easy to forget points and difficulties, focusing on the syntax foundation of Python. For novice friends, it's better to read first. Combined with the summary of common Python functions and methods (API), the effect may be better.
1. Variables and simple data structures
- . py indicates that this is a python program, and the editor will run it using the Python interpreter;
- The Python interpreter reads the whole program and determines the meaning of each word;
- When the program fails to run successfully, the interpreter provides a traceback. Traceback is a record of where the interpreter gets into trouble when trying to run code;
- In Python, you can enclose a string in single or double quotation marks;
- Escape characters in Python:
- \n line feed (cursor to the beginning of the line);
- \r press enter (the cursor returns to the beginning of the line);
- \T tab character, \ n\t indicates a line break and adds a tab character at the beginning of the next line;
- \b fallback;
- In Python 2, some print statements contain parentheses and some do not;
- Python uses two multiplication signs to represent the power, such as: 3 * * 2 = = 9;
- Division in Python 2 \ delete the decimal part directly. Keep decimals in Python 3. But in Python 2: 3.0 / 2 = = 1.5;
- Python Zen: some programming concepts of Python. Enter import this in the terminal to obtain;
- Python keyword: undefined
- Python built-in function: undefined

2. List related
- An example of a list: cycles = ['Trek', 'cannon Dale', 'redline']. Pay attention to square brackets and commas; Example of print list: print(bicycles); Access list elements: cycles [0] - > trek; Access the penultimate x element of the list: cycles [- x] --- > when x=1, output: redline; Use the for loop to traverse the list: for object in list: print(object)
- List analysis: List = [num * * 2 for num in range (1s, 11)] --- > output the square of 1 to 10;
- Traversal part list: for object in list[firstNum: lastNum]:;
- You can copy the list by using the method of list [:];
- Related to Yuanzu:
- In Python, values that cannot be modified are called immutable, and immutable lists are called Yuanzu;
- Programmatically, it is different from the list in that it uses () or tuple() or does not use parentheses; The list uses [] or list();
- Tuples cannot be modified after creation, so there is no special operation;
- If you propose to modify the python language, you need to write a python improvement proposal (PEP). PEP 8 is one of the oldest peps, which specifies the following Python code format specifications:
- Indent 4 spaces per level. You need to set the tab key to 4 spaces for the text editor (or ide);
- The Python interpreter interprets the code according to the horizontal indentation, and does not care about the vertical spacing;
- It is recommended that each line should not exceed characters;
- It is recommended to add a space on both sides of the comparison operator;
3. Assembly
- An example of a collection: cycles = {Trek ',' cannon Dale ',' redline '}. Pay attention to braces and commas;
- The characteristic of a set is that it cannot be repeated;
- De duplication using set data:
```
s = set(list) #Using the characteristics of set without repeated elements to remove duplication
l = list(s) #Convert collection back to list
```
4. If statement
- Python considers case when checking whether it is the same;
- Most of the time, it is more efficient to check the inequality of two fingers;
- In Python, and and or are used to represent and and or, rather than & & and |;
- A statement to check whether the list contains a specific value: if(object in list), or if(object not in list);
- The basic structure of Python's if statement is as follows (note the colon):` if conditional_test1: do something1 elif conditional_test2: do something2 else: do other
- Judge whether the list is empty: if list:
5. Dictionary
- In fact, any Python object can be used as a value in the dictionary;
- An example of a dictionary: alien0 = {color ':' green ',' points': 5}
- Traversal Dictionary: for key, value in map items():
- Key to traverse Dictionary: for object in map Keys(): or for object in map:, because traversing the dictionary traverses all keys by default;
- Traverse all keys in the dictionary in order: for object in sorted(map.keys()):
- Traversal dictionary value: for object in map values():
- Traverse dictionary values and eliminate duplicates: for object in set(map.values()):
- The nesting levels of lists and dictionaries should not be too many. If there are too many, there may be simpler solutions to the problem;
6. User input and while loop
- Use the input () method in Python 3 and raw in Python 2.7_ input() method;
- Loop statement: while conditional_test:
- You can use the break keyword to exit the loop. The loops here include while and for loops;
- You can use the continue keyword to continue the loop;
- Use the loop to process the list: while object in list:
7. Function
- Example of function definition without return value:
```
def greet_user(username, age=1): #username has no default value and 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) #Position argument
greet_user(age=18, username='jesse') #Keyword argument
greet_user('jesse') #Use the default value age=1
```
* Second behavior**Document string comment**,Describe what functions do; * Followed by function call; Example of function definition with normal return value:
```
def greet_user(username, age=1): #username has no default value and 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()
```
- Example of function definition with dictionary return value:
```
def build_person(first_name, last_name): #username has no default value and must be placed at the beginning of the formal parameter list
"""Return to dictionary"""
person = {'first': first_name, 'last': last_name}
return person
```
- Pass the list parameter, and the list will be modified:
```
def greet_users(names):
"""The passed in parameter is a list"""
for name in names:
msg = "Hello, " + name.title() + "!"
print(mas)
usermanes = ['margot', 'hannah', 'ty']
greet_users(usernames)
```
- Pass a copy of the list parameter, and the list will not be modified: def greet_users(names[:]):
- Pass any number of arguments: * toppings can be understood as a list;
```
def make_pizza(*toppings):
"""Print all ingredients ordered by the customer"""
print(toppings)
make_pizza('pepperoni')
make_pizza('mushrooms', 'green peppers', 'etra cheese')
```
* Python Create a file named toppings Empty tuple of; Use a combination of positional arguments and any number of arguments: def make_pizza(size, *toppings):You must accept any number of arguments as formal parameters*toppings Put it last; Use any number of keyword arguments:\user_info**Can be understood as a dictionary;
```
def build_profile(name, **user_info):
"""Create a dictionary that 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)
```
- In Python, the import is a module, and the module is used Method (parameter) can call the function in the module;
- Import a specific function and use it as an example:` from module_name import function_0, function_1 function_0() function_ 1 (parameter)
- Use as to assign an alias to the function: from model import function as fn; Subsequently, use fn() to call the function function;
- Use as to assign an alias to the module: import model as md; Subsequently, you can call the function by using md.function();
- Import all functions of the module: from model import *; Subsequently, the function can be called directly by using the function() in the model;
- You can use the global keyword in the function class to declare that the variable is a global variable;
- Lambda expression: & lt; Function name & gt= lambda < Parameter & gt;:& lt; Expression & gt;;
* Example: ```
>>> f = lambda x, y : x + y
>>> f(10, 15)
25
```
> > > f = lambda : "lambda expression" > > > print(f()) > > > lambda expression ```
- Function and module writing details:
- Recommended Practice for importing external functions: only import the functions to be used / import the whole module and use the period representation;
- The naming of functions and modules shall use lowercase letters and underscores instead of hump naming method;
- The function annotation follows the function definition and uses the document string format;
- When specifying default values for formal parameters, equal sign = no spaces on both sides;
8. Classes and objects
- Functions in a class are called methods;
- An example of a class: the module name is dog py
```
"""Class representing dog and electronic dog"""
class Dog():
"""Simulated dog"""
def __init__(self, name):
"""Initialize instance"""
self.name = name
self.age = 1 #Assign default values to properties
def get_age(self):
"""Return age"""
return self.age
def set_age(self, age):
"""Set age"""
self.age = age
def sit(self):
"""Simulate a dog squatting 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__()`Methods: formal parameters self Essential and must be preceded by other parameters; * establish Dog Instance, the 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, so that the instance can access the properties and methods in the class; * `self.`Variables prefixed with can be used by all methods in the class. Variables that can be accessed through instances like this are called attributes; For parent and child classes:
* The child class and parent class must be included in the current file, and the parent class must be in front of the child class; * The parent class name must be specified in parentheses of the subclass definition; * `super()`Is a special function that associates a parent class with a child class; * stay Python 2.7 In,`super()`Method needs to pass two arguments:**Subclass name**and**self**,And the fields are specified in parentheses of the parent class definition**object**;stay Python 2.7 When creating a class in, you need to include words in parenthesesobject: class ClassName(object):
- Examples of class instances (objects):
```
class Dog():
--snip--
my_dog = Dog('willie')
dog_name = my_dog.name #get attribute
dog_name = my_dog.get_age() #Get properties by method
my_dog.name = 'jucy' #Modify properties directly
my_dog.set_age = 18 #Modify properties through methods
my_dog.sit() #Call method
```
- From dog Py module: from dog, import dog, tinydog;
- Import the entire dog Py module, and then use a period to indicate the class required for access: import dog;
- The collections module contains a class OrderedDict. The instance behavior of this class is almost the same as that of a dictionary, except that it records the order of key value pairs;
- Coding style of class:
- Hump naming method is adopted for the class, and the first letter of each word in the class is capitalized;
- The instance name and module name are in lowercase and underlined between words;
- An empty line separation method; Two spaces separate classes;
- You need to import both standard libraries and modules
9. Documentation
- Open and read a file and display its contents on the screen:
```
with open('xxx.txt') as file_object:
contents = file_object.read()
print(contents)
```
* Open file`open()`And close files`close()`Can be used at the same time, but when there is bug Time`close()`Failure to execute will prevent the file from closing. Don't write`close()`Will be Python Determine whether to close the file; * `with`Keyword close the file after it is no longer needed to access it; * Direct printing contents There will be one more blank line, which can be printed like this`print(contens.rstrip())`;For absolute file path: 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 in the folder below the directory where the program file is located; Read line by line:
```
with open(filename) as file_object:
for line in file_object:
print(line)
```
* Similarly, print directly contents There will be one more blank line, which can be printed like this`print(line.rstrip())`;use with Keyword, open()The returned object is only in with Available within the code block; Pay attention to use when dealing with files strip()or rstrip()Remove the spaces on both sides of the string; Python Interpret all text as strings; open('xxx.txt', 'w'): Open the file by writing; Other parameters are r Read a Additional r+Reading and writing; a Attach: attach the content to the end of the file instead of overwriting the original content of the file; with w Be careful when opening a file 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;
10. Abnormal
- Use try except to handle exceptions:
```
try:
print(5/0)
except ZeroDivisionError:
print('Capture ZeroDivisionError abnormal')
else:
print('No exception caught')
finally:
print('It will be executed whether there is an exception or not')
```
* Available in`except`Add keywords to indented blocks**pass**Skip error capture; * Among them,`else`and`finally`Some code blocks can be saved;
11. Test
- Use the module unittest in Python standard library for testing;
- A simple test example:
```
import unittest
from model_name import function_name
class TestCase(unittest.TestCase):
"""Test function 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 the module first`unittest`And method under test`function_name`; * Then create`TestCase`Class, which contains various specific unit test methods. This class inherits`unittest.TestCase`Class; * `setUp()`Method is used to create preconditions; * Writing test methods`test_function`,Method name must be`test_`Take the lead; * Use assertions`assertEqual()`Judge the difference between the function execution result and the expected result; * `unittest.main()`Give Way Python Run the tests in this file; unittest See for the 6 assertion methods commonly used in; Every time a test is completed, Python One character will be printed: the test passes and the period is printed .;Test raises an error printing a E;The test causes the assertion to fail. Print a F;