Liaoche Python Notes

Source: Internet
Author: User
Tags floor division mathematical constants ord

command-line mode and Python interaction mode

In the Windows Start menu, select "Command Prompt" and go to command-line mode, its prompt is similar to c:\>;
In command-line mode, when you tap command python, you see a bunch of text output similar to the following, and then go into Python interactive mode, with the prompt >>>.
Entering exit () and enter in Python interactive mode exits the Python interaction mode and returns to the command line mode.

The python file name can only be a combination of English letters, numbers, and underscores. (But the practice proves that Chinese is also possible, but not recommended.) )
Print () prints each string sequentially, encountering a comma "," which outputs a space

Each line is a statement that, when the statement ends with a colon:, the indented statement is treated as a block of code.
Indentation has pros and cons. The advantage is that you are forced to write the formatted code, but there is no rule that indents are a few spaces or tabs. In accordance with established management, you should always stick to the indentation of 4 spaces.
Another benefit of indenting is forcing you to write less indented code, and you tend to split a very long piece of code into several functions, resulting in less code being indented.
The downside of indentation is that the "copy-paste" function fails, which is the most pit-daddy place. When you refactor the code, the pasted past code must re-check that the indentation is correct. In addition, it is difficult for the IDE to format Python code just like formatted Java code.
Finally, it is important to note that the Python program is case-sensitive, and if the case is written incorrectly, the program will give an error.

Integers and floating-point numbers are stored inside the computer in different ways, and integer operations are always accurate (is division accurate?). Yes! The result is always an integer, regardless of whether the integer is A//(floor division) or the remainder, so the result of the integer operation is forever accurate. The result of the/Division calculation is a floating-point number, even if the two integers are evenly divisible, the result is a floating-point number, and the floating-point arithmetic may have rounding errors.
Note: Python's integers have no size limit;
Python also has no size limit for floating-point numbers, but is represented as INF (infinity) beyond a certain range.

string is any text enclosed in single quotation marks ' or double quotation marks, note that ' or ' itself is only a representation, not part of a string. If ' itself is also a character, it can be enclosed in '. If the string inside contains both ' and ' can be identified with the escape character \ (for example: ' I\ ' m\ "ok\"! ') ), you can also use three single quotes or three double quotation marks (for example: "' I ' m" OK "! )。
Python also lets you use R ' to indicate that the string inside of ' is not escaped by default (for example,:>>> print (R ' \\\t\\ ') prints the result to \\\t\\).
If there is a lot of line wrapping inside the string, it is not good to read in a single line, and in order to simplify, Python allows multiple lines of content to be represented in the format ' multiline content '. such as
A= ' line1
Line2
Line3 ""
Print (a)
Prints the result as
Line1
Line2
LINE3)

The null value is a special value in Python, denoted by none. None cannot be understood as 0, because 0 is meaningful, and none is a special null value.

So-called constants are immutable variables, such as the usual mathematical constants π is a constant. In Python, constants are typically represented in all uppercase variable names: PI = 3.14159265359
But in fact pi is still a variable, Python does not have any mechanism to ensure that PI will not be changed, so, using all uppercase variable names to represent constants is only a customary usage, if you must change the value of the variable pi, no one can stop you.

Character encoding
ASCII encoding (1 bytes) →unicode encoding (2 bytes) →utf-8 encoding (variable byte)
Now the computer system common character encoding working mode:
In computer memory, Unicode encoding is used uniformly, and is converted to UTF-8 encoding when it needs to be saved to the hard disk or when it needs to be transferred. (Unicode in memory, UTF-8 on output device)

A Python string
For the encoding of a single character, Python provides an integer representation of the Ord () function to get the character, and the Chr () function converts the encoding to the corresponding character:
>>> Ord (' A ')
65
>>> Chr (66)
B

Because Python's string type is str, it is represented in memory in Unicode and a character corresponds to several bytes. If you want to transfer on the network, or save to disk, you need to turn str into bytes in bytes.
Python uses single or double quotation marks with a B prefix for data of type bytes:
x = B ' ABC '
Be aware of the distinction between ' abc ' and ' B ' abc ', which is STR, although the content is the same as the former, but each character of bytes occupies only one byte.

The STR represented in Unicode can be encoded as a specified bytes by using the Encode () method, for example:
>>> ' ABC '. Encode (' ASCII ')
B ' ABC '
>>> ' Chinese '. Encode (' Utf-8 ')
B ' \xe4\xb8\xad\xe6\x96\x87 '
Conversely, if we read the byte stream from the network or disk, then the data read is bytes. To turn bytes into STR, you need to use the Decode () method:
>>> b ' ABC '. Decode (' ASCII ')
' ABC '
>>> b ' \xe4\xb8\xad\xe6\x96\x87 '. Decode (' Utf-8 ')
Chinese

The Len () function calculates the number of characters in STR and computes the number of bytes if replaced by the Bytes,len () function:
>>> Len (' Chinese ')
2
>>> Len (' Chinese '. Encode (' Utf-8 '))
6

Formatting
The% operator is used to format the string. Inside the string,%s is replaced with a string,%d is replaced with an integer, there are several% placeholder, followed by a number of variables or values, the order to correspond well. If there is only one%, the parentheses can be omitted.
Placeholder Replacement Content
%d integers
%f floating Point
%s string
%x hexadecimal integer
where formatted integers and floating-point numbers can also specify whether to complement 0 and the number of digits of integers and decimals:
Print ('%2d-%02d '% (3, 1)) result is 3-01
Print ('%.2f '% 3.1415926) result is 3.14
If you're not sure what to use,%s will always work, and it will convert any data type to a string.

Another way to format a string is to use the format () method of the string, which in turn replaces the placeholder {0}, {1} ... in the string with the passed-in parameter, but this is a much more troublesome way to write than%:

>>> ' Hello, {0}, result increased {1:.1f}% '. Format (' Xiao Ming ', 17.125)
' Hello, xiaoming, 17.1% improvement in grades '


One of the data types built into Python is the list: lists. A list is an ordered, mutable set of elements that can be added and removed at any time, as an array. The data type of the elements inside the list can also be different. The number of list elements can be obtained with the Len () function, and the index is used to access the elements of each position in the list, remembering that the index from the left is starting at 0, and the index from the right is starting from 1.
>>> classmates = [' Michael ', ' Bob ', ' Tracy ']
>>> Classmates
[' Michael ', ' Bob ', ' Tracy ']

1 Append element to end:>>> Classmates.append (' Adam ')
>>> classmates
[' Michael ', ' Bob ', ' Tracy ', ' Adam ' ]
2 Inserts the element into the specified position:>>> classmates.insert (1, ' Jack ')
>>> classmates
[' Michael ', ' Jack ', ' Bob ' , ' Tracy ', ' Adam ']
3 to delete the element at the end of the list, use the Pop () method:>>> Classmates.pop ()
' Adam '
>>> classmates
[' Michael ', ' Jack ', ' Bob ', ' Tracy ']
4 to delete the element at the specified position, use the pop (i) method, where I is the index position:>>> classmates.pop (1)
' Jack '
>>> classmates
[' Michael ', ' Bob ', ' Tracy ']
5 to replace an element with another element, you can assign a value directly to the corresponding index position:>>> CLASSMATES[1] = ' Sarah '
>>> classmates
[' Michael ', ' Sarah ', ' Tracy ']
Note: These several actions against the list, Only deletions (4 and 5) are inherently output.

The other is ordered and directed unchanged (the so-called "invariant" of a tuple is that each element of a tuple, pointing to never change. After understanding "point to invariant", how do you create a tuple that does not change the content? It is necessary to ensure that every element of the tuple itself cannot be changed. The list is called tuples: tuple. Tuple and list are very similar, but once the tuple initialization can not be modified, when you define a tuple, at the time of definition, the elements of the tuple must be determined:>>> classmates = (' Michael ', ' Bob ', ' Tracy ')
A tuple of only 1 elements must be defined with a comma, to disambiguate (>>> t = (1) In this case, Python specifies that the parentheses in the mathematical formula are calculated as the result is 1):>>> t = (1,)
>>> T
(1,)
Summary: List and tuple are Python built-in ordered collections, one variable, one immutable.

Conditional Judgment If statement (note that the colon is not written less:.) )
If < condition judgment 1>:
< Executive 1>
Elif < condition judgment 2>:
< Executive 2>
Elif < condition judgment 3>:
< Executive 3>
Else
< Executive 4>
If statement execution has a characteristic, it is judging from the top, if in a certain judgment is true, the judgment corresponding to the execution of the statement, will ignore the remaining elif and else.

Loops (for and while conditional statements also have colons after them:)
One is the for...in loop, which sequentially iterates through each element in the list or tuple
names = [' Michael ', ' Bob ', ' Tracy ']
For name in Names:
Print (name)
Executing this code, each element of the names is printed sequentially

Python provides a range () function that generates a sequence of integers that can be converted to a list by using the list () function. For example, the series generated by range (5) is an integer starting from 0 that is less than 5:
>>> List (range (5))
[0, 1, 2, 3, 4]

The second loop is the while loop, which, as long as the condition is satisfied, loops continuously, exiting the loop when the condition is not satisfied. In the loop, the break statement can exit the loop in advance, and in the loop, it can also skip the current cycle through the Continue statement and start the next loop directly.

Summary:
The break statement can exit the loop directly during the loop, while the continue statement can end the cycle in advance and start the next cycle directly. These two statements usually have to be used with the IF statement.
Be especially careful not to misuse break and continue statements. Break and continue can cause too many logical forks for code execution and error-prone. Most loops do not need to use break and continue statements, often by overwriting the loop condition or by modifying the loop logic to remove the break and continue statements.
The program is trapped in a "dead loop", that is, the cycle continues forever. You can then use CTRL + C to exit the program.

Liaoche Python Notes

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.