Understand the Python
- Guido Van Rossum, the father of Python, was a Dutch programmer who wrote Pyhon on Christmas Day 1989.
- The first Python interpreter was created in 1991, written in C
- Python2.0 was born in 2000
- Python3.0 was born in 2008
- Python2.0 was discontinued in 2020, and Python3.0 was more concise
- Python is a high-level object-oriented programming language. It is a dynamically interpreted language with elegant structure and clear syntax. It is easy to learn. Provides rich third-party libraries. Python can also call code from other languages, also known as glue languages.
- Python is used in many fields, including artificial intelligence, data science, writing system tools, apps, automation scripting, WEB development…
Basic Python syntax
- annotation
- Single-line comments are implemented using # comment content numbers
- Use “” “comment content “” “triple quotes to implement multi-line comments
- Import libraries
- Import the module import OS
- Import objects from OS import getcwd
- Import the module and name it “import pandas as pd”
- Variable used
- Variable names (identifiers) in Python consist of alphanumeric underscores (_) and cannot start with a number or have the same name as a keyword
- Look at the keyword keyword. Kwlist or help(” keywords “) in Python
- Python divides variables into global variables (used throughout the module) and local variables (used within defined methods and functions) based on scope.
- Execution order Python statements are executed top-down
- Python uses indentation to distinguish blocks of code. The indentation can be n >=1, and must be consistent globally
- Basic function
Python data structures
There are six types of built-in data structures in Python: Number, String, List, Tuple, Dictionary, and Set. In addition to the array, matrix and other structures need to import toolkit to use.
The numerical
Python3 supports values of int, float, bool, and complex
- Print (a/b) : get the floating-point value of a divided by b
- Print (a // b)
- Print (a ** b)
string
In Python, a string is a sequence of one or more characters, the number of characters being the length of the string. Note that there are no character types in Python, and individual characters are treated as strings of length 1.
-
Create strings: Strings created using single or double quotation marks are exactly the same. Triple-quoted strings can be multi-line strings, as shown below
-
Escape character: The escape character \n can be used to create multi-line strings with single or double quotation marks, as well as the special character masking function \
-
Raw string: Print the original string by adding r to the front of the string, S = r”P\y\thon”
-
Accessing string elements: Accessed by subscript, a string is an ordered and immutable structure
-
String addition and multiplication: Addition for concatenation, multiplication for repetition
-
Str.split (str1) Splits the string with str1 as the separator
-
Str.replace (str1, str2) Replaces str1 with str2 to generate a new string
-
String case conversion: str.lower() converts uppercase characters in a string to lowercase characters, and str.upper() converts lowercase characters in a string to uppercase characters
-
String concatenation: str.join(iter) generates a new string by concatenating each element in the given parameter iter with the specified string STR
-
Format output: Use the formatting operator % to assist in formatting output, such as print(” My name is %s, age is %d. “%(‘ Python ‘, 31))
The list of
A list is a sequence in which elements can be of any data type and can be added or removed at any time.
Print (List) print(List) print(List) print(1, 0, 3)Copy the code
-
List operators Operators in lists are the same as in strings, as follows
A = b = [1, 2, 3] [4, 5] print (a * 2) # print [1, 2, 3, 1, 2, 3] print (a + b) # print [1, 2, 3, 4, 4]
- List index and slice index access from 0 to n-1, all ordered sequences can use slice List[start: end: Step], can be omitted when start is 0, end is n-1, and step is 1. Note that when step is negative, the value is reversed
tuples
A tuple is an immutable ordered sequence, similar to a string, except that objects in a tuple can be arbitrary objects.
The Tuple = (1, 'a', 'b'], "Python") # create tuples print (a Tuple) # print (1, (' a ', 'b'), 'Python') print(type(Tuple)) #Copy the code
-
To create a single tuple, use a comma to indicate that it is a tuple
-
The tuple cannot be changed. If you modify the tuple, an error will be reported. It is not recommended to modify the tuple in disguised form
t1 = (1) t2 = (1,) print(“t1 type: “, type(t1), “\n” “t2 type: “, type(t2))
T1 type:
T2 type:
The dictionary
Each element of a dictionary in Python consists of a set of key-value pairs, where the key is uniquely immutable, and if the dictionary has the same key, the subsequent value overwrites the previous value. When data volumes are large, dictionaries are faster to access than lists.
-
Dictionary definition
Three dictionary assignment operations
x1 = {‘name’:’Caso’, ‘age’:18, ‘sex’:’man’} x2 = dict(name = ‘Caso’, age = 18, sex = ‘man’) x3 = dict([(“name”, “Caso”), (“age”, 18), (“sex”, “man”)]) print(x1) print(x2) print(x3)
{” name “:” Caso ‘, ‘age: 18,’ sex ‘:’ the man ‘} {” name “:” Caso ‘, ‘age: 18,’ sex ‘:’ the man ‘} {” name “:” Caso ‘, ‘age’ : 18, “sex” : ‘the man’}
-
Get dictionary data
1. Obtain a value by using a key. If a key does not exist, an error message is displayed
print(x1[‘name’])
2. Use get(key, [” STR “]) to obtain data
print(x1.get(“age”))
2.1 None or the specified value will be returned if a key value does not exist when getting a value using GET
print(x1.get(“school”)) print(x1.get(“school”, “school not exist”))
3. View all keys
print(x1.keys())
4. View all values
print(x1.values())
5. View all key/value pairs
print(x1.items())
The above code output is as follows:
Caso 18 None school not exist dict_keys([‘ name ‘, ‘age’, ‘sex’]) dict_values([‘ Caso ‘, 18, ‘man’]) dict_items([(‘ name ‘, ‘Caso’), (‘ age ‘, 18), (‘ sex ‘, ‘man’)]
-
Insert data into the dictionary
X1 [“school”] = “print(x1)
{” name “:” Caso ‘, ‘age: 18,’ sex ‘:’ man ‘, ‘school’ : ‘Edinburgh}’
-
Modify data in the dictionary
x1[“age”] = 25 print(x1)
{” name “:” Caso ‘, ‘age: 25,’ sex ‘:’ man ‘, ‘school’ : ‘Edinburgh}’
A collection of
Elements in Python collections are unique, and duplicate elements are removed.
-
Define a collection
keyset = {‘name’, ‘age’, ‘sex’, ‘school’}
Use in to check if an element exists
print(“score” in keyset)
False
-
Add elements
Set.add (obj) adds an element to the collection. If the element already exists, nothing is done
keyset.add(‘name’) keyset.add(‘score’) print(keyset)
{‘ score ‘, ‘name’, ‘school’, ‘sex’, ‘age’}
-
Remove elements
Set.remove (obj) removes the specified element from the collection
keyset.remove(‘name’) print(keyset)
{‘ score ‘, ‘school’, ‘sex’, ‘age’}
-
Set uniqueness
Test = [1, 2, 3, 2, 3, 5]
Use the uniqueness of the set to deduplicate the list
print(list(set(Test)))
[1, 2, 3, 5]
Python control flow
The control flow keywords in Python are if, elif, else, for, while, break, continue.
If statement
Conditional control in Python determines which block of code to execute by determining the result of a conditional statement (True or False); There are several code blocks that can use if-elif-else as follows:
Is it a dog? If game == 'Dog': print("Oh, you're True Dog!") ) elif game == 'not Dog': print("hh, you're not Dog! Congratulation!" ) else: print("Ok, you are man?" )Copy the code
Note that 0, None, and null values are False by default in Python, and all others are True
For loop
Python’s for loop differs from other languages in that it takes an iterable (such as a sequence) as its arguments, one at a time. The for loop can also be followed by an else, which will execute normally after the loop ends.
For I in ['you', 'are', 'true', 'dog']: print(I) else: print(" )Copy the code
You are true dog!
Nested loops in Python, eg: output multiplication tables
for i in range(1, 10):
for j in range(1, i+1):
print("%dX%d=%-2d"%(j, i, j*i), end=" ")
print()
Copy the code
1X1=1
1X2=2 2X2=4
1X3=3 2X3=6 3X3=9
1X4=4 2X4=8 3X4=12 4X4=16
1X5=5 2X5=10 3X5=15 4X5=20 5X5=25
1X6=6 2X6=12 3X6=18 4X6=24 5X6=30 6X6=36
1X7=7 2X7=14 3X7=21 4X7=28 5X7=35 6X7=42 7X7=49
1X8=8 2X8=16 3X8=24 4X8=32 5X8=40 6X8=48 7X8=56 8X8=64
1X9=9 2X9=18 3X9=27 4X9=36 5X9=45 6X9=54 7X9=63 8X9=72 9X9=81
While loop statement
The while statement in Python, if the loop condition is true, executes the body of the loop, or else. There is no do-while statement in Python.
Game = ['life', 'is', 'True'] I = 0 while I < 3: print(game[I]) I += 1 else: print("... )Copy the code
Life is True…
Break and continue
In Python, break is used to break out of the current loop, and continue is used to skip subsequent loops
While True: game = input(" please admit you are dog! \n") if game == "You are real dog ": print(" Ok, real dog!" ) break; Else: print(" Do not admit it? Until you admit it!" Continue print(" You can't get here anyway!" ) # either break or continueCopy the code
Python functions
Custom function def
A custom function that returns a sequence in which each number is the sum of the first two numbers (Fibonacci sequence)
def fibs(nums):
result = [0, 1];
for i in range(2, nums):
val = result[i-1] + result[i-2]
result.append(val)
return result
print(fibs(5))
Copy the code
[0, 1, 1, 2, 3]
There are several ways to pass arguments in Python functions:
def func(a=1, b=2, *args):
print(a, b)
print(args)
1. Set required parameters
func(0, 4)
2. Pass keyword parameters
func(b=4, a=0)
3. Upload default parameters
func()
4. Pass variable length parameters
func(1, 2, 3, 4, 5)
1 1 2 2 (3, 4, 5)
Anonymous function lambda
Lambda in Python is used to create anonymous functions, which are simply expressions compared to regular functions. The function body is simpler than DEF and encapsulates only limited logic.
max = lambda x,y : x + y
max(2, 3)
Copy the code
5
Python objects
Classes are created in Python using the class keyword and have encapsulation, polymorphism, and inheritance features.
Class Person(object): def __init__(self, age, name): # self. self.name = name def show(self): print("My name is %s"%(self.name)) print("age: %d"%(self.__age)) # instantiate object p1 = Person(age=18, name="dog") p1.show() # Man = man (age=25, name="Caso") man.show()Copy the code
My name is dog
age: 18
My name is Caso
age: 25
By default, attributes are public in Python, and are accessible by the module in which the class resides or by any other module that imports the class. You can privatize properties of a class that you don’t want to access or inherit.
- An underscore _ precedes an attribute or method to prevent it from being imported for use in other modules, but only in the current module
- Add two underscores __ before an attribute or method to make it fully private and inaccessible outside the class
Python file reading and writing
Python has a built-in function for reading and writing files: open, which returns file objects. Common usage: open(filename, mode, encoding)
F = open(“text.txt”, ‘w’) # open the text.txt file and create a new one if it doesn’t exist
STR = input(” Input what to write: “)
F. write(STR) # write the STR content to the file
F.close () # close the file descriptor
E:>type text.txt Caso_ caso
Python exception catching
A program exception is a run-time error (such as zero dividend, out-of-bounds list subscript, string modification, etc.). The Python keywords used to handle exceptions include try, except, and final.
Print (1/0) except Exception as e: # Exception Print (e) finally: Print (" Finally statement will be executed at the end ")Copy the code
Division by Zero eventually executes the statement in finally
A library of common Python tools
About this part of the content is prepared to write another blog summary, divided into a common standard library, third-party library according to the use of specific library to make a summary, and finally summarize a link out.
The standard library
Some of Python’s built-in libraries, such as the OS, SYS, and time modules, are going to write a separate blog summary. The Python standard library — OS module
Third-party libraries
Third-party libraries that need to be installed by yourself. Libraries such as NUMPY (Scientific computing) and PANDAS (data processing)
Author: Caso_ caso blog: blog.csdn.net/xiaoma_2018 copyright notice: this article shall not be reproduced without permission
For a complete tutorial on starting Python from scratch, click hereThe blue wordsTo get!