Python3 Basic Data Types


Variables in Python do not need to be declared. Each variable must be assigned a value before it is used, and the variable will be created after the variable is assigned.

In Python, a variable is a variable. It has no type. What we call "type" is the type of the object in the memory that the 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. E.g:

Example (Python 3+)

#!/usr/bin/python3

counter = 100 # Integer variable
miles = 1000.0 # Floating point variable
name = "TutorialFish.com" # string

print (counter)
print (miles)
print (name)


Executing the above program will output the following results:

100 
1000.0 
TutorialFish.com

Multiple Variable Assignment

Python allows you to assign values to multiple variables at the same time. E.g:

a = b = c = 1

The above example creates an integer object with a value of 1, assigning values from back to front, and three variables are assigned the same value.

You can also specify multiple variables for multiple objects. E.g:

a , b , c = 1 , 2 , "TutorialFish.com"

In the above example, two integer objects 1 and 2 are assigned to variables a and b, and the string object "TutorialFish.com" is assigned to variable c.


Standard Data Type

There are six standard data types in Python3:

  • Number

  • String

  • List

  • Tuple

  • Set

  • Dictionary

Among the six standard data types of Python3:

  • Immutable data (3): Number, String, Tuple

  • Variable data (3): List, Dictionary, Set


Number

Python3 supports int, float, bool, complex (plural) .

In Python 3, there is only one integer type int, which is represented as a long integer, and there is no Long as python2.

Like most languages, the assignment and calculation of numeric types are very intuitive.

The built-in type() function can be used to query the object type pointed to by the 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'>

In addition, you can isinstance() to judge:

Example

>>> a = 111
>>> isinstance(a, int)
True
>>>


The difference between isinstance and type is:

  • type() will not consider the subclass to be a superclass type.

  • isinstance() will consider the subclass to be a superclass type.

>>> class A:
... pass
...
>>> class B(A):
... pass
...
>>> isinstance(A(), A)
True
>>> type(A()) == A
True
>>> isinstance(B(), A)
True
>>> type(B()) == A
False

Note: In Python3, bool is a subclass of int, True and False can be added to numbers, True==1, False==0 will return True , but the type can be judged by is .

>>> issubclass(bool, int)
True
>>> True==1
True
>>> False==0
True
>>> True+1
2
>>> False+1
1
>>> 1 is True
False
>>> 0 is False
False

There is no Boolean type in Python2. It uses the number 0 to represent False and 1 to represent True.

When you specify a value, the Number object is created:

var1 = 1 
var2 = 10

You can also use the del statement to delete some object references.

The syntax of the del statement is:

del var1[,var2[,var3[....,varN]]]

You can delete single or multiple objects by using the del statement. E.g:

del var 
del var_a , var_b

Numerical Operations

Example

>>> 5 + 4 # addition
9
>>> 4.3-2 # Subtraction
2.3
>>> 3 * 7 # multiplication
twenty one
>>> 2/4 # Division, get a floating point number
0.5
>>> 2 // 4 # Division to get an integer
0
>>> 17% 3 # Take the remainder
2
>>> 2 ** 5 # factor
32

Notice:

  • 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 assignment.

  • 3. Numerical division contains two operators: / returns a floating point number, // returns an integer.

  • 4. In mixed calculations, Python will convert integers into floating-point numbers.

Examples of Numeric Types

intfloatcomplex
100.03.14j
10015.2045.j
-786-21.99.322e-36j
08032.3e+18.876j
-0490-90.-.6545+0J
-0x260-32.54e1003e+26J
0x6970.2E-124.53e-7j

Python also supports complex numbers. Complex numbers are composed of real and imaginary parts, which can be represented by a + bj, or complex(a, b). The a and b of the complex number are both floating-point types.


String

Python in single quotes ' or double quotes " quotes, while the backslash \ escape special characters.

The grammatical format of string interception is as follows:

variable [head index:tail idnex]

The index value starts with 0, and -1 is the starting position from the end.

image.png

The plus sign + is the concatenation of the character strings, and the asterisk * means to copy the current character string, and the number combined with it is the number of times of copying. Examples are as follows:

Example

#!/usr/bin/python3

str ='Try It'

print (str) # output string
print (str[0:-1]) # Print all characters from the first to the second to last
print (str[0]) # Output the first character of the string
print (str[2:5]) # print the characters starting from the third to the fifth
print (str[2:]) # output all characters starting from the third
print (str * 2) # Output the string twice, or it can be written as print (2 * str)
print (str + "TEST") # connection string

Executing the above program will output the following results:

Try It
Try I
T
y I
y It
Try ItTry It
Try ItTEST

Python uses backslash \to escape special characters. If you don't want the backslash to be escaped, you can add an r in front of the string to indicate the original string:

Example

>>> print('Tr\ny It')
Tr
y It
>>> print(r'Tr\ny It')
Tr\ny It
>>>

In addition, the backslash (\) can be used as a line continuation character, indicating that the next line is a continuation of the previous line. You can also use """...""" or '''...''' to span multiple lines.

Note that Python does not have a separate character type, a character is a string of length 1.

Example

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

Unlike C strings, Python strings cannot be changed. Assigning a value to an index position, such as word[0] ='m' will cause an error.

Notice:

  • 1. The backslash can be used to escape, and the use of r can make the backslash not escape.

  • 2. Strings can be connected together with the + operator and repeated with the * operator.

  • 3. There are two indexing methods for strings in Python, starting with 0 from left to right, and starting with -1 from right to left.

  • 4. Strings in Python cannot be changed (immutable).


List

List is the most frequently used data type in Python.

The list can complete most of the data structure implementation of the collection class. The types of the elements in the list can be different, it supports numbers, strings and even lists (so-called nesting).

The list is a comma-separated list of elements written between square brackets [ ] .

Like strings, lists can also be indexed and intercepted. After the list is intercepted, a new list containing the required elements is returned.

The syntax format of list interception is as follows:

variable [head index: tail index]

The index value starts with 0 , and -1 is the starting position from the end.

image.png

The plus sign + is the list concatenation operator, and the asterisk * is the repeated operation. Examples are as follows:

Example

#!/usr/bin/python3

list = ['abcd', 786, 2.23,'Try It', 70.2]
tinylist = [123,'Try It']

print (list) # print the complete list
print (list[0]) # print the first element of the list
print (list[1:3]) # Start output from the second to the third element
print (list[2:]) # print all elements starting from the third element
print (tinylist * 2) # print the list twice
print (list + tinylist) # connection list

The output of the above example:

['abcd', 786, 2.23,'Try It', 70.2]
abcd
[786, 2.23]
[2.23,'Try It', 70.2]
[123,'Try It', 123,'Try It']
['abcd', 786, 2.23,'Try It', 70.2, 123,'Try It']

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

Example

>>> 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] = [] # Set the corresponding element value to []
>>> a
[9, 2, 6]

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

Notice:

  • 1. List is written between square brackets, and the elements are separated by commas.

  • 2. Like strings, lists can be indexed and sliced.

  • 3. List can be spliced using + operator.

  • 4. The elements in the List can be changed.

Python list interception can receive the third parameter. The parameter is used to intercept the step size. The following example intercepts the string at the position of index 1 to index 4 and set the step size to 2 (one position apart):

image.png

The result is: 'r' ' '.

If the third parameter is a negative number to indicate reverse reading, the following example is used to reverse the string:

Example


def reverseWords(input):
     
     # Separate the strings by spaces, and separate each word into a list
     inputWords = input.split(" ")
 
     # Reverse string
     # Assuming list list = [1,2,3,4],
     # list[0]=1, list[1]=2, and -1 means the last element list[-1]=4 (same as list[3]=4)
     # inputWords[-1::-1] has three parameters
     # The first parameter -1 means the last element
     # The second parameter is empty, which means to move to the end of the list
     # The third parameter is the step size, -1 means reverse
     inputWords=inputWords[-1::-1]
 
     # Recombine strings
     output = ''.join(inputWords)
     
     return output
 
if __name__ == "__main__":
     input ='I like tutorialfish'
     rw = reverseWords(input)
     print(rw)

The output is:

tutorialfish like I

Tuple

A tuple is similar to a list, except that the elements of a tuple cannot be modified. Tuples are written in parentheses ( ) , and the elements are separated by commas.

The element types in the tuple can also be different:

Example

#!/usr/bin/python3

tuple = ('abcd', 786, 2.23,'tutorialfish', 70.2)
tinytuple = (123,'tutorialfish')

print (tuple) # output complete tuple
print (tuple[0]) # output the first element of the tuple
print (tuple[1:3]) # output from the second element to the third element
print (tuple[2:]) # print all elements starting from the third element
print (tinytuple * 2) # output tuples twice
print (tuple + tinytuple) # connect tuples

The output of the above example:

('abcd', 786, 2.23, 'tutorialfish', 70.2)
abcd
(786, 2.23)
(2.23, 'tutorialfish', 70.2)
(123, 'tutorialfish', 123, 'tutorialfish')
('abcd', 786, 2.23, 'tutorialfish', 70.2, 123, 'tutorialfish')

Tuples are similar to strings, they can be indexed and the subscript index starts from 0, and -1 is the position from the end. It can also be intercepted (see above for more details).

In fact, you can think of strings as a special kind of tuples.

Example


>>> tup = (1, 2, 3, 4, 5, 6)
>>> print(tup[0])
1
>>> print(tup[1:5])
(2, 3, 4, 5)
>>> tup[0] = 11 # The operation of modifying tuple elements is illegal
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
TypeError:'tuple' object does not support item assignment
>>>

Although the elements of a tuple cannot be changed, it can contain mutable objects, such as lists.

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

tup1 = () # empty tuple
tup2 = (20,) # An element, you need to add a comma after the element

String, list and tuple all belong to sequence.

Notice:

  • 1. Like strings, the elements of tuples cannot be modified.

  • 2. Tuples can also be indexed and sliced in the same way.

  • 3. Pay attention to the special grammatical rules for constructing tuples containing 0 or 1 elements.

  • 4. Tuples can also be concatenated using the + operator.


Set

A set is composed of one or several wholes of different sizes. The things or objects that make up the set are called elements or members.

The basic function is to test membership and delete duplicate elements.

You can use braces { } or set() to create a collection. Note: To create an empty collection, you must use set() instead of { } , because { } is used to create an empty dictionary.

Creating format:

parame = {value01,value02,...}
OR
set(value)

Example

#!/usr/bin/python3

sites = {'Google','Bing','TutorialFish','Facebook','Twitter','Eay'}

print(sites) # output collection, duplicate elements are automatically removed

# Member test
if 'TutorialFish' in sites:
     print('TutorialFish in the collection')
else:
     print('TutorialFish is not in the collection')
     
# set can perform set operations
a = set('kfskjhuguyljsf')
b = set('krnoifkjbwestyy')

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

The output of the above example:

{'Google', 'Bing', 'Eay', 'TutorialFish', 'Twitter', 'Facebook'}

TutorialFish in the collection

{'u', 'f', 'y', 'j', 'g', 's', 'h', 'k', 'l'}
{'u', 'g', 'l', 'h'}
{'u', 'b', 'y', 'g', 'n', 's', 'h', 'l', 'r', 'o', 't', 'f', 'j', 'i', 'k', 'e', 'w'}
{'f', 'y', 'j', 's', 'k'}
{'u', 'b', 'g', 'i', 'n', 'r', 'l', 'h', 'o', 'e', 'w', 't'}

Dictionary

Dictionary is another very useful built-in data type in Python.

A list is an ordered collection of objects, and a dictionary is an unordered collection of objects. The difference between the two is that the elements in the dictionary are accessed through keys, not by offsets.

A dictionary mapping type, with dictionaries { } identifier, which is an unordered key:value set.

The key must use an immutable type.

In the same dictionary, the key must be unique.

Example

#!/usr/bin/python3
dict = {}
dict['one'] = "1-Mr.Fish"
dict[2] = "2-Jake C"
tinydict = {'name':'tutorialfish','code':1,'site':'www.tutorialfish.com'}
print (dict['one']) # Output the value of the key as'one'
print (dict[2]) # output the value of key 2
print (tinydict) # output complete dictionary
print (tinydict.keys()) # output all keys
print (tinydict.values()) # output all values

The output of the above example:

1-Mr.Fish
2-Jake C
{'name': 'tutorialfish', 'code': 1, 'site': 'www.tutorialfish.com'}
dict_keys(['name', 'code', 'site'])
dict_values(['tutorialfish', 1, 'www.tutorialfish.com'])

The constructor dict() can directly construct a dictionary from the sequence of key-value pairs as follows:

Example


>>> dict([('tutorialfish', 1), ('Google', 2), ('Bing', 3)])
{'tutorialfish': 1,'Google': 2,'Bing': 3}
>>> {x: x**2 for x in (2, 4, 6)}
{2: 4, 4: 16, 6: 36}
>>> dict(tutorialfish=1, Google=2, Bing=3)
{'tutorialfish': 1,'Google': 2,'Taobao': 3}
>>>

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

Notice:

  • 1. A dictionary is a mapping type, and its elements are key-value pairs.

  • 2. The keywords of the dictionary must be immutable and cannot be repeated.

  • 3. Use { } to create an empty dictionary .


Python Data Type Conversions

Sometimes, we need to convert the built-in type of the data. For the conversion of the data type, you only need to use the data type as the function name.

The following built-in functions can perform conversion between data types. These functions return a new object that represents the converted value.

FunctionDescription

int(x [,base])

Convert x to an integer

float(x)

Convert x to a floating point number

complex(real [,imag])

Create a plural

str(x)

Convert object x to string

repr(x)

Convert object x to expression string

eval(str)

Used to calculate valid Python expressions in a string and return an object

tuple(s)

Convert the sequence s into a tuple

list(s)

Convert the sequence s into a list

set(s)

Convert to mutable collection

dict(d)

Create a dictionary. d must be a sequence of (key, value) tuples.

frozenset(s)

Convert to immutable collection

chr(x)

Convert an integer to a character

ord(x)

Convert a character to its integer value

hex(x)

Convert an integer to a hexadecimal string

oct(x)

Convert an integer to an octal string