Python 3 Basic Data Types

Posted by nicx on Mon, 24 Jun 2019 02:00:22 +0200

I. Explanation

Variables in Python do not need to be declared. Every variable must be assigned before it is used, and the variable will be created after it is assigned.
In Python, a variable is a variable. It has no type. What we call "type" is the type of object in memory that a variable refers to.
The equal sign (=) is used to assign values to variables.
The left side of the equal sign (=) operator is a variable name, and the right side of the equal sign (=) operator is the value stored in the variable.

For example:

#!/usr/bin/python3
 
counter = 100          # Integer variables
miles   = 1000.0       # Float
name    = "runoob"     # Character string
a = b = c = 1          # Assignment of multiple variables at the same time
a,b,c=1,2,'hello'      # Specify multiple variables for multiple objects

II. Standard Data Types

There are six standard data types in Python 3:

Number
 String (String)
List (List)
Tuple (tuple)
Sets (Sets)
Dictionary

2.1 Number (Number)

Python 3 supports int, float, bool, complex (plural)
There is only one integer type int, expressed as a long integer, and there is no Long in Python 2.
The built-in type() function can be used to query the object type referred to by the variable.

>>> a,b,c,d=5,6.7,true,2+3j
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'true' is not defined
>>> a,b,c,d=5,6.7,True,2+3j
>>> print(type(a),type(b),type(c),type(d))
<class 'int'> <class 'float'> <class 'bool'> <class 'complex'>

Be careful:

1. Python can assign multiple variables at the same time, such as a, b = 1, 2.
2. A variable can be assigned to different types of objects.
3. The division (/) of values always returns a floating-point number (print (2/4) output of 0.5), using the // operator to obtain integers.
4. In hybrid computing, Python converts integers into floating-point numbers. 5. Boolean: Ture and False, 1 and 0
 6. Del statement can delete defined objects, such as del a,b

2.2 String (String)

Strings in Python are enclosed with single quotes (') or double quotes ("), and special characters are escaped with backslashes.
The grammatical format of string interception is as follows:

Variable [header subscript: tail subscript]

The index value starts with 0 and starts with -1.
The plus sign (+) is the connector of the string, and the asterisk (*) indicates the number of times the current string is copied.

Example:

#!/usr/bin/python3
# -*- coding:UTF-8 -*-

str='hello,world!'

print(str)                 # Output string
print(str[0:-1])           # Output all characters from the first to the penultimate
print(str[0])              # Output string first character
print(str[2:5])            # Output from the third to the fifth character
print(str[2:])             # Output all characters starting from the third
print(str * 2)             # Output string twice
print(str + 'Hello')        # Connection string

print('------------------------------')

print('hello\nworld')      # Use backslash ()+n to escape special characters
print(r'hello\nworld')     # Add an r before the string to indicate that the original string will not be escaped

results of enforcement

hello,world!                  
hello,world                  
h                  
llo
llo,world!
hello,world!hello,world!
hello,world!Hello

------------------------------

hello
world
hello\nworld

Be careful:

 1. Backslash can be used to escape, and r can keep backslash from escaping.
 2. Strings can be connected with + operators and repeated with * operators.
 3. There are two indexing methods for strings in Python, starting from left to right with 0 and from right to left with -1.
 4. Strings in Python cannot be changed.
 5. Python does not have a separate character type. A character is a string of length 1.
 

2.3 List (List)

List is the most frequently used data type in Python.
Lists can complete the data structure implementation of most collection classes.
The types of elements in a list can be different. It supports numbers, and strings can even contain lists (so-called nesting).
A list is a comma-separated list of elements written between square brackets [].
As with strings, lists can also be indexed and intercepted, and when the list is intercepted, a new list containing the required elements is returned.

The grammatical format of list interception is as follows:

Variable [header subscript: tail subscript]

The index value starts with 0 and starts with -1.
The plus sign (+) is the list join operator, and the asterisk (*) is a repeat operation.

Example:

#!/usr/bin/python3
# -*- coding:UTF-8 -*-

list=['hello',357,6.6,'world']
ttlist=[123,'new']

print(list)                # Output complete list
print(list[0])             # The first element of the output list
print(list[1:3])           # Output starts from the second to the third element
print(list[2:])            # Output all elements starting from the third
print(ttlist * 2)          # Output two lists
print(str + ttlist)        # Connection List

results of enforcement

['hello', 357, 6.6, 'world']
hello
[357, 6.6]
[6.6, 'world']
[123, 'new', 123, 'new']
['hello', 357, 6.6, 'world', 123, 'new']

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

>>> new=[1,2,3,4,5,'hi']       
>>> new
[1, 2, 3, 4, 5, 'hi']
>>> new[1]='hehe'           #Change the second element in the list new to hehe
>>> new
[1, 'hehe', 3, 4, 5, 'hi']
>>> new[2:4]=[8,10]         #Change the 3/4 element in the list new to 8,9
>>> new
[1, 'hehe', 8, 10, 5, 'hi'
>>> new[2:4]=[]            #Delete the third and fourth elements in the list new
>>> new
[1, 'hehe', 5, 'hi']
>>> new[2:3]=[]

Be careful:

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

2.4 Tuple (tuple)

 Tuples are similar to lists, except that elements of tuple s cannot be modified.
 Tuples are written in parentheses (), separated by commas between elements.
 Element types in tuples can also be different. 
 Tuples, like strings, can be indexed and subscript indexes start at 0 and - 1 at the end. It can also be intercepted.
 In fact, you can think of a string as a special tuple.   

Constructing tuples with 0 or 1 elements is special, so there are some additional grammatical rules:

tup1 = ()     # Empty tuple
tup2 = (20,)  # An element that needs to be followed by a comma

string, list, and tuple all belong to sequence.

Be careful:

1. Like strings, elements of tuples cannot be modified.
2. Tuples can also be indexed and sliced in the same way.
3. Attention should be paid to the construction of special grammatical rules for tuples containing 0 or 1 elements.
4. Tuples can also be spliced using the + operator.

2.5 Sets (Sets)

A set is a sequence of disorderly, non-repetitive elements.
The basic function is to test membership and delete duplicate elements.
You can use braces {} or set() functions to create collections. Note that creating an empty collection must use set() instead of {}, because {} is used to create an empty dictionary. 

Example:

#!/usr/bin/python3

student = {'Tom', 'Jim', 'Mary', 'Tom', 'Jack', 'Rose'}
print(student)  # Output set, duplicate elements are automatically removed

# Membership testing
if ('Rose' in student):
    print('Rose In a collection')
else:
    print('Rose Not in the collection')

# Set can perform set operations
a = set('abracadabra')
b = set('alacazam')

print(a)
print(b)
print(a - b)  # Difference sets of a and b
print(b - a)  # Difference sets of b and a
print(a | b)  # Union of a and b
print(a & b)  # Intersection of a and b
print(a ^ b)  # Elements that do not exist at the same time in a and b

Output results:

{'Jim', 'Mary', 'Rose', 'Tom', 'Jack'}
Rose In a collection
{'d', 'c', 'r', 'a', 'b'}
{'l', 'c', 'm', 'a', 'z'}
{'d', 'b', 'r'}
{'l', 'm', 'z'}
{'l', 'd', 'c', 'r', 'm', 'a', 'b', 'z'}
{'c', 'a'}
{'l', 'd', 'r', 'm', 'b', 'z'}

2.6 Dictionary

dictionary is another very useful built-in data type in Python.
A list is an ordered combination of objects, and a dictionary is an unordered collection of objects.
The difference between the two is that the elements in a dictionary are accessed by keys, not by offsets.
A dictionary is a mapping type marked by "{}", which is an unordered set of key: value pairs.
Keys must use immutable types.
In the same dictionary, keys must be unique. 

Example:

#!/usr/bin/python3

dict = {}
dict['one'] = "1 - hello,world"
dict[2] = "2 - Hey"

tinydict = {'name': 'lucy', 'code': 100, 'class': '5 Class 6'}

print(dict['one'])  # The output key is the value of'one'.
print(dict[2])  # Value of output key 2
print(tinydict)  # Output complete dictionary
print(tinydict.keys())  # Output all keys
print(tinydict.values())  # Output all values

Output results:

1 - hello,world
2 - Hey
{'name': 'lucy', 'code': 100, 'class': '5 Class 6'}
dict_keys(['name', 'code', 'class'])
dict_values(['lucy', 100, '5 Class 6'])

Built-in functions:

get returns None based on the value corresponding to the key value and does not report errors.

dic = {'k1':'v1','k2':'v2'}
v = dic.get('k1')
print(v)

clear clearance

dic = {'k1':'v1','k2':'v2'}
v = dic.clear()
print(dic)
copy Copies (shallow copies)
dic = {'k1':'v1','k2':'v2'}
v = dic.copy()
print(dic)

pop deletes and gets the corresponding value

dic = {'k1':'v1','k2':'v2'}
v = dic.pop('k1')
print(dic)
print(v)

popitem randomly deletes key-value pairs and obtains the deleted key values

dic = {'k1':'v1','k2':'v2'}
v = dic.popitem()
print(v)
print(dic)

setdefault increases, but does not operate if the key value exists

dic = {'k1':'v1','k2':'v2'}
dic.setdefault('k3','v3')
print(dic)

update batch increase or modification

dic = {'k1':'v1','k2':'v2'}
dic.update({'k3':'v3','k4':'v4'})
print(dic)

Be careful:

1. A dictionary is a mapping type whose elements are key-value pairs.
2. The keywords in a dictionary must be immutable and cannot be repeated.
3. Create an empty dictionary using {}.

III. Data Type Conversion

For data type conversion, you only need to use the data type as the function name.

The following built-in functions perform conversion between data types. These functions return a new object representing the value of the transformation.

function describe
int(x [,base]) Convert x to an integer
float(x) Converting x to a floating point number
complex(real [,imag]) Create a plural
str(x) Converting object x to string
repr(x) Converting object x to expression string
eval(str) Used to calculate a valid Python expression in a string and return an object
tuple(s) Convert sequence s to a tuple
list(s) Convert sequence s to a list
set(s) Converting to Variable Sets
dict(d) Create a dictionary. d must be a sequence tuple.
frozenset(s) Converting to an immutable set
chr(x) Converting an integer to a character
unichr(x) Converting an integer to a Unicode character
ord(x) Converting a character to its integer value
hex(x) Converting an integer to a hexadecimal string
oct(x) Converting an integer to an octal string

Topics: Python Asterisk