Python grammar basics dry inventory [with source code]

Programmer Didi 2022-06-23 17:47:51 阅读数:1,007

pythongrammarbasicsdryinventory

Preface

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 .


1. Variables and simple data structures

  • .py Point out that this is a Python Program , Editor Will use Python Interpreter Run it ;
  • Python Interpreter Read the whole program , Determine the meaning of each word ;
  • When the program cannot run successfully , The interpreter will provide a traceback.traceback It's a record , Indicates when the interpreter attempts to run code , Where are you in trouble ;
  • stay Python in , It can be used Single quotation marks or Double quotes Enclose the string ;
  • Python Escape character in :
    • \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 ;
  • Python2 in , There are some print Statement contains parentheses , Some do not contain ;
  • Python Use Two multiplication signs indicate power , Such as :3 ** 2 == 9;
  • Python2 in division \ Delete the decimal part directly .Python3 Keep decimals in . But in Python2 in :3.0 / 2 == 1.5;
  • Python zen :Python Some programming concepts . Input... At the terminal import this Can get ;
  • Python keyword :undefined
  • Python Built in functions :undefined

2. List related

  • An example of a list :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 of analytical list = [num**2 for num in range(1s, 11)] ---> Output 1 To 10 The square of ;
  • Traverse the partial list for object in list[firstNum: lastNum]:;
  • have access to list[:] To copy the list ;
  • Yuan Zu relevant :
    • Python The value that cannot be modified is called immutable , The immutable list is called Yuan Zu ;
    • Programmatically different from a list in that it uses () or tuple() Or do not use parentheses ; and list Use [] or list();
    • Tuples can't be modified after they are created , So there is no special operation ;
  • If amendments are proposed Python Suggestions for language modification , You need to write Python Improvement proposal (PEP).PEP 8 It's the oldest PEP One of , It stipulates the following Python Code format specification :
    • Indent each level 4 A space . You need to edit the text editor ( or ide) Set up tab The key is 4 A space ;
    • Python The interpreter interprets the code according to the horizontal indentation , Don't care about vertical spacing ;
    • It is recommended that each line be no more than characters ;
    • It is recommended to add a space on each side of the comparison operator ;

3. aggregate

  • A collection example :bicycles = { 'trek', 'cannondale', 'redline'}. Be careful Curly braces And comma ;
  • The characteristic of a set is that it cannot be repeated ;
  • Use set data to remove duplication :
```
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 
```

4. If sentence

  • Python Consider case when checking for the same ;
  • Most of the time, it is more efficient to check the inequality of two fingers ;
  • stay Python Use in and and or Express and with or , instead of && and ||;
  • A statement that checks whether the list contains a specific value :if(object in list), It can also be used. if(object not in list);
  • Python Of if The basic structure of the statement is as follows ( Pay attention to the colons ):` if conditional_test1: do something1 elif conditional_test2: do something2 else: do other
  • Determine whether the list is empty :if list:

5. Dictionaries

  • in fact , Any Python Object is used as a value in the dictionary ;
  • One Dictionaries An example of :alien0 = {'color': 'green', 'points': 5}
  • Ergodic dictionary for key, value in map.items():
  • Traverse the key of the dictionary for object in map.keys(): or for object in map:, Because traversing the dictionary traverses all keys by default ;
  • Traverse all the keys in the dictionary in order :for object in sorted(map.keys()):
  • Traversal dictionary value for object in map.values():
  • Traversal dictionary value , Eliminate duplicates :for object in set(map.values()):
  • Lists and dictionaries should not have too many levels of nesting , If too many , There may be a simpler solution to the problem ;

6. User input and while loop

  • stay Python 3 Use in input() Method , And in the Python 2.7 Use in raw_input() Method ;
  • Loop statement :while conditional_test:
  • have access to break Keyword exit loop , The cycle here includes while and for loop ;
  • have access to continue Keywords continue to cycle ;
  • Use circular processing list :while object in list:

7. function

  • Example of function definition without 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))
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()
```
  • Example of function definition with dictionary return value :
```
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
```
  • Pass list parameters , The list will be modified :
```
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)
```
  • Pass a copy of the list parameter , 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 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 *toppings In 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)
```
  • stay Python in ,import It's a module , Use modular . Method ( Parameters ) You can call the functions in the module ;
  • Import specific functions , And use the function example :` from module_name import function_0, function_1 function_0() function_1( Parameters )
  • Use as Give the function an alias :from model import function as fn; Use later fn() You can call function function ;
  • Use as Assign an alias to a module :import model as md; Use later md.function() You can call the function ;
  • All functions import modules :from model import *; Use it directly later model The function in function() You can call the function ;
  • You can use... In function classes global Keyword declares that the variable is a global variable ;
  • lambda expression < Function name > = lambda < Parameters > : < expression >;
* 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 : Import only the functions you need to use / Import the entire module and use the period notation ;
    • Functions and modules should be named with lowercase letters and underscores , Not hump nomenclature ;
    • The function annotation follows the function definition , Use document string format ;
    • When a parameter is assigned a default value , Equal sign = There should be no spaces on either side ;

8. Classes and objects

  • Functions in a class are called methods ;
  • A class example : The module is called 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 objectclass ClassName(object):
  • Class instance ( object ) An example of :
```
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.py Import multiple classes into the module :from dog import Dog, TinyDog;
  • Import the whole dog.py modular , Then use a period to indicate the class you need to access :import dog;
  • collections The module contains a class 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 ;
  • Class coding style :
    • Class uses hump nomenclature , Every word in the class is capitalized ;
    • The instance name and module name are in lowercase , And underline the words ;
    • An empty line separation method ; Two spaces separate classes ;
    • You need to import both standard libraries and modules

9. file

  • 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 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())`; Use with When a keyword ,open() The returned object is only in with Code blocks are available in ; When dealing with files, pay attention to 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 as a write ; Other parameters are r Read 、a additional 、r+ Reading and writing ;a additional : Append content to the end of the file , Instead of covering the original contents of the file ; With w Be 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 ;

10. abnormal

  • Use try-except Handling exceptions :
```
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 ;

11. test

  • Use Python Modules in the standard library unittest To test ;
  • A simple test example :
```
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 a E; The test causes the assertion to fail, printing a F;
版权声明:本文为[Programmer Didi]所创,转载请带上原文链接,感谢。 https://pythonmana.com/2022/01/202201051847395392.html