Python3 Basic Data Types
Variables in Python do not need to be declared. Each variable must be assigned a value before use, and the variable is created after assignment.
In Python, a variable itself has no type; the "type" we refer to is the type of the object in memory that the variable points 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 is the value stored in the variable. For example:
Example (Python 3.0+)
#!/usr/bin/python3
counter = 100 # Integer variable
miles = 1000.0 # Floating-point variable
name = "tutorialpro" # String
print(counter)
print(miles)
print(name)
Executing the above program will output the following results:
100
1000.0
tutorialpro
Multiple Variable Assignment
Python allows you to assign values to multiple variables simultaneously. For example:
a = b = c = 1
In the above example, an integer object with the value 1 is created, and the values are assigned from right to left, so all three variables are assigned the same value.
You can also assign multiple values to multiple variables. For example:
a, b, c = 1, 2, "tutorialpro"
In the above example, the integer objects 1 and 2 are assigned to variables a and b, respectively, and the string object "tutorialpro" is assigned to variable c.
Standard Data Types
Python3 has six standard data types:
- Number
- String
- List
- Tuple
- Set
- Dictionary
Among the six standard data types in Python3:
- Immutable Data (3 types): Number, String, Tuple;
- Mutable Data (3 types): List, Dictionary, Set.
Number
Python3 supports int, float, bool, complex (complex number).
In Python 3, there is only one integer type, int, which represents a long integer, unlike the Long type in Python2.
Assignment and calculations for numeric types are straightforward, similar to most languages.
The built-in type() function can be used to query the type of the object a variable points to.
>>> 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'>
Additionally, you can use isinstance to determine the type:
Example
>>> a = 111
>>> isinstance(a, int)
True
>>>
The difference between isinstance and type is:
- type() does not consider a subclass to be a type of its parent class.
- isinstance() considers a subclass to be a type of its parent class.
>>> 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, and True and False can be added to numbers. True==1
and False==0
return True, but you can use is
to check the type.
>>> issubclass(bool, int)
True
>>> True==1
True
>>> False==0
True
>>> True+1
2
>>> False+1
1
>>> 1 is True
False
>>> 0 is False
False
In Python2, there is no boolean type; it uses the number 0 to represent False and 1 to represent True.
When you assign a value, a Number object is created:
var1 = 1
var2 = 10
You can also use the del statement to delete object references.
The syntax for the del statement is:
del var1[,var2[,var3[....,varN]]]
You can delete single or multiple objects using the del statement. For example:
del var
del var_a, var_b
Numeric Operations
Example
>>> 5 + 4 # Addition
9
>>> 4.3 - 2 # Subtraction
2.3
>>> 3 * 7 # Multiplication
21
>>> 2 / 4 # Division, resulting in a floating-point number
0.5
>>> 2 // 4 # Division, resulting in an integer
0
17 % 3 # Modulus
2
>>> 2 ** 5 # Exponentiation
32
**Note:**
- 1. Python allows simultaneous assignment of multiple variables, such as `a, b = 1, 2`.
- 2. A variable can be assigned to objects of different types.
- 3. Numeric division includes two operators: `/` returns a float, and `//` returns an integer.
- 4. In mixed calculations, Python converts integers to floats.
### Numeric Types Examples
| int | float | complex |
| --- | --- | --- |
| 10 | 0.0 | 3.14j |
| 100 | 15.20 | 45.j |
| -786 | -21.9 | 9.322e-36j |
| 080 | 32.3e+18 | .876j |
| -0490 | -90. | -.6545+0J |
| -0x260 | -32.54e100 | 3e+26J |
| 0x69 | 70.2E-12 | 4.53e-7j |
Python also supports complex numbers, which are made up of a real part and an imaginary part. They can be represented as `a + bj` or `complex(a, b)`, where both the real part **a** and the imaginary part **b** are floats.
---
## String
Strings in Python are enclosed in single `'` or double quotes `"`, and special characters are escaped using a backslash `\`.
The syntax for slicing a string is:
variable[start_index:end_index]
Index values start at 0 from the beginning and -1 from the end.
The plus sign `+` is the string concatenation operator, and the asterisk `*` is the repetition operator. Here is an example:
## Example
!/usr/bin/python3
str = 'tutorialpro'
print(str) # Output the string print(str[0:-1]) # Output all characters from the first to the second last print(str[0]) # Output the first character print(str[2:5]) # Output characters from the third to the fifth print(str[2:]) # Output all characters from the third onwards print(str * 2) # Output the string twice, also can be written as print(2 * str) print(str + "TEST") # Concatenate strings
Executing the above program will output the following:
tutorialpro tutorialpr t tor torialpro tutorialprotutorialpro tutorialproTEST
Python uses a backslash `\` to escape special characters. If you do not want the backslash to escape, you can prefix the string with an `r`, indicating a raw string:
## Example
print('Tutorial\nPro') Tutorial Pro print(r'Tutorial\nPro') Tutorial\nPro
Additionally, a backslash (`\`) can be used as a line continuation character, indicating that the next line is a continuation of the previous one. You can also use triple quotes `"""..."""` or `'''...'''` to span multiple lines. Note that Python does not have a separate character type; a character is simply 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 to an indexed position, such as `word[0] = 'm'`, will result in an error. **Note:** - 1. A backslash can be used to escape characters, and using `r` prevents the backslash from escaping. - 2. Strings can be concatenated with the `+` operator and repeated with the `*` operator. - 3. Python strings have two indexing systems: left to right starting at 0, and right to left starting at -1. - 4. Python strings are immutable. --- ## List A List is one of the most frequently used data types in Python. Lists can implement most collection data structures. Elements in a list can be of different types, including numbers, strings, or even other lists (nested lists). Lists are written within square brackets `[]` and elements are separated by commas. Like strings, lists can be indexed and sliced, and slicing returns a new list containing the requested elements. The syntax for slicing a list is:
variable[start_index:end_index]
Index values start at `0` from the beginning and `-1` from the end. The plus sign `+` is the list concatenation operator, and the asterisk `*` is the repetition operator. Here is an example: ## Example
!/usr/bin/python3
list = ['abcd', 786, 2.23, 'tutorialpro', 70.2] tinylist = [123, 'tutorialpro']
print(list) # Output the list print(list[0]) # Output the first element of the list print(list[1:3]) # Output elements from the second to the third print(list[2:]) # Output elements from the third onwards print(tinylist * 2) # Output the list twice print(list + tinylist) # Concatenate lists
print(list) # Output the entire list
print(list[0]) # Output the first element of the list
print(list[1:3]) # Output elements from the second to the third
print(list[2:]) # Output all elements starting from the third
print(tinylist * 2) # Output the list twice
print(list + tinylist) # Concatenate the lists
Example output:
['abcd', 786, 2.23, 'tutorialpro', 70.2]
abcd
[786, 2.23]
[2.23, 'tutorialpro', 70.2]
[123, 'tutorialpro', 123, 'tutorialpro']
['abcd', 786, 2.23, 'tutorialpro', 70.2, 123, 'tutorialpro']
Unlike Python strings, elements in a 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 values to []
>>> a
[9, 2, 6]
List has many built-in methods, such as append() and pop(), which will be discussed later.
Note:
- Lists are written within square brackets and elements are separated by commas.
- Like strings, lists can be indexed and sliced.
- Lists can be concatenated using the + operator.
- Elements in a list can be changed.
Python list slicing can take a third parameter, which specifies the step size. The following example slices the string from index 1 to index 4 with a step size of 2 (skipping one position):
If the third parameter is negative, it indicates reading in reverse. The following example is used to reverse a string:
Example
def reverseWords(input):
# Split the string by spaces, dividing it into words
inputWords = input.split(" ")
# Reverse the string
# Assuming list = [1,2,3,4],
# list[0]=1, list[1]=2, and -1 represents the last element list[-1]=4 (same as list[3]=4)
# inputWords[-1::-1] has three parameters
# The first parameter -1 represents the last element
# The second parameter is empty, meaning move to the end of the list
# The third parameter is the step, -1 means reverse
inputWords=inputWords[-1::-1]
# Recombine the string
output = ' '.join(inputWords)
return output
if __name__ == "__main__":
input = 'I like tutorialpro'
rw = reverseWords(input)
print(rw)
Output result:
tutorialpro like I
Tuple
A tuple is similar to a list, but its elements cannot be modified. Tuples are written within parentheses ()
and elements are separated by commas.
Tuples can also contain elements of different types:
Example
#!/usr/bin/python3
tuple = ( 'abcd', 786 , 2.23, 'tutorialpro', 70.2 )
tinytuple = (123, 'tutorialpro')
print (tuple) # Output the entire tuple
print (tuple[0]) # Output the first element of the tuple
print (tuple[1:3]) # Output elements from the second to the third
print (tuple[2:]) # Output all elements starting from the third
print (tinytuple * 2) # Output the tuple twice
print (tuple + tinytuple) # Concatenate the tuples
Example output:
('abcd', 786, 2.23, 'tutorialpro', 70.2)
abcd
(786, 2.23)
(2.23, 'tutorialpro', 70.2)
(123, 'tutorialpro', 123, 'tutorialpro')
('abcd', 786, 2.23, 'tutorialpro', 70.2, 123, 'tutorialpro')
Tuples are similar to strings and can be indexed, with the subscript index starting from 0, and -1 being the position from the end. They can also be sliced (as mentioned above, no further elaboration here).
In fact, strings can be considered a special type of tuple.
Example
>>> tup = (1, 2, 3, 4, 5, 6)
>>> print(tup[0])
1
>>> print(tup[1:5])
(2, 3, 4, 5)
>>> tup[0] = 11 # 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 tuple elements cannot be changed, tuples can contain mutable objects, such as lists.
Constructing tuples with 0 or 1 element is special, so there are some additional syntax rules:
tup1 = () # Empty tuple
tup2 = (20,) # One element, a comma must be added after the element
Strings, lists, and tuples all belong to sequences.
Note:
- Like strings, tuple elements cannot be modified.
- Tuples can also be indexed and sliced, using the same methods.
- Pay attention to the special syntax rules for constructing tuples with 0 or 1 element.
- Tuples can also be concatenated using the + operator.
Set
A set is a collection of one or more different sizes and shapes, with the things or objects that make up the set being called elements or members.
The basic functions are membership testing and removing duplicate elements.
Sets can be created using curly braces { }
or the set()
function. Note: To create an empty set, you must use set()
, not { }
, because { }
is used to create an empty dictionary.
Creation format:
parame = {value01, value02, ...}
or
set(value)
Example
#!/usr/bin/python3
sites = {'Google', 'Taobao', 'tutorialpro', 'Facebook', 'Zhihu', 'Baidu'}
print(sites) # Output the set, duplicate elements are automatically removed
# Membership test
if 'tutorialpro' in sites :
print('tutorialpro is in the set')
else :
print('tutorialpro is not in the set')
# Set operations
a = set('abracadabra')
b = set('alacazam')
print(a)
print(a - b) # Difference of a and b
print(a | b) # Union of a and b
print(a & b) # Intersection of a and b
print(a ^ b) # Elements in a and b that are not in both
Output of the above example:
{'Zhihu', 'Baidu', 'Taobao', 'tutorialpro', 'Google', 'Facebook'}
tutorialpro is in the set
{'b', 'c', 'a', 'r', 'd'}
{'r', 'b', 'd'}
{'b', 'c', 'a', 'z', 'm', 'r', 'l', 'd'}
{'c', 'a'}
{'z', 'b', 'm', 'r', 'l', 'd'}
Dictionary
A dictionary is another very useful built-in data type in Python.
Lists are ordered collections of objects, while dictionaries are unordered collections. The difference between them is that elements in dictionaries are accessed by keys, not by offsets.
A dictionary is a mapping type, identified by { }
, and it is a collection of unordered key(key):value(value) pairs.
Keys must be of an immutable type.
In the same dictionary, keys must be unique.
Example
#!/usr/bin/python3
dict = {}
dict['one'] = "1 - tutorialpro.org"
dict[2] = "2 - tutorialpro"
tinydict = {'name': 'tutorialpro', 'code': 1, 'site': 'www.tutorialpro.org'}
print (dict['one']) # Output value for key 'one'
print (dict[2]) # Output value for key 2
print (tinydict) # Output the entire dictionary
print(tinydict.keys()) # Output all keys
print(tinydict.values()) # Output all values
Example output:
1 - tutorialpro.org
2 - tutorialpro
{'name': 'tutorialpro', 'code': 1, 'site': 'www.tutorialpro.org'}
dict_keys(['name', 'code', 'site'])
dict_values(['tutorialpro', 1, 'www.tutorialpro.org'])
The dict()
constructor can directly build a dictionary from a sequence of key-value pairs as follows:
Example
>>> dict([('tutorialpro', 1), ('Google', 2), ('Taobao', 3)])
{'tutorialpro': 1, 'Google': 2, 'Taobao': 3}
>>> {x: x**2 for x in (2, 4, 6)}
{2: 4, 4: 16, 6: 36}
>>> dict(tutorialpro=1, Google=2, Taobao=3)
{'tutorialpro': 1, 'Google': 2, 'Taobao': 3}
{x: x**2 for x in (2, 4, 6)}
uses dictionary comprehension. For more comprehension details, refer to Python Comprehensions.
Additionally, the dictionary type has some built-in functions such as clear()
, keys()
, values()
, etc.
Note:
- A dictionary is a mapping type, with elements as key-value pairs.
- Dictionary keys must be of an immutable type and cannot be duplicated.
- An empty dictionary is created using
{}
.
- An empty dictionary is created using
Python Data Type Conversion
Sometimes, we need to convert the built-in types of data. Data type conversion is done by using the data type as the function name. The next chapter, Python3 Data Type Conversion, will introduce this in detail.
The following built-in functions perform conversions between data types. These functions return a new object representing the converted value.
Function | Description |
---|---|
int(x [,base]) | Converts x to an integer |
float(x) | Converts x to a floating-point number |
complex(real [,imag]) | Creates a complex number |
str(x) | Converts object x to a string |
repr(x) | Converts object x to an expression string |
eval(str) | Evaluates a string as a valid Python expression and returns an object |
tuple(s) | Converts sequence s to a tuple |
list(s) | Converts sequence s to a list |
set(s) | Converts to a mutable set |
dict(d) | Creates a dictionary. d must be a sequence of (key, value) tuples. |
frozenset(s) | Converts to an immutable set |
chr(x) | Converts an integer to a character |
ord(x) | Converts a character to its integer value |
hex(x) | Converts an integer to a hexadecimal string |
oct(x) | Converts an integer to an octal string |