Python is a computer programming language. Computer programming languages and natural language we use every day is different, the biggest difference is that natural languages have different interpretations in different contexts, and the computer to perform tasks according to the programming language, you must ensure that the programming language to write programs there must be no ambiguity, therefore, any programming language has its own set of syntax , compiler or interpreter is responsible for converting grammatical program code into machine code the CPU can execute, and then executed. Python is no exception.
Python's syntax is relatively simple, using indented, write code that looks like the following:
# print absolute value of an integer: a = 100 if a>=0: print(a) else: print(-a)
In a #
statement at the beginning of a comment, the comment is posters, and can be anything, the interpreter will ignore the comment. Every other row is a statement, the statements by a colon :
at the end, indented statement as a code block.
Indent both advantages and disadvantages. Benefit is forcing you to write formatted code, but no provision is indented a few spaces or Tab. By convention management, you should always stick with the four spaces of indentation.
Another benefit is the indentation force you to write less code indentation, you will tend to split a long code into several functions, resulting in less code indentation.
Indent downside is "copy - paste" function failure, and this is where most pit father. When you refactor the code, paste the code must re-examine the past indentation is correct. In addition, IDE Java code as difficult as formatted formatted Python code.
Finally, be sure to pay attention, Python programs are case-sensitive, if the wrong case, the program will complain.
summary
Python uses indentation to organize code blocks, be sure to follow the customary, stick with the four spaces of indentation.
In a text editor, you need to set the Tab automatically converted into four spaces, and spaces to ensure that no mix Tab.
Data types and variables
A data type
The computer name suggests is that you can do the math to calculate the machine, therefore, a computer program can handle various values for granted. However, the computer can handle far more than the value, and can also process a variety of data, text, graphics, audio, video, web pages, different data, different data types need to be defined. In Python, data types can be processed directly are the following:
1 . Integer
Python integers of any size can be treated, including, of course negative integer representation in the program and written mathematical exactly the same, for example: 1
, , 100
, -8080
, 0
and the like.
Due to the use of a binary computer, so sometimes expressed in hexadecimal integer more convenient, hexadecimal with 0x
the prefix and 0-9, af, for example: 0xff00
, 0xa5b4c3d2
and so
2. Float
I.e. decimal floating-point, floating-point number is called, because when expressed in terms of scientific notation, a floating decimal point position is variable, for example, 1.23x10 . 9 and 12.3x10 . 8 are completely identical. Floating-point math can be written, such as 1.23
, 3.14
, -9.01
, and so on. However, for very large or very small float, it must be expressed in scientific notation, with the 10 e alternative, 1.23x10 . 9 is 1.23e9
, or 12.3e8
, 0.000012 can be written 1.2e-5
, and the like.
Integer and floating point numbers in a computer internal storage approach is different, integer arithmetic is always accurate (division Is it also accurate? Yes!), And floating-point operations may have rounding error.
3. String
String is single quotes '
or double quotes "
any text enclosed in, for example 'abc'
, "xyz"
and the like. Please note, ''
or ""
itself is only a part of the way, not a string representation, therefore, strings 'abc'
only a
, b
, c
these three characters. If '
itself is a character, it can ""
enclose, such as "I'm OK"
the character is included I
, , '
, m
space O
, K
these 6 characters.
If the string contains both internal '
and included "
how to do? Escape character can be used \
to identify, for example:
'I\'m \"OK\"!'
A string representation of the contents are:
I'm "OK"!
Escape character
\
can escape a lot of characters, such as\n
newline,\t
tab character, the character\
itself must be escaped, so the\\
character is expressed\
, can be used in interactive command-line Python'sprint()
look at print string:
>>> print('I\'m ok.') I'm ok. >>> print('I\'m learning\nPython.') I'm learning Python. >>> print('\\\n\\') \ \
If the string there are many characters need to be escaped, we need to add a lot \
, in order to simplify, Python also allows r''
representation ''
default does not escape the string inside, you can see for yourself:
>>> print('\\\t\\') \ \ >>> print(r'\\\t\\') \\\t\\
If the internal string has a lot of line breaks, with \n
write one line is not good reading, in order to simplify, Python allows '''...'''
format represents a number of lines, you can see for yourself:
>>> print('''line1 ... line2 ... line3''') line1 line2 line3
The above is in interactive command line input, pay attention when entering a multi-line, by the prompt >>>
changed ...
, suggesting that you can then enter on line, pay attention to ...
is part of the prompt, not the code:
>>> print('''line1 ... line2 ... line3''')
When the input complete terminator ```
, and parentheses )
after the statement is executed and print the results.
If the program is written and stored as a .py
file, that is:
print('''line1 line2 line3''')
Multiline strings '''...'''
may also preface r
use, self-testing:
print(r'''hello,\n world''')
4. Boolean value
Boolean algebra and Boolean value indicating exactly the same, only a Boolean value True
, False
two kinds of value, either True
, either False
, in Python, can be directly used True
, False
represents a Boolean value (note the case), can also be calculated by Boolean operators :
>>> True True >>> False False >>> 3 > 2 True >>> 3 > 5 False
Boolean values may be used and
, or
and not
operation.
and
Operation with operation, only if all are True
, and
the operation result is True
:
>>> True and True True >>> True and False False >>> False and False False >>> 5 > 3 and 3 > 1 True
or
A calculation or operation, as long as one is True
, or
the operation result is True
:
>>> True or True True >>> True or False True >>> False or False False >>> 5 > 3 or 1 > 3 True
not
Calculating a non-operation, which is a unary operator, put True
into False
, False
into True
:
>>> not True False >>> not False True >>> not 1 > 2 True
Boolean often used in determination conditions, such as:
if age >= 18: print('adult') else: print('teenager')
5. null
Null is a special value in Python, with None
representation. None
Can not understand it is 0
, because 0
it makes sense, but None
is a special null value.
In addition, Python also provides lists, dictionaries and other types of data, but also allows you to create custom data types, as we will continue mentioned.
Second, variable
Variable concept and substantially junior algebraic equation variables is the same, but in a computer program, the variables may be not only numbers, can also be any data type.
Variable in the program is expressed by a variable name, variable names must be uppercase and lowercase, numbers and _
combinations, can not start with a number, for example:
a = 1
Variable a
is an integer.
t_007 = 'T007'
Variable t_007
is a string.
Answer = True
Variable Answer
is a Boolean value True
.
In Python, the equal sign =
is the assignment statement, any data type can be assigned to a variable, the same can be repeated a variable assignment, and may be different types of variables, for example:
123 = A # A is an integer of Print (A) A = ' the ABC ' # A string becomes Print (A)
This type of variable itself is not fixed language called dynamic languages , corresponding to a static language . Static language must be specified when defining a variable variable type, time assignment if the type does not match, it will error. Static language such as Java, the assignment statement is as follows (// denotes a comment):
123 A = int; // A is an integer type variable A = " the ABC " ; // Error: the string can not be assigned to integer variables
And compared to static languages, dynamic languages are more flexible, and this is why.
Please do not take an assignment of the equal sign in mathematics equivalent of the equal sign. For example the following code:
x = 10
x = x + 2
If you understand mathematically x = x + 2
that in any case is not established in the program, the first assignment statement evaluates the expression on the right side x + 2
, get results 12
, and then assigned to the variable x
. Since the x
previous value 10
, re-assignment, x
the value becomes 12
.
Finally, understand the variables represent in the computer's memory is also very important. When we write:
a = 'ABC'
When, Python interpreter did two things:
-
Created in memory of a
'ABC'
string; -
We created a directory named in memory
a
variables, and it points to'ABC'
.
A variable can also a
be assigned to another variable b
, the operation is actually the variable b
pointing to the variable a
data points, for example the following code:
a = 'ABC' b = a a = 'XYZ' print(b)
Print out the last line of variable b
content in the end is 'ABC'
it still 'XYZ'
? If you understand the mathematical sense, will come erroneously b
and a
the same, it should be 'XYZ'
, but in fact b
the values are 'ABC'
, let's execute the code line by line, you can see in the end what happened:
Execution a = 'ABC'
, the interpreter creates strings 'ABC'
and variables a
, and to a
point to 'ABC'
:
Execution b = a
, the interpreter creates a variable b
, and to b
point to a
the string pointed to 'ABC'
:
Execution a = 'XYZ'
, the interpreter creates a string 'XYZ', and the a
point to be changed 'XYZ'
, but b
did not change:
Therefore, the final print variable b
result is naturally 'ABC'
a.
Third, the constant
The so-called constant variables that can not be changed, such as the commonly used mathematical constant π is a constant. In Python, usually expressed with constants in all uppercase variable names:
PI = 3.14159265359
But the fact PI
remains a variable, Python did not have any mechanism to ensure that PI
will not be changed, so, with all uppercase variable name indicates the usage of the constants just a habit, if you must change the variable PI
value, no one can stop you.
Finally explain why integer division is accurate. In Python, there are two division a division is /
:
>>> 10 / 3 3.3333333333333335
/
Floating-point division calculation result, even exactly divisible by two integers, floating point result is:
>>> 9 / 3 3.0
There is also a division is //
called the floor in addition, two integer division still is an integer:
>>> 10 // 3 3
You read right, integers floor in addition to //
always be an integer, even indivisible. Do mathematical division, use /
can be.
Since //
the integer part of the division result only taken, so Python also provides a modulo operation, the remainder can be divided by two integers:
>>> 10 % 3 1
Whether doing integer //
division or take the remainder, the result is always an integer, so the result is always integer arithmetic is accurate.
IV Summary
Python supports multiple data types, inside the computer, you can put any data as an "object", and the variable is used to refer to these data objects in the program, for variable assignment is to to associate the data and variables.
Variable assignment x = y
is the variable x
points to a real object, which is variable y
points to. Then the variable y
assignment does not affect the variable x
points to.
Note: Integer Python is no size limit, and some languages integer length are stored according to its size limit, for example 32-bit integer Java range limit -2147483648
- 2147483647
.
Python floats will no size limit, but beyond a certain range directly expressed as inf
(infinite).