Overview of basic data types for Python3 Foundation _python

Source: Internet
Author: User
Tags set set

This article introduces the basic data types in Python3, which are necessary knowledge for the beginning of Python, as follows:

First, thevariables in Python do not need to be declared. Each variable must be assigned before it is used, and the variable will not be created until it is assigned a value . In Python, a variable is a variable, it has no type, and what we call "type" is the type of the object in memory that the variable refers to. There are six standard data types in Python 3:

Numbers (digital)

String (strings)

List (listing)

Tuple (META Group)

Sets (Collection)

Dictionaries (dictionary)

This paper first introduces the definitions of these data types and their relations and differences.

First, Numbers

Python 3 supports int, float, bool, complex (plural). The assignment and calculation of numeric types are intuitive, just like most languages. The built-in type () function can be used to query the object type that the variable refers to.

>>> A, B, c, d = 5.5, True, 4+3j
>>> print (Type (a), type (b), type (c), type (d))
<class ' in T ' > <class ' float ' > <class ' bool ' > <class ' Complex ' >

Numeric operations:

>>> 5 + 4 # addition
9
>>> 4.3-2 # subtraction
2.3
>>> 3 * 7 # multiplication
>>> 2 /4 # Division, get a floating-point number
0.5
>>> 2//4 # Division, get an integer
0
>>> 17% 3 # take more than 
2
>>> 2 * * 5 #
32

Points:

1. Python can assign values to multiple variables, such as a, B = 1, 2.
2. A variable can point to different types of objects by assigning values.
3, the Numerical division (/) always returns a floating-point number, to get the integer use//operator.
4, in the mixed calculation, Pyhton will transform the integer into a floating-point number.

Second, Strings

String str in Python is enclosed in single quotes ("") or double quotes (""), while using backslashes (\) to escape special characters.

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

If you do not want the backslash to escape, you can add an R in front of the string that represents the original string:

>>> print (' C:\some\name ')
C:\some
ame
>>> print (R ' C:\some\name ')
C:\some\ Name

In addition, a backslash can be used as a continuation line, indicating that the next row is the extension of the previous line. You can also use "" "" or "" "" or "..." to cross multiple lines.

Strings can be concatenated with the + operator string, or repeat with the * operator:

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

Strings in Python are indexed in two ways, the first from left to right, from 0 to one, and the second from right to left, and from-1 to lower. Note that there is no single character type, and one character is a string of length 1.

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

You can also slice the strings to get a string. Separate two indexes with a colon, in the form of a variable [header subscript: tail subscript]. The scope of the interception is open after the front closure, and two indexes can be omitted:

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

Unlike the C string, the Python string cannot be changed . Assigning values to an index position, such as word[0] = ' m ' can result in an error.

Points:

1, the backslash can be used to escape, using R allows the backslash to not be escaped.
2. Strings can be joined together with the + operator, repeated with the * operator.
3. Strings in Python are indexed in two ways, starting from left to right with 0, starting from right to left with-1.
4, the string in Python can not be changed.

Third, List

The list is the most frequently used data type in Python. The list is a comma-delimited list of elements that are written between square brackets. The types of elements in a list can be different:

>>> a = [' him ', MB, ' her '] 
>>> print (A, type (a), Len (a))
[' him ', MB, ' her '] <class ' List ' > 4

As with strings, lists can also be indexed and sliced, and the list is sliced to return a new list containing the required elements. Detailed here will not repeat.

The list also supports inline operations, using the + operator:

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

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

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

The list is built in a number of ways, such as append (), Pop (), and so on, which will be mentioned later.

Points:

1. The list is written between square brackets and the elements are separated by commas.
2, as with strings, the list can be indexed and sliced.
3, list can use the + operator for stitching.
4, the elements in the list can be changed.

Four, Tuple

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

>>> a = (1991, 2014, ' physics ', ' math ')
>>> print (A, type (a), Len (a))
(1991, 2014, ' Physics ', ' Math ') <class ' tuple ' > 4

Tuples are similar to strings, can be indexed and the subscript index starts at 0 or can be intercepted/sliced (see above, no longer repeat here). In fact, you can think of a string as a special tuple.

>>> Tup = (1, 2, 3, 4, 5, 6)
>>> print (tup[0], Tup[1:5])
1 (2, 3, 4, 5)
>>> tup[0] = 11 # The operation of modifying tuple elements is illegal

Although tuple elements cannot be changed, they can contain mutable objects, such as list lists.
Constructing a tuple that contains 0 or 1 elements is a special problem, so there are some additional syntax rules:

Tup1 = () # empty tuple
tup2 = (20,) # An element that needs to add a comma after the element

In addition, the tuple also supports the use of the + operator:

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

String, list, and tuple all belong to the sequence (sequence).

Points:

1, as with strings, the elements of a tuple cannot be modified.
2, the tuple can also be indexed and sliced, the same method.
3. Note the special syntax rules for constructing tuples that contain 0 or 1 elements.
4, the tuple can also use the + operator for stitching.

Five, Sets

A collection (set) is a set of unordered, distinct elements. The basic function is to conduct member relationship testing and eliminate duplicate elements. You can use curly braces or set () functions to create set collections, note: Creating an empty collection must be 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 (' Abracadabra ')
>>> b = Set (' Alacazam ')
>>> a
{' A ', ' B ', ' C ', ' d ', ' R ' ' {'}
>>> a-b   # A and B's set of difference
{' B ', ' d ', ' r '}
>>> a | b   # A and B ' and ' l ',
' m ', ' a ', ' B ', ' C ', ' d ', ' Z ', ' r '}
>>> A & B   # A and B's intersection
{' A ', ' C '}
>>> a ^ b   # A and b do not exist at the same time Elements
{' L ', ' m ', ' B ', ' d ', ' Z ', ' r '}

Points:

1, the set set of elements do not repeat, repeat it will automatically remove.
2. Set collections can be created with curly braces or set () functions, but empty collections must be created using the set () function.
3, set set can be used for member testing, eliminating duplicate elements.

VI. Dictionaries

The Dictionary (dictionary) is another very useful built-in data type in Python. A dictionary is a mapping type (mapping type), which is a unordered key: a collection of value pairs. Keywords must use immutable types, that is, list and tuple that contain mutable types cannot be keywords. In the same dictionary, keywords must also be different.

>>> dic = {} # Create empty dictionary
>>> tel = {' Jack ': 1557, ' Tom ': 1320, ' Rose ': 1886}
>>> Tel
{' To M ': 1320, ' Jack ': 1557, ' Rose ': 1886}
>>> tel[' Jack ']  # main operation: Query via key
1557
>>> 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 all Key's 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 () constructs the dictionary directly from the key value pair of sequence, and of course it can 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, there are built-in functions for dictionary types, such as clear (), keys (), values (), and so on.

Points:

1, the dictionary is a mapping type, its elements are key-value pairs.
2, the dictionary keyword must be immutable type, and can not be repeated.
3, create an empty dictionary using {}.

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.