Python Learning Notes---variables and data types

Source: Internet
Author: User

Variables in Python and built-in data types


This article is only I in MU class net study "the beginning of Python" This course, extracts, the collation of some of the more important grammar and hints. More than 90% of the content, as well as all code examples, are excerpt from the Web. Because I have a certain C/+ + language Foundation, and this article is mainly for me to review the use, so I prefer to extract some of the differences between Python and C + +, may cause this article semantically not necessarily coherent, suggesting that learning needs of readers directly to the network to learn the course (Link:/http www.imooc.com/learn/177) or view a Python tutorial from the official website of Mr. Liaoche, the instructor of this course (link: http://www.liaoxuefeng.com/wiki/ 001374738125095c955c1e6d8bb493182103fac9270762a000)


1. Variables

Variable name composition: English alphabet, Arabic numerals, underline, where the Arabic numerals can not be used as the beginning "and C!" 】

The same variable can be repeatedly assigned, and can be different types of variables, the variable itself type of non-fixed language called Dynamic language "and corresponding to the static language (C, Java, etc.), in the definition of variables must be specified variable type, if the assignment when the type does not match, will error". For example:

A = 123       # A is an integer print AA = ' Imooc '   # A becomes a string print a


2. String type

Strings can be expressed in single or double quotation marks. The string itself contains single quotation marks, which can be enclosed in double quotation marks (example 1); The string itself contains double quotation marks, which can be enclosed in single quotation marks (example 2); The string itself contains both single and double quotation marks, and must be escaped (example 3). The python string is escaped with \, and the escape character \ is not counted into the contents of the string.

Precede the string with the R prefix , you can flag a raw string (example 4). The characters inside the raw string do not have to be escaped, and are suitable for situations where the escape character is too large and contains no single double quotes.

Usethree single quotesCan putmulti-line string(Example 5).

You can flag a Unicode string (example 6) by prefixing the string with the u prefix . Unicode literals are used internally with Unicode encoding, and are suitable for handling non-ASCII characters such as Chinese. A Unicode string is no different than a normal string, except for one more u, and the escape character and multiline notation are still valid (example 7).

Raw strings, multiline strings, and Unicode strings are concepts of different dimensions that can be cross-used (example 8).

# example 1. The string itself contains single quotes and can be enclosed in double quotation marks to denote the print "I m OK" # example 2. The string itself contains double quotes, which can be enclosed in single quotes to denote print ' learn "Python" in Imooc ' # Example 3. The string itself contains both single and double quotes, and the print ' Bob said \ ' I\ ' m ok\ must be escaped with a backslash. # example 4. Use the R prefix to flag a raw string print R ' \ (~_~)/\ (~_~)/' # example 5. Enclose a multiline string in three single quotes print ' Python is created by guido.it are free and easy to Learn. " # equivalent to print ' Python are created by Guido.\nit are free and easy to learn. ' # example 6. Mark a Unicode string with u prefix print u ' Chinese ' # example 7. Escape, Unicode, multiple lines simultaneously apply print U ' chinese \ n \ korean ' # example 8.raw, Unicode, multiple lines simultaneously apply print ur ' Python's Unicode string supports "Chinese", "Japanese", "Korean" and many other languages "

If the Chinese string encounters unicodedecodeerror in a Python environment, this is because the. py file has a problem with the format saved. 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 the UTF-8 encoding. Then save as ... and select UTF-8 format to save.


3. Boolean type

In Python, Boolean types have only true and false two values, and 0, empty string ', and none are treated as false, and other numeric and non-empty strings are considered True.

Boolean types can also do and, or, and not with other data types, but the result of the operation may not be a Boolean type (Example 1). For example:

# example 1 Boolean type with other data types do a logical operation, the result is not a Boolean type a = Trueprint A and ' a=t ' or ' a=f ' # Print the result is: a=t
This is because the and and or operations in Python have an important law---Short Circuit Calculation:

    • 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.
    • 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, in the above example, True and ' a=t ' evaluates to ' a=t ', and continues to calculate ' a=t ' or ' a=f ' results or ' a=t '. "Short-circuit calculation is not uncommon, C + + actually, except that C + + will first turn non-Boolean type into a Boolean type and then perform the operation, so the logical operation result must be Boolean type"


4. List Type 4.1 lists

List, which is an ordered listing. Unlike other languages, in Python, it is a built -in data type. List is an ordered set in mathematical sense.

Constructing the list is very simple, enclosing all the elements of the list directly in square brackets [] , which is a list object (example 1); Usually, we assign a list to a variable so that you can refer to the list by a variable, and a list that doesn't have an element. is an empty list (example 2). "Pretty much like a vector in C + + STL."

Because Python is a dynamic language, the elements contained in the list are not required to be of the same data type, and we can include a variety of different types of data in the list (example 3). "The difference between this and vector is great."

You can 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 index of the second element is 1, and so on (example 4). When using an index, be careful not to cross the border. "To some extent, an index can be likened to an array subscript in C."

Oddly enough, in Python you can also access the specified element in the list in reverse ORDER BY index! The index uses a - number to indicate that it is in reverse order, for example, we can use the index of the 1 to represent the last element, similar to the penultimate 2, the penultimate use-3 means ... And so on (example 4).

List has two ways to add new elements, where: theappend () method always adds new elements to the end of the list; theinsert () method accepts two parameters, the first parameter is the index number NUM, and the second parameter is the new element to be added. After inserting a new element using the Insert () method, the list has the original index number of NUM and num after the element, and then move one after another . (Example 5)

The list uses the pop () method to delete the specified element, which can be omitted, by default deleting the element at the end of the list, or by receiving an index number num, which deletes the element with List index 0. the deleted element is automatically printed after each call to the Pop () method. (Example 6)

Replaces the specified element in the list by directly accessing and assigning a new value using an index (in reverse order). (Example 7)

# example 1 uses [] to enclose the element is Listl = [' Michael ', ' Bob ', ' Tracy ']# case 2 element data type is not exactly the same as Listmix_list = [' Adam ', 95.5, ' Lisa ', ', ' Bart ', 59]# Example 3 null listempty_list = []# Example 4 gets the specified element in the list with an index print l[0]   # access the first element with a positive-order index print l[-3]  # access the first element with an inverse index (3rd to last Element) # example 5 adding a new element L.append (' Tom ')      # adds Tom to the end of the list shown in Example 1, print L  # shows: [' Michael ', ' Bob ', ' Tracy ', ' Tom ']l.insert (0, ' Alice ') # Add Alice to the list in Example 1, where index 0 is shown in the print L  # display: [' Alice ', ' Michael ', ' Bob ', ' Tracy ', ' Tom ']# example 6 delete element L.pop ()      # no argument, By default, the element at the end of the list is deleted, showing: ' Tom ' Print L  # shows: [' Alice ', ' Michael ', ' Bob ', ' Tracy ']l.pop (0)     # parameter is indexed, the element with list index 0 is deleted, Display: ' Alice ' print L  # shows: [' Michael ', ' Bob ', ' Tracy ']# example 6 replacement element l[0]  = ' Alice ' l[-1] = ' Tom ' Print L
4.2 Tuple

Tuple is also an ordered list type, generally translated as " tuple ". Unlike list, a tuple cannot be modified once it has been created. Therefore, the tuple does not have append, insert, pop and other methods, and can not be re-assigned by index.

Unlike list, creating a tuple requires enclosing all elements in parentheses () rather than square brackets [] (example 1). Because parentheses can also represent the precedence of an operation, you must add a comma behind the element when you create the cell tuple (example 2)!

In addition to the above, the use of tuple and list is similar. (Example 3-5)

The so-called "invariant" of a tuple is that each element of a tuple, pointing to never change. That point to ' a ', it cannot be changed to point to ' B '; If you point to a list, you cannot change to point to another object. However, the list itself is mutable (example 3)! Therefore, to create a tuple with the same content, you must ensure that each element of the tuple itself cannot be changed.

# example 1 uses () to enclose the element is Tuplet = (' Michael ', ' Bob ', ' Tracy ') # example 2 Create cell tuplesingle_tuple = (' Bob ',) Single_tuple = (10,) # example 3 element data type not Exactly the same tuplemix_tuple = (' Adam ', 95.5, ' Lisa ', ', ' Bart ', 59) # example 4 empty tupleempty_tuple = () # example 5 gets the specified element in a tuple by index print t[0]
   
    # access to the first element with a positive ordinal index print t[-3]  # access to the first element with an inverse index (3rd to last Element) # example 6 "variable" Tuplet = (' A ', ' B ', [' A ', ' B ']) L = t[2]l[0] = ' X ' l[1] = ' Y ' Print T    #显示: (' A ', ' B ', [' X ', ' Y '])
   


5. To be Continued





Python Learning Notes---variables and data types

Related Article

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.