Python basic syntax
NOTE: the following is a brief summary NOTE based on Python 3. More details python3 official documents: https://docs.python.org/zh-cn/3/
0. python Zen
The Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those!
1. Data type
- number
- Integer (int): 199
- float: 3.141592654
- String (str): 'hello', 'world'
- boolean: True False
- Type conversion
- String - > integer: num = int('123 ')
- Floating point - > integer: num = int(3.14)
- List - > tuple: tuple(['cat', 'dog', 5])
- Tuple - > List: list ('cat ',' dog ', 5))
- Set - > List: list ({cat ',' dog ', 5})
2. Operator
- Arithmetic: + - * /% * * (power) / / (quotient)
- Comparison: = =! = > < > =<=
- Assignment / compound operation: = + = - = * = / =% = * * =//==
- Logic: and or not
- Bit operation: & ^ ~ < > >
- Member operator (judge whether an element is in the sequence): in not in
- Identity operator (judge whether two identifiers refer to an object): is not
- Set operator: | & ^. See 5.1.5 for details
3. Conditional branch
-
if
if cond1: pass elif cond2: pass else: pass
4. Circulation
-
while
while cond: print('aaa')
while cond1: # If the cond1 condition is not satisfied and you jump out of while, the code in else will be executed print('hello') if cond2: break # Jump out of while by break, and the code in else will not be executed else: print('world')
-
for
General formula: for variable in sequence. Sequences include strings, lists, tuples.
for c in 'codemao': print(c)
for i in range(9): # If the cond1 condition is not satisfied and you jump out of while, the code in else will be executed print(i) if i > 5: break # Jump out of while by break, and the code in else will not be executed else: print('end')
range(start, stop, step): generates a sequence of numbers.
Start: start, no default, start from 0
Stop: end without stop
Step: step size
range(6) # The sequence is: 0 1 2 3 4 5 range(1, 5) # Sequence: 1 2 3 4 range(1, 11, 3) # Sequence: 1 4 7 10
5. Data structure
5.1 List
A list consists of a series of elements arranged in a specific order. In fact, the array in C language is similar: the subscript index also starts from 0; Access elements with array[5]; A string is also a list. It's just a little different in some syntax: in C language, arrays are enclosed by parentheses, but lists in python are enclosed by parentheses. Bicycles = ['trek ',' cannon Dale ',' redline ',' specialized ']; In C language, the type of elements in an array can only be single, but in python, multiple types can be placed in a list. list = [1, 'hello', None, True].
append, pop, insert and remove in the list are all methods of the list. Similarly, tuples, sets, dictionaries... Also have their own methods. Methods and functions are actually the same thing, but in different forms. Methods are often followed by an object, such as a.pop(), which represents the operation of the object. The function call is only func(). When referring to the function in the module, the form is similar to the method, such as random randint(1, 10).
5.1.1 addition, deletion, query and modification of the list
a = [1, 2, 3, 4, 'codemao'] a.append(5) # Add at the end a[1] = 100 # Modify element with index 1 del a[1] # Delete element with index 1 num = a.pop(1) # Pop up the element with index 1 and assign it to num. If a.pop(), the element at the end of the pop-up list will pop up by default a.remove('codemao') # Delete element with value 'codemao' a.insert(1, 'hello') # Insert 'hello' where the index is 1, and move the other elements back one bit # List splicing and copying a += ['x', 'y']*2 # + for splicing and + for copying*
5.1.2 create numeric list and sort
numbers = list(range(1,6)) # Create a list named numbers for [1, 2, 3, 4, 5] squares = [value**2 for value in range(1,6)] # Generate a list named squares for [1, 4, 9, 16, 25] slen = len(squares) # Find the length of squares, that is, the number of elements a = [1, 10, 3, 6, 8] a.sort() # Permanently change the order of a b = sorted(a) # A sorted copy of a is generated without changing the order of A a.reverse() # Permanently change the order of a, in reverse order
5.1.3 Slice
Slicing technology is used when you need to access or use some elements in the list. When it comes to slicing, we have to mention the index method of lists in python, which is a little different from C language. In python, lists can be indexed in two ways: forward and reverse.
Take a list with a list length of 5 as an example:
The forward direction is 0 1 2 3 4 from left to right
The reverse direction from right to left is: - 5 - 4 - 3 - 2 - 1
When using slicing, it will be convenient to use index flexibly and make the code easy to read.
The basic form of slice: listname[4:9]. Similar to range, it is also "with head but without tail". At the same time, it can also use step size. The specific codes are as follows:
a = [1, 10, 3, 6, 8] print(a[1:4]) # Cut the elements with indexes from 1 to 3 and generate a new list print(a[:3]) # Cut the elements with indexes from 0 to 2 and generate a new list print(a[-3:]) # Cut the elements with indexes from - 3 to - 1 and generate a new list print(a[1:8:2]) # Cut the elements with indexes from 1 and 3 and generate a new list b = a[:] # Make a copy of a
It should be noted here that to copy a list, you should use slices. If you just use =, you are making 2 different variables point to the same list. For example:
a = [1, 10, 3, 6, 8] b = a # Assign a to b b.append(100) print(id(a), id(b)) print(a, b) ----------------------------- Operation results: 43022216 43022216 [1, 10, 3, 6, 8, 100] [1, 10, 3, 6, 8, 100]
5.1.4 Tuple
Tuples are also a list (in parentheses), so they are put in the list. In python, there are variable objects and immutable objects. Tuples are immutable objects. When a tuple is created, the value of its elements cannot be changed. But modify the value of the variable that stores tuples.
a = (1, 10, 3, 6, 8) # An error will be reported: TypeError: 'tuple' object does not support item assignment a[4] = 9 a = (100, 50) # legal
5.1.5 Set
A collection is also a list (in curly braces). A collection is an unordered and non repeating sequence of elements. For example:
a = {1, 2, 3, 4} # Create a collection
There are four kinds of set operations:
a = {4, 5, 6} b = {1, 4, 7} print(a-b) # Elements contained in set a but not in set b. Equivalent to A-A & b print(a|b) # All non repeating elements contained in set a or b print(a&b) # Sets a and b contain both elements print(a^b) # Elements not included in both a and b # ------------------------------- Operation results: {5, 6} {1, 4, 5, 6, 7} {4} {1, 5, 6, 7}
5.2 Dictionary (Dic)
A dictionary is a series of key value pairs, with each key associated with a value. It is similar to struct in C language.
The table items in the dictionary are not sorted. Therefore, when using the table items in the dictionary, you cannot index them with subscripts, but with keys.
Among them, the value of the dictionary can take any python object without restriction, which can be either a standard object or a user-defined object, but the key cannot
1. The same key is not allowed to appear twice. If the same key is assigned twice, the next assignment shall prevail
2. The key must be immutable. You can use number/str/tuple.
d = {'size':42, 'maker':'Nike', 'color':'orange'} # Create dictionary print(d['make']) # Index with key d['size'] = 44 # modify del d['color'] # Delete k-v pair
-
method
-
keys(),values(),items(). The values returned by these methods are not real lists, they cannot be modified, and there is no append method, but they can be used in a for loop to traverse the dictionary
spam = {'color': 'red', 'age': 42} for v in spam.values(): print(v)
-
The get(key, retval) method takes the value corresponding to the corresponding key. Key is the key to get its value, and retval is the backup value returned if the key does not exist.
picnicItems = {'apples': 5, 'cups': 2} print(str(picnicItems.get('cups', 0)) + ' cups.') print(str(picnicItems.get('eggs', 0)) + ' eggs.') #----------------------- Operation results: 2 cups. 0 eggs.
-
The setDefault (key, default_value) method is to set a default value for a key in the dictionary. def_value is the default value.
spam = {'name': 'Pooka', 'age': 5} spam.setdefault('color', 'black') # color is set to black spam.setdefault('color', 'white') # color is not set to white, or black
-
6. Function
6.1 definition and call
# definition def f1(arg1, arg2, arg3...): arg1 = arg2 + arg3 return arg1 # The return value can be Number or List # call f1(3, 4, 5)
6.2 parameter transfer
def describe(name, gender, age) # Position argument. When calling, the positions of the actual participating formal parameters should correspond one by one def describe(name, gender, age) describe(gender='male', age=23, name='James') # Keyword arguments. No one-to-one correspondence is required def describe(name, gender, age=23) # Default value. If there is no age argument when calling, it is 23 def describe(name, gender, age='') # Optional parameters. When calling, the age argument is optional def mul(*n): # Indefinite length parameter mul(3, 4, 5) # You can have n arguments when calling
Immutable object (int / string / tuple / set), passing only copies of N1 and N2. Equivalent to C language value transfer
def change(a): print(id(a)) # It points to the same object a=10 print(id(a)) # A new object a=1 print(id(a)) change(a) print(id(a)) print(a)
4379369136 4379369136 4379369424 4379369436 1 End of program operation
The variable object (list/dic) passes N1 and N2 itself. Equivalent to C language pointer passing
def changeme( mylist ): "Modify incoming list" mylist.append([1,2,3,4]) print ("Value in function: ", mylist) return # Call the changeme function mylist = [10,20,30] changeme( mylist ) print ("Value outside function: ", mylist)
Value in function: [10, 20, 30, [1, 2, 3, 4]] Value outside function: [10, 20, 30, [1, 2, 3, 4]] End of program operation
6.3 scope
You can think of scope as a container for variables. When the scope is destroyed, the values of all variables stored in the scope are discarded.
Global variables: variables assigned outside all functions have global scope and are global variables.
Local variables: variables that are local are called local variables.
-
Local variables cannot be used within the global scope
def f(): a = 100 f() print(a)
Running result: NameError: name a is not defined
-
Local scopes cannot use other local variables
def f1(): a = 100 f2() print(a) def f2(): b = 10 a = 120 f1()
Operation result: 100. Different local scopes are independent of each other, and the variables between them are also independent of each other.
-
Global variables can also be used in local scopes
def spam(): print(eggs) eggs = 42 spam()
Operation result: 42.
If there is no variable named eggs in the function body, and no code assigns a value to eggs, python defaults to its reference to the global variable when using eggs in spam().
Therefore, if the local variable and global variable have the same name, it will be confusing:
def spam(): eggs = 'spam local' print(eggs) # prints 'spam local' def bacon(): eggs = 'bacon local' print(eggs) # prints 'bacon local' spam() print(eggs) # prints 'bacon local' eggs = 'global' bacon() print(eggs) # prints 'global'
Operation results:
bacon local spam local bacon local global
So avoid this situation.
If you want to change the value of a global variable in a local scope, you should use global:
def spam(): global eggs eggs = 'spam' eggs = 'global' spam() print(eggs)
Running result: spam.
7. Abnormal
In general, whenever Python encounters a overwhelmed error, the program stops and displays a traceback with an exception report. If you use try except, even if an exception occurs, the program will continue to run and display the friendly error message you wrote.
General conditions:
def div(n): return 42 / n print(div(5)) print(div(0)) print(div(3))
8.4 Traceback(most recent call last): ..... ZeroDivisionError: division by zero
After treatment with try except:
def div(n): try: answer = 42 / n except ZeroDivisionError: # Execute this code if an exception occurs print('Error: Cannot div by zero') else: # If no exception occurs, else is executed return answer print(div(5)) print(div(0)) print(div(3))
8.4 Error: Cannot div by zero None 14.0
8. Documentation
8.1 reading documents
filename = 'pi_digits.txt' with open(filename) as file_object: # Open txt file lines = file_object.readlines() # Read line by line into the lines list for line in lines: print(line.rstrip())
8.2 writing documents
filename = 'programming.txt' with open(filename, 'w') as file_object: # Open file as write file_object.write("I love programming.") # Write content to file
Common modes: 'r' (read mode), 'w' (write mode), 'a' (additional mode)
These patterns are similar to the text operation of C language, which can be used for reference.
9. Class
- Create classes and instances
# Create a class. Generally speaking, in Python, capitalized names refer to classes class Car(): def __init__(self, make, model, year): """Initialize the properties that describe the car""" self.make = make self.model = model self.year = year self.odometer_reading = 0 # Attribute defaults def get_descriptive_name(self): return (str(self.year) + ' ' + self.make + ' ' + self.model) def read_odometer(self): """Print a message indicating the mileage of the car""" print("This car has " + str(self.odometer_reading) + " miles on it.") # Create instance my_new_car = Car('audi', 'a4', 2016) # Calling a method in a class print(my_new_car.get_descriptive_name()) my_new_car.read_odometer()
- inherit
# Create subclasses and inherit from Car class ElectricCar(Car): """The uniqueness of electric vehicles""" def __init__(self, make, model, year): """Initializes the properties of the parent class. A parent class is also called a superclass""" super().__init__(make, model, year) self.battery_size = 70 # Subclass specific attribute def describe_battery(self): """Print a message describing the battery capacity""" print("This car has a " + str(self.battery_size) + "-kWh battery.") # You can also override parent methods def fill_gas_tank(): """Electric cars have no fuel tanks""" print("This car doesn't need a gas tank!") # Create instance my_tesla = ElectricCar('tesla', 'model s', 2016) print(my_tesla.get_descriptive_name()) my_tesla.describe_battery()
- Class "nested"
# Abstract the battery in electrocar into a battery class class Battery(): """A simple attempt to simulate electric vehicle battery""" def __init__(self, battery_size=70): """Initialize battery properties""" self.battery_size = battery_size def describe_battery(self): """Print a message describing the battery capacity""" print("This car has a " + str(self.battery_size) + "-kWh battery.") # Create subclasses and inherit from Car class ElectricCar(Car): """The uniqueness of electric vehicles""" def __init__(self, make, model, year): """Initializes the properties of the parent class. A parent class is also called a superclass""" super().__init__(make, model, year) self.battery = Battery() # Create Battery instance # You can also override parent methods def fill_gas_tank(): """Electric cars have no fuel tanks""" print("This car doesn't need a gas tank!") # Create instance my_tesla = ElectricCar('tesla', 'model s', 2016) print(my_tesla.get_descriptive_name()) my_tesla.battery.describe_battery() def describe_battery(self):
- Import class
from car import Car # Import a class my_new_car = Car('audi', 'a4', 2016) from car import Car, ElectricCar # Import multiple classes my_tesla = ElectricCar('tesla', 'roadster', 2016) import car # Import the entire module my_beetle = car.Car('volkswagen', 'beetle', 2016)
- When there are dependencies between modules, the dependent modules must be imported. If the electrocar class depends on the Battery class, when writing the electrocar class, you must first import the module name of the Battery class at the beginning of the file.
10. Module
In addition to python's own standard library, we can also install other third-party modules to expand the functions of python.
Installation method:
-
Install pip tool
Win and OS X may be installed by default when downloading Python 3. Linux: get install python3-pip . After installation, PIP on win is located at c:\python34\scripts\pip exe ; On OS X at / library / frameworks / python framework/Versions/3.4/bin/pip3 ; On Linux at / usr/bin/pip3
-
Installing third-party modules
On Win, run pip install ModuleName; On OS X or Linux, run sudo pip3 install ModuleName