2. Python basic data types

Posted by svguerin3 on Thu, 16 Dec 2021 17:17:13 +0100

1 Number

1.1 integer

There are four forms of integer:

  • Binary: '0b111' is 7
  • Octal: '0o111' is 73
  • Decimal: 73
  • Hexadecimal: '0o111' is 273

Binary conversion:

  • bin(i): convert i to binary
  • oct(i): convert i to octal
  • int(i): converts i to hexadecimal
  • hex(i): convert i to hexadecimal

Numeric type conversion:

  • int(x)
  • float(x)
  • complex(x) - converts x to a complex number. The real part is x and the imaginary part is 0.
  • complex(x,y)

Python number operation:

  • /: always returns a floating point number
  • //: rounding down after division
  • **: power operation

1.2 floating point

Floating point types consist of integers and decimals, which can also be represented by scientific counting (2.5e2 = 2.5 x 102 = 250).

Note:
When using floating-point numbers for calculation, the number of decimal places may be uncertain. For example, when calculating 0.1 + 0.2, you should get 0.3, but after testing, the running result of Python interpreter is 0.300000000000000 4. This problem is related to the underlying storage of floating-point numbers.

1.3 boolean type

  • Null object, any number with a value of zero or the Boolean value of null object None is False.
  • In Python 3, True=1, False=0, which can be operated with numeric type.

1.4 plural

It is composed of real part and imaginary part, represented by a + bj or * * complex(a,b) * *. Where a and B are floating point.

Common functions:



2 String (string)

  • String interception (left closed right open):
    Variable [head subscript: tail subscript]
  • Non variable
  • Python string operator:

    Format string: print ("my name is% s, and I am% d years old!"% " ('xiaoming ', 10))
  • f-string
    f-string format string starts with f, followed by a string. The expression in the string is wrapped in curly braces {}. It will replace the calculated value of the variable or expression. Examples are as follows:
>>> w = {'name': 'Runoob', 'url': 'www.runoob.com'}
>>> f'{w["name"]}: {w["url"]}'
'Runoob: www.runoob.com'
  • String common functions





3 List

The list can perform operations, including indexing, slicing, adding, multiplying, and checking members.

  • Create list
list1 = []	#Empty list
list2 = ['Google', 'Runoob', 1997, 2000]
  • Update list
#Original list
list = ['Google', 'Runoob', 1997, 2000]
#1 
list[2] = 2001		#Modify list elements according to index
#2 
list.append('Baidu')		#Add objects at the end of the list
print("Updated list : ", list)

#Output results
['Google', 'Runoob', 2001, 2000, 'Baidu']
  • Delete list element
del list[2]
  • List script operator
  • List interception and splicing
list = ["aaa","bbb","ccc"]
listp[1:2] 
#Output result: "bbb"

list + ["ddd","eee"] 
#Output result: ["aaa","bbb","ccc","ddd","eee"]
  • Python list functions and methods

4 Tuple

Python tuples are similar to lists, except that the elements of tuples cannot be modified.

  • Create tuple
tup1 = ('Google', 'Runoob', 1997, 2000)
tup2 = (1, 2, 3, 4, 5 )
tup3 = "a", "b", "c", "d"   #  You don't need parentheses
tup4 = ()	# Create empty tuple

Note:
When a tuple contains only one element, you need to add a comma after the element, otherwise the parentheses will be used as operators:

>>> tup1 = (50)
>>> type(tup1)     # The type is integer without comma
<class 'int'>

>>> tup1 = (50,)
>>> type(tup1)     # Add a comma and the type is tuple
<class 'tuple'>
  • Access tuple
    Similar to the list.

  • Modify tuple
    Element values in tuples are not allowed to be modified, but we can connect and combine tuples:

tup1 = (12, 34.56)
tup2 = ('abc', 'xyz')
 
# The following operation to modify tuple elements is illegal.
# tup1[0] = 100
 
# Create a new tuple
tup3 = tup1 + tup2
print (tup3)
  • Delete tuple
    Element values in tuples are not allowed to be deleted, but we can use del statement to delete the whole tuple:
del tup
  • Tuple operator
    Like strings, tuples can be manipulated with + and * signs.

  • Tuple index

  • Tuple built-in function

An iteratable object means a container object that stores elements, and the elements in the container can be accessed through the iter() method or getitem() method. It does not refer to a specific data type.

Note:
The immutability of tuples refers to the immutability of the contents in the memory pointed to by tuples.

>>> tup = ('r', 'u', 'n', 'o', 'o', 'b')
>>> tup[0] = 'g'     # Modifying elements is not supported
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> id(tup)     # View memory address
4440687904
>>> tup = (1,2,3)
>>> id(tup)
4441088800    # The memory address is different

5 Set

A set is an unordered sequence of non repeating elements.

  • Create collection
s = {'apple', 'orange'}
s = set()	#Create an empty collection
  • Add element
#1. Add
s.add("banana")
#2. Add. The parameters can be list, tuple, dictionary, etc
s.update( x )
  • Removing Elements
#1. An error will be reported if the element does not exist
s.remove( x )
#2. No error will be reported if the element does not exist
s.discard( x )
#3. Randomly delete an element
s.pop()
  • Calculate the number of elements
len(s)
  • Empty collection
s.clear()
  • Determine whether the element exists in the collection
# Judge whether the element x is in the collection s. if it is, it returns True; otherwise, it returns False
x in s
  • Set operators
    S1 & S2: find the intersection of two sets
    s1 | s2: find the union of two sets
    s1 - s2: find the difference set of s1 minus s2
    s1 ^ s2: find the symmetric difference set of two sets

  • Complete list of collection built-in methods

6 Dictionary

Each key = > value pair of the dictionary is separated by a colon, and each pair is separated by a comma * * (,) * * between them. The whole dictionary is included in curly braces {}. The format is as follows:

d = {key1 : value1, key2 : value2, key3 : value3 }

Keys must be unique, but values do not.
The value can take any data type, but the key must be immutable, such as string and number.

  • Create dictionary
dict1 = { 'abc': 456 }
dict2 = { 'abc': 123, 98.6: 37 }
  • Accessing values in the dictionary
dict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}
 
print ("dict['Name']: ", dict['Name'])
print ("dict['Age']: ", dict['Age'])

#Output results
dict['Name']:  Runoob
dict['Age']:  7
  • Modify dictionary
dict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}
 
dict['Age'] = 8               # Update Age
dict['School'] = "Rookie tutorial"  # Add information

#Output results
{'Name': 'Runoob', 'Age': 8, 'Class': 'First', 'School': 'Rookie tutorial'}
  • Delete dictionary element
dict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}
 
del dict['Name'] # Delete key 'Name'
dict.clear()     # Empty dictionary
del dict         # Delete dictionary
  • Properties of dictionary keys
    The same key is not allowed to appear twice.
    Keys must be immutable, so they can be numbers, strings, or tuples. The list is variable and cannot act as a.

  • Dictionary built-in functions and methods


Note:

  • Direct assignment: the reference (alias) of the object.
  • Shallow copy: copies the parent object without copying the child objects inside the object.
  • Deep copy: a full copy of the parent and its children.

Resolution:
1. b = a: assignment reference, a and b both point to the same object.

2. b = a.copy(): shallow copy. a and b are independent objects, but their child objects still point to unified objects (references).

3. b = copy. Deep copy (a): deep copy. A and B completely copy the parent object and its children. They are completely independent.

Topics: Python