1. Basic data type
1.1 numerical type
All data in Python are objects, such as well-known int integer objects, float double precision floating-point objects and bool logical objects, which are all single elements. Two examples.
Prefix with 0x to create a hexadecimal integer:
0xa5 # Equal to 165 decimal
Use e to create floating-point numbers in scientific notation:
1.05e3 # 1050.0
1.2 container type
Container objects that can hold multiple elements, such as list objects, tuple tuple objects, dict dictionary objects, and set collection objects. Python defines these types of variables, and the syntax is very concise.
Examples are as follows.
Create a list variable with a pair of brackets []:
lst = [1,3,5] # list variable
According to the schematic diagram, the container on the right is open-loop, which means that elements can be added and deleted into the container:
Create a tuple object with a pair of parentheses ():
tup = (1,3,5) # tuple variable
The diagram shows that the container on the right is closed, which means that once a tuple is created, elements cannot be added or deleted into the container:
However, it should be noted that tuples containing a single element must be followed by a comma before they can be interpreted as tuples.
tup = (1,) # Comma must be reserved
Otherwise, it will be considered as the element itself:
In [14]: tup=(1) ...: print(type(tup)) <class 'int'>
Using a pair of curly braces {} and a colon:, create a dict object:
dic = {'a':1, 'b':3, 'c':5} # dict variable
The dictionary is a hash table. The following diagram vividly expresses the "shape" of the dictionary.
Create a set object using only a pair of curly braces {}:
s = {1,3,5} # Set variable
Python's container types, such as list, dict, tuple and set, can easily realize powerful functions. The following examples are given.
1. Get the best and average "remove the maximum and minimum"
Before we begin to write the final code, let's write out the basic knowledge we need. That is: round.
1.1 Python 3 round() function
describe
The round() method returns the rounded value of the floating-point number x. to be exact, the reserved value will be retained to the end closer to the previous bit (rounded).
This function is not recommended for those with high accuracy requirements.
grammar
The following is the syntax of the round() method:
round( x [, n] )
parameter
- x – numeric expression.
- n – indicates the number of decimal places, where x needs to be rounded, and the default value is 0.
Return value
Returns the rounded value of a floating-point number x.
example
The following shows an example of using the round() method:
print("round(70.23456) : ", round(70.23456)) print("round(56.659,1) : ", round(56.659, 1)) print("round(80.264, 2) : ", round(80.264, 2)) print("round(100.000056, 3) : ", round(100.000056, 3)) print("round(-100.000056, 3) : ", round(-100.000056, 3))
Output result:
round(70.23456) : 70 round(56.659,1) : 56.7 round(80.264, 2) : 80.26 round(100.000056, 3) : 100.0 round(-100.000056, 3) : -100.0
Take a look at an example given on the official website:
>>> round(2.675, 2) 2.67
According to our idea, the return result should be 2.68, but the result is 2.67. Why?
This is related to the precision of floating point numbers. We know that floating-point numbers may not be accurately expressed in the machine, because they may be infinite after being converted into a string of 1 and 0, and the machine has made truncation. Then the number of 2.675 saved in the machine is a little smaller than the actual number. This makes it a little closer to 2.67, so it's close to 2.67 when you keep two decimal places.
Because the function does not calculate the returned floating-point number according to the rounding rule, but will be affected by the accuracy of computer representation.
For this question, the address of the article with clear explanation after search is as follows: http://www.runoob.com/w3cnote/python-round-func-note.html
Next, let's write the final object code: after removing a minimum value and a maximum value from the list, calculate the average value of the remaining elements.
def score_mean(lst): lst.sort() lst2 = lst[1:-1] return round((sum(lst2) / len(lst2)), 1) lst = [9.1, 9.0, 8.1, 9.7, 19, 8.2, 8.6, 9.8] print(score_mean(lst)) # 9.1
Code execution process, animation demonstration:
2. Print 99 multiplication table
Print out the multiplication table in the following format:
1*1=1 1*2=2 2*2=4 1*3=3 2*3=6 3*3=9 1*4=4 2*4=8 3*4=12 4*4=16 1*5=5 2*5=10 3*5=15 4*5=20 5*5=25 1*6=6 2*6=12 3*6=18 4*6=24 5*6=30 6*6=36 1*7=7 2*7=14 3*7=21 4*7=28 5*7=35 6*7=42 7*7=49 1*8=8 2*8=16 3*8=24 4*8=32 5*8=40 6*8=48 7*8=56 8*8=64 1*9=9 2*9=18 3*9=27 4*9=36 5*9=45 6*9=54 7*9=63 8*9=72 9*9=81
There are 10 rows in total. Column j of row i is equal to: j*i, where:
- i value range: 1 < = i < = 9
- j value range: 1 < = j < = I
According to the language description of "example analysis", it is converted into the following code:
In [13]: for i in range(1,10): ...: for j in range(1,i+1): ...: print('%d*%d=%d'%(j,i,j*i),end='\t') ...: print()
3. Sample sampling
Using sample sampling, the following example randomly samples 10 samples from 100 samples.
from random import randint, sample lst = [randint(0, 50) for _ in range(100)] print(lst[:5]) # [38, 19, 11, 3, 6] lst_sample = sample(lst, 10) print(lst_sample) # [33, 40, 35, 49, 24, 15, 48, 29, 37, 24]
1.3 string
Note that there is no character type (char) like C + + in Python. All characters or strings are unified as STR objects. For example, the type of single character c is also str.
str type will be used frequently. First list five methods that are used frequently.
- strip is used to remove spaces before and after a string:
In [1]: ' I love python\t\n '.strip() Out[1]: 'I love python'
- Replace is used to replace strings:
In [2]: 'i love python'.replace(' ','_') Out[2]: 'i_love_python'
- join is used to merge strings:
In [3]: '_'.join(['book', 'store','count']) Out[3]: 'book_store_count'
- title is used to capitalize the first character of a word:
In [4]: 'i love python'.title() Out[4]: 'I Love Python'
- find is used to return the starting position index of the matching string:
In [5]: 'i love python'.find('python') Out[5]: 7
For example, in the case of application string, judge whether str1 is rotated from str2.
After the string stringbook is rotated, the bookstring is obtained. Write a piece of code to verify whether str1 is obtained by str2 rotation.
**It is converted to judge whether * * str1 is a substring of str2+str2.
In the following function prototype, the type of each parameter and the type of return value are indicated to enhance the readability and maintainability of the code.
def is_rotation(s1: str, s2: str) -> bool: if s1 is None or s2 is None: return False if len(s1) != len(s2): return False def is_substring(s1: str, s2: str) -> bool: return s1 in s2 return is_substring(s1, s2 + s2)
Test function is_rotation:
r = is_rotation('stringbook', 'bookstring') print(r) # True r = is_rotation('greatman', 'maneatgr') print(r) # False
Code execution process, animation demonstration:
In addition to the str encapsulation method, the re regular module of Python is more powerful and easier to write. It is widely applicable to crawlers, data analysis and so on.
The following example is implemented: password security check, which is very easy to implement using regular expressions.
Password security requirements:
- The password is required to be 6 to 20 digits;
- The password contains only English letters and numbers.
import re pat = re.compile(r'\w{6,20}') # This is wrong because the \ w wildcard matches letters, numbers and underscores. The title must not contain underscores # Use the most stable method: \ da-zA-Z meet the requirement of "password only contains English letters and numbers" # \d matches numbers 0-9 # Match all lowercase characters with z-a; Match all uppercase characters z-a pat = re.compile(r'[\da-zA-Z]{6,20}')
Select the safest fullmatch method to check whether the whole string matches.
The following test examples return None, and the reasons are explained.
pat.fullmatch('qaz12') # Return None, length less than 6 pat.fullmatch('qaz12wsxedcrfvtgb67890942234343434') # None length greater than 22 pat.fullmatch('qaz_231') # None contains underscores
The following string n0passw0Rd fully matches:
In [20]: pat.fullmatch('n0passw0Rd') Out[20]: <re.Match object; span=(0, 10), match='n0passw0Rd'>
1.4 custom types
Python uses the keyword class to customize its own class, and self represents the class instance object itself.
A custom class includes attributes and methods, some of which are self-contained.
Class (object):
class Dog(object): pass
The above defines a Dog object, which inherits from the root class object. pass means that there are no custom attributes and methods.
Next, create an instance of Dog type:
wangwang = Dog()
The Dog class does not define any methods at present, but as mentioned earlier, it will have its own methods. Use dir() to view these own methods:
In [26]: wangwang.__dir__() Out[26]: ['__module__', '__dict__', '__weakref__', '__doc__', '__repr__', '__hash__', '__str__', '__getattribute__', '__setattr__', '__delattr__', '__lt__', '__le__', '__eq__', '__ne__', '__gt__', '__ge__', '__init__', '__new__', '__reduce_ex__', '__reduce__', '__subclasshook__', '__init_subclass__', '__format__', '__sizeof__', '__dir__', '__class__']
In some places, the above methods are called magic methods, which are related to customizing personalized behavior when creating classes. For example:
- init method can define a class with parameters;
- The new method defines the behavior of the instantiated class;
- getattribute method customizes the behavior of reading attributes;
- setattr defines the behavior when assigning and modifying attributes.
Properties of class:
def __init__(self, name, dtype): self.name = name self.dtype = dtype
Through init, define two attributes of Dog object: name and dtype.
Instance of class:
wangwang = Dog('wangwang','cute_type')
wangwang is an instance of the Dog class.
Method of class:
def shout(self): print('I\'m %s, type: %s' % (self.name, self.dtype))
be careful:
- The first parameter of the custom method must be self, which points to the instance itself, such as the dog instance of dog type;
- When referencing an attribute, you must add self before it, such as self Name et al.
Summarize the above Codes:
In [40]: class Dog(object): ...: def __init__(self,name,dtype): ...: self.name=name ...: self.dtype=dtype ...: def shout(self): ...: print('I\'m %s, type: %s' % (self.name, self.dtype)) In [41]: wangwang = Dog('wangwang','cute_type') In [42]: wangwang.name Out[42]: 'wangwang' In [43]: wangwang.dtype Out[43]: 'cute_type' In [44]: wangwang.shout() I'm wangwang, type: cute_type
See that the two properties and a method created are exposed and can be called by wangwang. In this way, these properties will be modified arbitrarily:
In [49]: wangwang.name='wrong_name' In [50]: wangwang.name Out[50]: 'wrong_name'
If you want to prevent the attribute name from being modified, you can make it a private variable. Change method: add 2 before the attribute_ After, it becomes a private property. For example:
In [51]: class Dog(object): ...: def __init__(self,name,dtype): ...: self.__name=name ...: self.__dtype=dtype ...: def shout(self): ...: print('I\'m %s, type: %s' % (self.name, self.dtype))
Similarly, add 2 before the method_ After, the method becomes a "private method" and can only be shared within the Dog class.
However, after this change, the attribute name cannot be accessed, and the name of wangwang cannot be known. However, there is a simple solution to this problem. Just define a new method:
def get_name(self): return self.__name
Comprehensive code:
In [52]: class Dog(object): ...: def __init__(self,name,dtype): ...: self.__name=name ...: self.__dtype=dtype ...: def shout(self): ...: print('I\'m %s, type: %s' % (self.name, self.dtype)) ...: def get_name(self): ...: return self.__name ...: In [53]: wangwang = Dog('wangwang','cute_type') In [54]: wangwang.get_name() Out[54]: 'wangwang'
However, it is not elegant to change the readability or Writeability of attributes through this mechanism! Because some redundant methods are added, such as get_name.
Next, through another example, explain how to more gracefully change a property to read-only or write only.
Customize the simplest Book class, which inherits from the root class object of the system:
class Book(object): def __init__(self,name,sale): self.__name = name self.__sale = sale
Using Python's own property class, you will gracefully change the name to read-only.
@property def name(self): return self.__name
use @property After decoration, name becomes an attribute, which means Name will return the name of the book, not through name() is a method called by this function. This makes it more readable when it becomes a real attribute.
In [101]: class Book(object): ...: def __init__(self,name,sale): ...: self.__name = name ...: self.__sale = sale ...: @property ...: def name(self): ...: return self.__name In [102]: a_book = Book('magic_book',100000) In [103]: a_book.name Out[103]: 'magic_book'
property is Python's own class, and the first three parameters are function types. A more detailed discussion will be carried out later when discussing decorators.
In [104]: help(property) Help on class property in module builtins: class property(object) | property(fget=None, fset=None, fdel=None, doc=None)
If you make name both readable and writable, add another decorator @ name setter.
In [105]: class Book(object): ...: def __init__(self,name,sale): ...: self.__name = name ...: self.__sale = sale ...: @property ...: def name(self): ...: return self.__name ...: @name.setter ...: def name(self,new_name): ...: self.__name = new_name In [106]: a_book = Book('magic_book',100000) In [107]: a_book.name = 'magic_book_2.0' In [108]: a_book.name Out[108]: 'magic_book_2.0'
Notice how this decorator is written: name Setter and name have been wrapped as property instances. Call the setter function on the instance and wrap the name to make it writable. For Python beginners, you don't have to worry about this part of the theory for the time being. After using Python for a period of time, you will naturally understand it by looking back.
Summary
Today, learn the four basic data types of Python. Numerical type int, float, etc; Container type list, dict, tuple, set, etc; Introduction to character str and regular expression; Basic syntax rules of user-defined classes, such as classes, properties and methods.