Chapter One Grammar Basics
Definition of software
Refers to a collection of computer data and instructions organized in a specific order.
Data: Some data that the computer can recognize. In the hard disk: avi, doc, txt, py, in the memory: constants, variables, functions, objects, classes.
Instructions : The steps to manipulate these data to perform pre-requisite calculations.
Software operation process
The code written by Python is called source code. Can the source code be directly recognized by the computer? Compile the source code into machine code that the computer can recognize, and then the computer executes the machine code.
Two operating modes of the software:
-
Graphical interface operation mode
-
Command line operation mode
High-level programming languages are divided into two categories:
-
Statically compiled type: C, C++, Java
-
Compile: The source code must be completely compiled into a machine code file, and then the machine code file must be executed and the program run
-
Static: Variables must have clear data type definitions
-
-
Dynamically interpreted: Python, JavaScript, Mathlab, Ruby, Go
-
Explanation: There is no need to completely convert the code into machine code, read one source code-compile one sentence-run one sentence
-
Dynamic: Variables have no clear data type definition, any data type variable can be stored
-
1.1 Basic data
Integer int
Usually called an integer, it is zero, positive and negative, without a decimal point.
When expressing numbers, we can also use the hexadecimal form of two, eight, ten, hexadecimal
>>> print(10)
10
>>> print(1001)
1001
>>> print(0b1001)
9
>>> print(0o1234)
668
>>> print(0x9C1A)
39962
>>> print(0x9W2Y)
File "<stdin>", line 1
print(0x9W2Y)
^
SyntaxError: invalid syntax
Note: the printed result is always decimal
Python's integer length is 32 bits-4 bytes, and it is usually a continuous allocation of memory space id() function
>>> id(0)
2034812832
>>> id(1)
2034812848
>>> id(2)
2034812864
When Python initializes the environment, it divides a space in the memory, dedicated to the access of integer objects. Of course, this space is not infinite, and the data that can be stored is limited.
>>> id(251)
2034816848
>>> id(260)
13647712
>>> id(-10)
13647696
Small integer object pool
When Python is initialized, it will automatically create a small integer object pool, which is convenient for us to call and avoid repeated generation later. It only contains -5~256. These numbers are our most commonly used numbers, so they are loaded into memory by Python in advance. For the use of integers, if it is not between -5 and 256, it will be recreated.
>>> id(-5)
2034812752
>>> id(-6)
13647728
>>> id(256)
2034816928
>>> id(257)
13647648
>>> id(300)
13647696
>>> id(300)
13647712
>>> id(300)
13647680
Floating point type float
Floating-point numbers are decimals. If the decimals are too long, they can also be expressed in scientific notation.
>>> print(3.14)
3.14
>>> print(1.298765e10)
12987650000.0
>>> print(0.89e-5)
8.9e-06
>>> print(1.23e-8)
1.23e-08
Complex
A complex number is composed of real and imaginary parts, a+bj
>>> print(1+2)
3
>>> print(1+2j)
(1+2j)
>>> (1+2j)*(1-2j)
(5+0j)
>>> complex(1,2)*complex(1,-2)
(5+0j)
Bool
Right and wrong, 0 and 1, positive and negative, are all boolean types in the traditional sense
In Python, there are only two Boolean types True and False
Boolean types can only exist in logical operations and comparison operations
>>> True + False
1
>>> True - False
1
>>> 3 > 2
True
>>> 2 < 1
False
>>> 3 > 2 and 2 < 1
False
None空值 NoneType
The null value cannot be understood as the number 0, it is the empty set φ; we mainly use it in creating sequences and in object-oriented programming.
>>> None + 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'
>>> [None] * 10 # 创建一个长度为10的列表 没有数据 但有空间
[None, None, None, None, None, None, None, None, None, None]
String str
There are three forms of character string: single quote, double quote, triple quote (usually used in comments)
>>> print("HelloWorld")
HelloWorld
>>> print('你好')
你好
>>> print(" '' ")
''
>>> print(' "" ')
""
>>> print(' ' ')
File "<stdin>", line 1
print(' ' ')
^
SyntaxError: EOL while scanning string literal
>>> print(' \' ')
'
Escapes
-
\\
: Backslash -
\'
:apostrophe -
\"
:Double quotes -
\n
: Wrap -
\t
: Horizontal tab
>>> print(' \' ')
'
>>> print("\")
File "<stdin>", line 1
print("\")
^
SyntaxError: EOL while scanning string literal
>>> print("\\")
\
variable
Variable : The amount by which the value will change during the running of the program.
Constant: The amount by which the value will not change during the running of the program. (Literal, data that appears directly in the code)
Regardless of whether it is a variable or a constant, a space is opened in the memory when it is created to save their value.
# Java中基本数据类型变量a,b 和 引用数据类型变量c d e
int a = 3;
int b = 8;
Object c = new Object();
Object d = new Object();
Object e = c;
In Python, everything is an object!
>>> a = 1
>>> b = 1
>>> c = 1
>>> a == b
True
>>> id(1)
2034812848
>>> id(a)
2034812848
>>> id(b)
2034812848
>>> d = a
>>> d == b
True
>>> num1 = 300
>>> num2 = 300
>>> num3 = 300
>>> id(num1)
13647712
>>> id(num2)
13647696
>>> id(num3)
13647680
>>> num1 == num2
True
You can't blindly compare the address, but also compare whether the contents of the two objects are equal.
In the variable space, only the address of a certain data object can be stored, and the variable is just a reference to the object
Variables must be assigned before they can be called.
>>> print(num4)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'num4' is not defined
Variables can be assigned continuously:
>>> a=b=c=10
>>> a
10
>>> b
10
>>> c
10
>>> a,b,c =10,20,30
>>> a
10
>>> b
20
>>> c
30
>>> a=b=c=1000
>>> id(a)
13647776
>>> id(b)
13647776
>>> id(c)
13647776
>>> a=1000
>>> b=1000
>>> c=1000
>>> id(a)
13647792
>>> id(b)
13647648
>>> id(c)
13647824
The variable itself in Python has no data type constraint, it is just a reference to an object, and it stores the memory address of the object data
Only data types are distinguished between data objects.
Identifier
The so-called identifier is the name we give to variables, constants, functions, classes, etc.
The following provisions:
-
The first character must be a letter or underscore
_
-
Although Python supports Chinese, we can also use Chinese to name, but we do not recommend
-
The words beginning with an underscore have a special meaning in object-oriented programming-private
-
-
The other parts of the identifier consist of letters, numbers, and underscores
-
Identifiers are case sensitive
-
Variable names are all lowercase and constant names are all uppercase (there is no constant PI = 3.14 in Python, and it is essentially a variable)
-
The function name is lowercase and underscored, which is equivalent to the variable name
-
The class name uses the big camel case naming method: if the name consists of multiple words, the first letter of each word is capitalized
变量的命名不要使用关键字和内置函数的名称!
>>> True = 2
File "<stdin>", line 1
SyntaxError: cannot assign to True
>>> if = 3
File "<stdin>", line 1
if = 3
^
SyntaxError: invalid syntax
Keyword
Refers to words that have been given special meanings by high-level programming languages.
>>> import keyword
>>> keyword.kwlist
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
Also cannot use built-in functions (change the name of built-in functions for other purposes)
>>> id(2)
2034812864
>>> id = 3
>>> id + 1
4
>>> id(4)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
In Python, everything is an object, and functions themselves are objects!
>>> id(2)
2034812864
>>> id(id)
45545184
>>> abc = id
>>> abc(1)
2034812848
>>> id(1)
2034812848
>>> id = 10
>>> print(id)
10
>>> abc(id)
2034812992
How many built-in functions are there?
>>> dir(__builtins__)
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', '_', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__', 'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'breakpoint', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']
Comment
Note: A piece of text information used by the program is not considered part of the program.
-
Single line comment : # comment content
-
Multi-line comments : multiple single-line comments
-
Document note : """ The content of the note can explain the class information function information """