Daydayup_python Self-study tutorial [1]_python Basics

Source: Internet
Author: User
Tags integer division

1 Data types

A computer is a machine that can do mathematical calculations as the name implies, so a computer program can handle a variety of values. However, the computer can handle far more than the numerical value, but also can deal with text, graphics, audio, video, web and other kinds of data, different data, need to define different data types. In Python, there are several types of data that can be processed directly:

1.1 Integers

Python can handle integers of any size, including, of course, negative integers, and in a Python program, integers are represented in exactly the same way as mathematically, for example: 1,100,-8080,0, and so on.

Computer because of the use of binary, so, sometimes hexadecimal notation is more convenient, hexadecimal with 0x prefix and 0-9,a-f, such as: 0XFF00,0XA5B4C3D2, and so on.

1.2 Floating point

Floating-point numbers, which are decimals, are called floating-point numbers because, when represented by scientific notation, the decimal position of a floating-point number is variable, for example, 1.23x10^9 and 12.3x10^8 are equal. Floating-point numbers can be written in mathematical notation, such as 1.23,3.14,-9.01, and so on. But for very large or very small floating-point numbers, it must be expressed in scientific notation, the 10 is replaced with E, 1.23x10^9 is 1.23e9, or 12.3e8,0.000012 can be written 1.2e-5, and so on.

Integers and floating-point numbers are stored inside the computer in different ways, and integer operations are always accurate (is division accurate?). Yes! ), and the floating-point operation may have rounding errors.

1.3 string

A string is any text enclosed in "or", such as ' abc ', ' XYZ ', and so on. Note that the "or" "itself is only a representation, not part of a string, so the string ' abc ' only a,b,c these 3 characters.

1.4 Boolean value

The Boolean value is exactly the same as the Boolean algebra, with a Boolean value of only true, false two, or true, or false, in Python, which can be used to indicate a Boolean value directly with True, false (note case), or by Boolean operations.

Boolean values can be operated with and, or, and not.

The and operation is associated with an operation, and only the result of all true,and operations is True.

An OR operation is an operation, as long as one of the true,or operation results is True.

The not operation is a non-operation, which is a single-mesh operator that turns true to False,false to true.

1.5 Null value

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.

In addition, Python provides a variety of data types, such as lists, dictionaries, etc., and also allows you to create custom data types.

1.6 Integers and floating-point numbers

Python supports four blending of integers and floating-point numbers directly, and the arithmetic rules are exactly the same as the arithmetic rules in mathematics.

Basic operations:

1 + 2 + 3   # ==> 64 * 5 - 6   # ==> 147.5 / 8 + 2.1   # ==> 3.0375

Using parentheses can elevate precedence, which is exactly the same as math, and note that only parentheses can be used, but parentheses may nest many layers:

(1 + 2) * 3    # ==> 9(2.2 + 3.3) / (1.5 * (9 - 0.3))    # ==> 0.42145593869731807

Unlike mathematical operations, the result of a Python integer operation is still an integer, and the result of the floating-point operation is still a floating-point number:

1 + 2    # ==> 整数 31.0 + 2.0    # ==> 浮点数 3.0

But the result of mixed integer and floating-point numbers becomes a floating-point number:

1 + 2.0    # ==> 浮点数 3.0

Why do you differentiate between integer and floating-point arithmetic? This is because the result of the integer operation is always accurate, and the result of the floating-point operation is not necessarily accurate, because the computer memory is large, and can not accurately represent the infinite loop of decimals, for example, 0.1 to binary representation is an infinite loop decimal.

Is the result not a floating-point number when the division operation of the integer is encountered in addition to the endless? Let's try it out:

11 / 4    # ==> 2

To the surprise of many beginners, the integer division of Python, even if it is not endless, the result is still an integer, the remainder is directly thrown away. However, Python provides a calculation of the remainder of the operation% that can be computed:

11 % 4    # ==> 3

If we want to calculate the exact result of 11/4, the "integer and floating-point mixed operation results are floating-point number" law, the two numbers of one into a floating point and then the operation is no problem:

11.0 / 4    # ==> 2.75
1.7 Boolean type

In Python, Boolean types can also do and, or, and not with other data types, see the following code:

a = Trueprint a and ‘a=T‘ or ‘a=F‘

The result of the calculation is not a Boolean type, but the string ' a=t ', which is why?

Because Python regards 0, empty string "and none as False, other numeric values and non-empty strings are considered True, so:

True and ' a=t ' calculation result is ' a=t '
Continue to calculate ' a=t ' or ' a=f ' results or ' a=t '
To explain the above results, it also involves an important law of the and and or operations: short-circuit calculation.

    1. When calculating A and B, if a is false, then according to the algorithm, the whole result must be false, so it returns a; If A is True, the entire result must depend on B, so it returns B.

    2. When a or B is computed, if a is true, the whole result must be true, according to the or algorithm, and therefore return a; If A is False, the whole result must depend on B, so it returns B.

So when the Python interpreter is doing a Boolean operation, as long as the calculation results can be determined in advance, it will not go back and return the result directly.

2 Print Statements

The print statement can output the specified text to the screen. For example, the output of ' Hello, world ', implemented in code as follows:

>>> print‘hello, world‘

Attention:

1. When we write code in a python interactive environment,,>>> is the prompt for the Python interpreter, not part of the code.

2. When we write code in a text editor, never add >>> yourself.

The print statement can also be followed by multiple strings, separated by a comma "," that can be connected to a string of outputs:

>>> print‘The quick brown fox‘‘jumps over‘‘the lazy dog‘The quick brown fox jumps over the lazy dog

Print prints each string sequentially, encounters a comma "," and outputs a space, so the output string is spelled like this:

Print also prints integers, or calculates the result:

>>> print300300    #运行结果>>> print100200300    #运行结果

Therefore, we can print the results of the calculation 100 + 200 more beautifully:

>>> print‘100 + 200 =‘100200100200300     #运行结果

Note: For the + 200,python interpreter automatically calculates the result 300, but, ' 100 + 200 = ' is a string rather than a mathematical formula, Python treats it as a string, please explain the above printing results yourself.

3 Notes

At any time, we can add comments to the program. Annotations are used to illustrate the code, to yourself or others, and when the program runs, the Python interpreter ignores comments directly, so there is no comment that doesn't affect the execution of the program, but it affects whether someone can read your code.

Python comments begin with #, followed by text until the end of the line is counted as a comment

In Python, the concept of variables is basically the same as the equation variables of the middle school algebra.

4 variables

For example, for equation y=x*x, x is the variable. When x=2, the result of the calculation is 4, when x=5, the result of the calculation is 25.

Just in a computer program, a variable can be not only a number, but also any data type.

In a python program, a variable is represented by a variable name, and the variable name must be a combination of uppercase and lowercase English, numeric, and underscore (_) and cannot start with a number, such as:

a1变量a‘T007‘变量t_007是一个字符串。

In Python, equals = is an assignment statement that can assign any data type to a variable, the same variable can be repeatedly assigned, and can be a variable of different types, for example:

a123    # a是整数aa‘imooc‘   # a变为字符串a

This type of variable itself is called Dynamic language, which corresponds to static language.

Static languages must specify the variable type when defining the variable, and if the type does not match, an error is given. For example, Java is a static language, and assignment statements are as follows (//for comments):

int a = 123; A is an integer type variable
A = "MOOC"; Error: Cannot assign string to integer variable
This is why dynamic languages are more flexible than static languages.

Do not equate an equal sign of an assignment statement with a mathematical equal sign. For example, the following code:

x = 10x = x + 2

If mathematically understood x = x + 2 That is not true anyway, in the program, the assignment statement first calculates the right expression X + 2, obtains the result 12, and assigns the variable x. Since the value before X is 10, the value of X becomes 12 after the value is re-assigned.

Finally, it is important to understand the representation of variables in computer memory. When we wrote: a = ' ABC ', the Python interpreter did two things:

    1. A string of ' ABC ' was created in memory;

    2. A variable named A is created in memory and points to ' ABC '.

You can also assign a variable A to another variable B, which actually points the variable B to the data that the variable a points to, such as the following code:

a‘ABC‘aa‘XYZ‘print b

Does the last line print out the contents of variable b exactly ' ABC ' or ' XYZ '? If you understand mathematically, you will mistakenly conclude that B and a are the same and should be ' XYZ ', but actually the value of B is ' ABC ', and let us execute the code in one line, and we can see exactly what happened:

Execute a = ' abc ', the interpreter creates the string ' abc ' and variable A, and points a to ' abc ':
Execute B = A, the interpreter creates the variable B and points B to the string ' ABC ' that points to a:
Execute a = ' xyz ', the interpreter creates the string ' xyz ' and changes the point of a to ' XYZ ', but B does not have a more
So, the result of printing variable B at last is ' ABC ' naturally.

6 raw strings with multiple lines of string

If a string contains many characters that need to be escaped, it can be cumbersome to escape each character. To avoid this, we can prefix the string with R, which means that it is a raw string, and that the characters inside it don't need to be escaped. For example:

r‘\(~_~)/ \(~_~)/‘

But R ' ... ' notation cannot represent multiple lines of string, nor can it represent a string containing ' and ' (Why?). )

If you want to represent multiple lines of string, you can use "' ..." to indicate:

‘‘‘Line 1Line 2Line 3‘‘‘

The above string is represented in exactly the same way as the following:

‘Line 1\nLine 2\nLine 3‘

You can also add R in front of a multiline string and turn the multiline string into a raw string:

r‘‘‘Python is created by "Guido".It is free and easy to learnLet‘s start learn Python in imooc!‘‘‘
7 Unicode string

The string also has an encoding problem.

Because a computer can only handle numbers, if you are working with text, you must convert the text to a number before processing it. The oldest computer was designed with 8 bits (bit) as a byte (byte), so the largest integer that a Word energy saver represents is 255 (binary 11111111 = decimal 255), and 0-255 is used to denote uppercase and lowercase letters, numbers, and some symbols. This Code table is called ASCII encoding, such as the code for capital A is 65, and the lowercase z is encoded as 122.

If you want to express Chinese, obviously a byte is not enough, need at least two bytes, and also can't and ASCII encoding conflict, so, China has developed GB2312 code, used to put Chinese into.

Similarly, other languages such as Japanese and Korean also have this problem. In order to unify all text encoding, Unicode came into being. Unicode unifies all languages into a set of encodings, so there is no more garbled problem.

Unicode usually uses two bytes to represent a character, the original English encoding from a single byte into a double-byte, only need to fill the high byte all 0 can be.

Because Python was born earlier than the Unicode standard, the earliest Python only supported ASCII encoding, and the normal string ' ABC ' was ASCII-encoded inside python.

Python later added support for Unicode, with a Unicode-represented string expressed in U ' ... ', for example:

print u‘中文‘

Chinese
Note: Without u, Chinese will not display properly.

Unicode strings are no different from normal strings except for one more u, and the escape character and multiline notation are still valid:

Escape:

u‘中文\n日文\n韩文‘多行:u‘‘‘第一行第二行‘‘‘raw+多行:ur‘‘‘Python的Unicode字符串支持"中文","日文","韩文"等多种语言‘‘‘

If the Chinese string encounters unicodedecodeerror in a Python environment, this is because there is a problem with the format saved by the. py file. You can add comments on the first line

# -*- coding: utf-8 -*-

The purpose is to tell the Python interpreter to read the source code with UTF-8 encoding. Then save with notepad++ as ... and select UTF-8 format to save.

8 list and tuple type 8.1 Create List

One of the data types built into Python is the list: lists. A list is an ordered set of elements that can be added and removed at any time.

For example, by listing the names of all the classmates in the class, you can use a list to indicate:

>>> [‘Michael‘, ‘Bob‘, ‘Tracy‘][‘Michael‘, ‘Bob‘, ‘Tracy‘]

A list is an ordered set of mathematical meanings, that is, the elements in the list are arranged in order.

Constructing the list is very simple, using the code above to enclose all elements of the list directly, which is a list object. In general, we assign a list to a variable so that we can refer to the list by a variable:

>>> classmates = [‘Michael‘, ‘Bob‘, ‘Tracy‘]>>> classmates # 打印classmates变量的内容[‘Michael‘, ‘Bob‘, ‘Tracy‘]

Because Python is a dynamic language, the elements contained in the list do not necessarily require the same data type, and we can include all kinds of data in the list:

>>> L = [‘Michael‘, 100, True]

A list that doesn't have an element is an empty list.

>>> empty_list = []
8.2 Accessing the list by index

Since list is an ordered set, we can use a list to indicate from high to low the 3 students in the class:

>>> L = [‘Adam‘, ‘Lisa‘, ‘Bart‘]

So how do we get the names of the nth-named students from the list? The method is to get the specified element in the list by index.

It is important to note that the index starts at 0, that is, the index of the first element is 0, the second element is indexed by 1, and so on.

Therefore, to print the first name of a classmate, use L[0]:

>>> print L[0]Adam

To print the name of the first two students, use L[1]:

>>> print L[1]Lisa

To print the name of the first three students, use L[2]:

>>> print L[2]Bart

To print the name of the first four students, use L[3]:

>>> print L[3]Traceback (most recent call last):  File "<stdin>", line 1, in <module>IndexError: list index out of range

The error! Indexerror means that the index is out of range because the list above has only 3 elements, and the valid index is 0,1,2.

Therefore, when using an index, be careful not to cross the border.

8.3 Reverse Access list

We still use a list to score from high to low to show 3 students in the class:

>>> L = [‘Adam‘, ‘Lisa‘, ‘Bart‘]

At this time, the teacher said, please score the lowest students stand out.

To write code to accomplish this task, we can count the list first and find that it contains 3 elements, so the index of the last element is 2:

>>> print L[2]Bart

Is there a simpler way?

Yes!

Bart classmate is the last, commonly known as the countdown first, so we can use the 1 index to represent the last element:

>>> print L[-1]Bart

Bart classmate says lying on the gun.

Similarly, the second-to-last use-2 means that the reciprocal third use-3 means that the penultimate fourth uses-4 means:

>>> print L[-2]Lisa>>> print L[-3]Adam>>> print L[-4]Traceback (most recent call last):  File "<stdin>", line 1, in <module>IndexError: list index out of range

L[-4] Error, because the penultimate fourth does not exist, there are only 3 elements.

When using a reverse index, also be careful not to cross the border.

8.4 Adding new elements

Now, there are 3 students in the class:

>>> L = [‘Adam‘, ‘Lisa‘, ‘Bart‘]

Today, the class transferred to a new classmate Paul, how to add new students to the existing list?

The first option is to append the new classmate to the end of the list by using the Append () method of the list:

>>> L = [‘Adam‘, ‘Lisa‘, ‘Bart‘]>>> L.append(‘Paul‘)>>> print L[‘Adam‘, ‘Lisa‘, ‘Bart‘, ‘Paul‘]

Append () always adds a new element to the tail of the list.

What if Paul says he is always on the test and asks to be added to the first place?

The method is to use the list's insert () method, which accepts two parameters, the first parameter is the index number, and the second parameter is the new element to be added:

>>> L = [‘Adam‘, ‘Lisa‘, ‘Bart‘]>>> L.insert(0, ‘Paul‘)>>> print L[‘Paul‘, ‘Adam‘, ‘Lisa‘, ‘Bart‘]

L.insert (0, ' Paul ') means that ' Paul ' will be added to the position of index 0 (i.e. the first one), while Adam, who originally indexed 0, and all the classmates behind it, automatically move backwards.

8.5 Deleting an element from the list

Paul's classmates had to turn away a few days ago, so how do we remove Paul from the existing list?

If Paul's classmates were in the last one, we could use the pop () method of list to delete:

>>> L = [‘Adam‘, ‘Lisa‘, ‘Bart‘, ‘Paul‘]>>> L.pop()‘Paul‘>>> print L[‘Adam‘, ‘Lisa‘, ‘Bart‘]

The pop () method always deletes the last element of the list, and it returns the element, so we print out ' Paul ' after we execute L.pop ().

What if Paul's classmates aren't the last one? For example, Paul is ranked third:

>>> L = [‘Adam‘, ‘Lisa‘, ‘Paul‘, ‘Bart‘]

To kick Paul out of the list, we have to locate Paul's position first. Since Paul's index is 2, the POP (2) is used to erase Paul:

>>> L.pop(2)‘Paul‘>>> print L[‘Adam‘, ‘Lisa‘, ‘Bart‘]
8.6 Replacing elements

Let's say the class is still 3 students:

>>> L = [‘Adam‘, ‘Lisa‘, ‘Bart‘]

Now, Bart's classmates are going to transfer, and happened to be a Paul classmate, to update the class membership list, we can first delete Bart, and then add Paul in.

Another way is to replace Bart with Paul directly:

>>> L[2] = ‘Paul‘>>> print LL = [‘Adam‘, ‘Lisa‘, ‘Paul‘]

To assign a value to an index in a list, you can replace the original element with the new element directly, and the list contains the same number of elements.

Since Bart can also index by-1, the following code can also do the same job:

>>> L[-1] = ‘Paul‘
8.7 Creating a tuple

Tuple is another ordered list, and Chinese is translated as "tuple". Tuple and list are very similar, however, once a tuple is created, it cannot be modified.

The same is the name of the class, expressed as a tuple as follows:

>>> t = (‘Adam‘, ‘Lisa‘, ‘Bart‘)

The only difference between creating a tuple and creating a list is to replace [] with ().

Now, this t cannot be changed, the tuple has no append () method, and there is no insert () and Pop () method. Therefore, the new classmate can not directly add to the tuple, old classmates want to quit a tuple also not.

The way to get a tuple element is exactly the same as the list, and we can access the element normally using indexed methods such as t[0],t[-1], but cannot be assigned to any other element, but it is not believed to try:

>>> t[0] = ‘Paul‘Traceback (most recent call last):  File "<stdin>", line 1, in <module>TypeError: ‘tuple‘ object does not support item assignment
8.8 Creating a cell element tuple

Tuple and list, can contain 0, one and any number of elements.

A tuple that contains multiple elements, which we have created earlier.

A tuple of 0 elements, which is an empty tuple, is represented directly by ():

>>> t = ()>>> print t()

What about creating a tuple with 1 elements? To try:

>>> t = (1)>>> print t1

It seems to be wrong! T is not a tuple, but an integer 1. Why is it?

Because () both can represent a tuple, and can be used as parentheses to indicate the priority of the operation, the result (1) is calculated by the Python interpreter result 1, resulting in we get not a tuple, but an integer 1.

It is precisely because the tuple with the () definition of a single element is ambiguous, so Python specifies that the element tuple should have a comma ",", which avoids ambiguity:

>>> t = (1,)>>> print t(1,)

Python also automatically adds a "," when printing cell tuples, in order to tell you more explicitly that this is a tuple.

The multivariate tuple plus does not add this extra "," effect is the same:

8.9 "Variable" tuple

We saw in the front that the tuple cannot be modified once it is created. Now, let's look at a "mutable" tuple:

>>> t = (‘a‘, ‘b‘, [‘A‘, ‘B‘])

Notice that T has 3 elements: ' A ', ' B ' and a list:[' a ', ' B '. List as a whole is the 3rd element of a tuple. The list object can be obtained by t[2]:

>>> L = t[2]

Then we change the list's two elements:

>>> L[0] = ‘X‘>>> L[1] = ‘Y‘

Then look at the contents of the tuple:

>>> print t(‘a‘, ‘b‘, [‘X‘, ‘Y‘])

Doesn't it mean that once a tuple is defined, it's immutable? What's the change now?

Don't worry, let's take a look at the definition when the tuple contains 3 elements:
When we modify the list's elements ' A ' and ' B ' to ' X ' and ' Y ', the tuple becomes:
On the surface, the elements of a tuple do change, but in fact it is not a tuple element, but a list element.

The list that the tuple initially points to is not changed to another list, so the so-called "invariant" of a tuple is that each element of a tuple is directed to never change. That point ' a ', it cannot be changed to point to ' B ', pointing to a list, cannot be changed to point to other objects, but the list itself is variable!

After understanding "point to invariant", how do you create a tuple that does not change the content? It is important to ensure that each element of a tuple cannot be changed.

Daydayup_python Self-study tutorial [1]_python Basics

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.