Python3 basic data type overview, python3 Data Type

Source: Internet
Author: User

Python3 basic data type overview, python3 Data Type

This article introduces the basic data types in Python3, which are required for beginners of Python. The specific content is as follows:

First,Variables in Python do not need to be declared. Each variable must be assigned a value before it can be used.. In Python, a variable is a variable and has no type. The "type" we call is the type of the object in memory referred to by the variable. Python 3 has six standard data types:

Numbers (number)

String (String)

List)

Tuple (tuples)

Sets)

Dictionaries (dictionary)

This article first introduces the definitions of these data types and their relationships and differences.

I. Numbers

Python 3 supports int, float, bool, and complex (plural ). Value assignment and computation are both intuitive, just like in most languages. The built-in type () function can be used to query the object type referred to by a variable.

>>> a, b, c, d = 20, 5.5, True, 4+3j>>> print(type(a), type(b), type(c), type(d))<class 'int'> <class 'float'> <class 'bool'> <class 'complex'>

Numeric operation:

>>> 5 + 4 # Addition 9 >>> 4.3-2 # subtraction 2.3 >>>> 3*7 # multiplication 21 >>> 2/4 # division, get a floating point number 0.5> 2 // 4 # Division, get an integer 0> 17% 3 # obtain the remainder 2> 2 ** 5 # multiply by 32

Key points:

1. Python can assign values to multiple variables at the same time, such as a, B = 1, 2.
2. A variable can point to different types of objects by assigning values.
3. Division (/) always returns a floating point number. To obtain an integer, use the // operator.
4. In hybrid computing, Pyhton converts an integer to a floating point number.

Ii. Strings

String 'str' in Python is enclosed by single quotation marks ('') or double quotation marks (" "), and special characters are escaped using a backslash.

>>> s = 'Yes,he doesn\'t'>>> print(s, type(s), len(s))Yes,he doesn't <class 'str'> 14

If you do not want to escape the backslash, you can add an r before the string to indicate the original string:

>>> print('C:\some\name')C:\someame>>> print(r'C:\some\name')C:\some\name

In addition, the backslash can be used as a line break to indicate that the next line is a continuation of the previous line. You can also use "..." "Or '''... ''' to span multiple rows.

Strings can be connected in series using the + operator, or the * operator is used to repeat:

>>> print('str'+'ing', 'my'*3)string mymymy

There are two indexing methods for strings in Python. The first is to increase from left to right and from 0. The second is to decrease from right to left and from-1. Note that there is no separate character type. A character is a string of 1.

>>> word = 'Python'>>> print(word[0], word[5])P n>>> print(word[-1], word[-6])n P

You can also slice strings to obtain a substring. Use a colon to separate two indexes, in the form of a variable [head Subscript: end subscript]. The Truncation range is preclosed and then open, and both indexes can be omitted:

>>> word = 'ilovepython'>>> word[1:5]'love'>>> word[:]'ilovepython'>>> word[5:]'python'>>> word[-10:-6]'love'

Different from the C string, the Python string cannot be changed. Assign a value to an index. For example, word [0] = 'M' may cause an error.

Key points:

1. The backslash can be used for escape, and r can be used to prevent the backslash from being escaped.
2. Strings can be connected together using the + operator, which is repeated using the * operator.
3. There are two indexing methods for strings in Python: 0 from left to right and-1 from right to left.
4. the strings in Python cannot be changed.

Iii. List

List is the most frequently used data type in Python. A list is a list of elements written between square brackets and separated by commas. The element types in the list can be different:

>>> a = ['him', 25, 100, 'her'] >>> print(a, type(a), len(a))['him', 25, 100, 'her'] <class 'list'> 4

Like a string, the list can also be indexed and sliced. After the list is sliced, a new list containing the required elements is returned. I will not go into details here.

The List also supports concatenation, using the + operator:

>>> a = [1, 2, 3, 4, 5]>>> a + [6, 7, 8][1, 2, 3, 4, 5, 6, 7, 8]

Unlike Python strings, the elements in the list can be changed:

>>> A = [1, 2, 3, 4, 5, 6] >>> a [0] = 9 >>> a [2: 5] = [13, 14, 15] >>> a [9, 2, 13, 14, 15, 6] >>>> a [2: 5] = [] # Delete >>> a [9, 2, 6]

List has many built-in methods, such as append () and pop (), which will be discussed later.

Key points:

1. List is written between square brackets, and elements are separated by commas.
2. Like strings, list can be indexed and sliced.
3. List can be spliced using the + operator.
4. The elements in the List can be changed.

Iv. Tuple

The tuple is similar to the list, except that the elements of the tuples cannot be modified. Tuples are a list of elements written between parentheses and separated by commas. The element types in the tuples can also be different:

>>> a = (1991, 2014, 'physics', 'math')>>> print(a, type(a), len(a))(1991, 2014, 'physics', 'math') <class 'tuple'> 4

The tuples are similar to strings. They can be indexed and the subscript index starts from 0, and can also be intercepted/sliced (as shown above, we will not repeat it here ). In fact, we can regard a string as a special tuples.

>>> Tup = (1, 2, 3, 4, 5, 6) >>> print (tup [0], tup []) 1 (2, 3, 4, 5) >>> tup [0] = 11 # the operation to modify the elements of the tuples is invalid.

Although the tuple element cannot be changed, it can contain variable objects, such as the list.
Constructing a tuple that contains 0 or 1 element is a special problem, so there are some additional syntax rules:

Tup1 = () # null tuples tup2 = (20,) # an element, which must be followed by a comma

In addition, tuples also support the + operator:

>>> tup1, tup2 = (1, 2, 3), (4, 5, 6)>>> print(tup1+tup2)(1, 2, 3, 4, 5, 6)

String, list, And tuple belong to sequence ).

Key points:

1. Like a string, the elements of the tuples cannot be modified.
2. tuples can also be indexed and sliced in the same way.
3. Note the special syntax rules for constructing tuples containing 0 or 1 element.
4. tuples can also be spliced using the + operator.

V. Sets

A set is a set of unordered and non-repeating elements. The basic function is to test the member relationship and eliminate repeated elements. You can use braces or the set () function to create a set. Note: To create an empty set, you must use set () instead of {}, because {} is used to create an empty dictionary.

>>> Student = {'Tom ', 'Jim', 'Mary ', 'Tom', 'Jack ', 'Rose'} >>> print (student) # repeated elements are automatically removed {'Jim ', 'jack', 'Mary', 'Tom ', 'Rose '}>>> 'Rose' in student # membership testing (member test) True >># set can perform set operations... >>> a = set ('abracadaba') >>> B = set ('acazam') >>> a {'A', 'B', 'C', 'D ', 'R' }>>> a-B # difference set between a and B {'B', 'D ', 'R' }>>> a | B # The Union of a and B {'l', 'M', 'A', 'B', 'C ', 'D', 'z', 'R'} >>> intersection of a & B # a and B {'A ', 'C' }>>> a ^ B # elements that do not exist simultaneously in a and B {'l', 'M', 'B', 'D ', 'Z', 'R '}

Key points:

1. The elements in the set are not repeated. If they are repeated, they are automatically removed.
2. The set can be created using braces or the set () function, but the empty set must be created using the set () function.
3. The set can be used to test members and eliminate repeated elements.

6. Dictionaries

A dictionary is another useful built-in data type in Python. A dictionary is a mapping type, which is an unordered key: a set of value pairs. The keyword must use an unchangeable type, that is, the list and tuple containing a variable type cannot be used as a keyword. In the same dictionary, the keywords must also be different.

>>> Dic ={}# create an empty dictionary >>> tel = {'jack': 1557, 'Tom ': 1320, 'Rose ': 1886 >>>> tel {'Tom ': 1320, 'jack': 1557, 'Rose': 1886 }>>> tel ['jack'] # main operations: query 1557 by key> del tel ['Rose '] # delete a key-Value Pair> tel ['Mary'] = 4127 # Add a key-Value Pair> tel {'Tom ': 1320, 'jack': 1557, 'Mary ': 4127 }>>> list (tel. keys () # returns the list ['Tom ', 'jack', 'Mary']> sorted (tel. keys () # sort by key ['jack', 'Mary ', 'Tom '] >>> 'Tom' in tel # member test True >>> 'Mary 'not in tel # member test False

The constructor dict () directly constructs a dictionary from the key-value pair sequence, which can also be deduced as follows:

>>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)]){'jack': 4098, 'sape': 4139, 'guido': 4127}>>> {x: x**2 for x in (2, 4, 6)}{2: 4, 4: 16, 6: 36}>>> dict(sape=4139, guido=4127, jack=4098){'jack': 4098, 'sape': 4139, 'guido': 4127}

In addition, the dictionary type also has some built-in functions, such as clear (), keys (), and values.

Key points:

1. a dictionary is a ing type. Its elements are key-value pairs.
2. The dictionary keywords must be of an unchangeable type and cannot be repeated.
3. Create an empty dictionary {}.


Python3 is recommended for beginners.

Head First Programming
Head First Python
These two books are very easy to get started with python3, but the books in the Head First series are very beginner, so you must read other books to improve. If you do not want to buy books, these two books are available in electronic versions below on the Internet. You can search for other books that cover 3.x in the online bookstore for your reference.

I just learned Python and used Python30. I recommend a book for beginners.

The release of python3.0 is not long before. We recommend that you use more than 2.7, with less information and less answers to problems.
First look at the python simple tutorial, and then look at the python core programming.
After learning, you can easily develop a crawler tool. If you want to research the web, you can study django, which will make you excited!

This is my learning path.

I have always been helpful!

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.