Python 3.9 Chapter 3 built in types and operators

3-1 built in type

  In Python, everything is an object. Object can be regarded as the smallest unit in Python, so the built-in data types to be introduced next can be objects. Python's built-in types are mainly divided into the following three types:

Numeric type: int, float, bool
String type: str, chr
Container type: list, dict, tuple

• Niklaus E. Wright once said: Algorithms + Data Structures = Programs
• in Python, all data is objects


3-1-1.   Numerical type

3-1-1-1. Integer

• integer
– the type is int, and integers and long integers are no longer distinguished
– after Python 3, the integer type is int, and the length of integers is not limited (except for hardware restrictions)

Next, we show 8, 10, 16 carry

>>> 10
10
>>> 0b1010
10
>>> 0o12
10
>>> 0xA
10

If you want to know how many bytes the int object uses, you can use the getsizeof() function of the sys module

import sys

print(sys.getsizeof(43848947982))

#The output is 32

After Python 3.6, you can use "" to separate numbers to increase readability.

>>> 1_000_000_000
1000000

If you want to know the data type, you can use the type() function:

As follows [code01]

x = 10
print(x)
print(type(x))

y = 20.0
print(y)
print(type(y))


#Output results
'''
10
<class 'int'>
20.0
<class 'float'>
'''

Any number is converted to an integer using the int() function, and the Boolean value is converted to 1 and False to 0:

x = 3
print(int(x))
y = 3.14159
print(int(y))
z = False
print(int(False))


#Output results
'''
3
3
0
'''

Floating point type (float):

x = float(3.14159)
print(x)
print(int(float(3.14159)))

#Output results
'''
3.14159
3
'''

Brin type:

There are only two values of boolean type, True and False, which are bool type

The following is True for non-0 values, and False for vice versa

*: None, False, complex, '' empty string, () empty tuple, [] empty list, {} when an empty dictionary is passed to bool, it will return False, and the rest will return True

x = bool(True)
print(int(x))
y = bool(False)
print(int(y))
z = 16
print(bool(z))
ab = 0
print(bool(ab))
cd = -13
print(bool(cd))


#Output results
'''
1
0
True
False
True

'''

Complex:

Use the form of a+bj when writing

x = 5 + 6j
y = 7 + 3j
print(x + y)
print(type(x + y))

#Output results
'''
(12+9j)
<class 'complex'>
'''

3-1-2. String type

If you want to represent a string in Python, you can use single quotation marks' 'or double quotation marks "" to wrap the text. Assuming that the string needs to use single quotation marks, the quotation marks surrounding the text should use double quotation marks. On the contrary, use single quotation marks, or use the symbols we will use later to solve the problem.

"Jame's"
'jame"s'

Basic string representation:

As shown above, assuming that single quotation marks and double quotation marks are used in the text, string translation can be used, as follows

print('Jame\'s')
print("Jame\"s")

#Jame's
#Jame"s

The following is the representation of string translation:

\\Backslash.
\'Single quotation mark. Use '' to represent a string. Use it when you want to represent a single quotation mark, for example: 'Jame\'s'.
\"Double quotation marks. Use "" to represent a string and single quotation marks. For example: "Jame\"s ".
\oooThe character code point is represented by an 8-digit number, with A maximum of 3 digits. For example, '\ 101' represents the string 'A'.
\xhhThe character code point is represented by the hexadecimal number hh. For example, '\ x41' represents the string 'A'.
\uhhhhThe character code point is represented by a 16 digit number hhhh hh.
\UhhhhhhhhThe character code point is represented by the 16 digit hhhh.
\0Empty character.
\nLine feed.
\rHoming.

\t

Tab.

To express \ T, you must write '\ \ t', which may be inconvenient. At this time, you can add r before the string.

print('\\t')
print(r'\t')

'''
\t
\t
'''

Legacy string formatting

Data form: String% data  

('string' % (d1, d2))

As shown below: 3 of. 3f is the output result, which is taken to the third decimal place

print('Hi %s' % 'Jason')
print('%d ÷ %d = %.3f' % (10, 3, 10 / 3))

'''
Hi Jason
10 ÷ 3 = 3.333
'''

The following are common formatting symbols

%%%The symbol is already used as a control symbol. If you want to represent% in a string, you must use%%
%fDecimal floating point number
%dDecimal integer
%gDecimal integer or floating point number
%e, %EScientific notation output, including lowercase output and uppercase output
%o8-bit integer
%x, %X16 bit integer output, including lowercase output and uppercase output
%sString format symbol
%r

The output string of the result obtained by the repr() function, which will be described in more detail in a later chapter

You can use the +, - Symbols to determine whether strings are aligned to the right or left

x = 10
y = 3
print('%-5d ÷ %-5d = %8.2f' % (x, y, x / y))
print('%5d ÷ %5d = %8.2f' % (x, y, x / y))


'''
10    ÷ 3     =     3.33
   10 ÷     3 =     3.33
'''

New string formatting:

The old format has poor readability. It is recommended to use the new format, as shown in the following example

* pay attention to the second line and use the number starting from 0

print('{} ÷ {} = {}'.format(10, 3, 10 / 3))
print('{0} ÷ {1} = {2}'.format(10, 3, 10 / 3))
print('{x} ÷ {y} = {z}'.format(x = 10, y = 3, z = 10 / 3))



'''
10 ÷ 3 = 3.3333333333333335
10 ÷ 3 = 3.3333333333333335
10 ÷ 3 = 3.3333333333333335
'''

Whether you use the second or third line above, you can specify the type, field width and number of decimal points

The <, > in the third and fourth lines determines whether to align left or right.

The ^ symbol in the fifth line can be preceded by the symbol to fill in the blank.

print('{0:6d} ÷ {1:6d} = {2:8.2f}'.format(10, 3, 10 / 3))
print('{x:6d} ÷ {y:6d} = {z:8.2f}'.format(x = 10, y = 3, z = 10 / 3))
print('{0:<6d} ÷ {1:<6d} = {2:<8.2f}'.format(10, 3, 10 / 3))
print('{0:>6d} ÷ {1:>6d} = {2:>8.2f}'.format(10, 3, 10 / 3))
print('{x:?^6d} ÷ {y:&^6d} = {z:8.2f}'.format(x = 10, y = 3, z = 10 / 3))


'''
    10 ÷      3 =     3.33
    10 ÷      3 =     3.33
10     ÷ 3      = 3.33    
    10 ÷      3 =     3.33
??10?? ÷ &&3&&& =     3.33
'''

The format method can also perform some simple operations, such as obtaining the list element value using the index, obtaining the corresponding value in the dictionary using the key name, or the name in the storage module:

names = ['James', 'Curry', 'Kevin']
print('EveryNames => {p[0]}, {p[1]}, {p[2]}'.format(p = names))

import sys
print('My MacOS is {pc.platform}'.format(pc = sys))



'''
EveryNames => James, Curry, Kevin
My MacOS is darwin
'''

Single formatted output:

print(format(1.123456, '.2f'))


'''
1.12
'''

String formatted real word:

Starting from Python 3.6, when writing a string real word, you can use f or F as the prefix to format the string. f-strings:

name = 'James'
print(f'Hi, {name}')
print(f'3 x 4 = {3 * 4}')
print(f'{{}}')



'''
Hi, James
3 x 4 = 12
{}
'''

f-strings can also perform operations, such as if...else expressions, function calls, etc. for example:

(not easy to read, not recommended)

name = None
print(f'Hi', {"James!" if name == None else name})


'''
Hi {'James!'}
'''

3-1-3 container type:

List:

The type of the list is list. It is ordered and has indexes. The content and length can be changed. The [] real word can be used to create a string:

x = [1, 2, 3]
print(x)
print(x[0])
print(x[1])
print(x[2])
x[1] = 40
print(x[1])
del x[0]
print(x)


'''
[1, 2, 3]
1
2
3
40
[40, 3]
'''

You can use [] to create a list with a length of 0, and you can use append() for the list     pop()     sort()     reverse()     remove() and other methods

, to attach multiple elements, you can use the extend() method, such as x.extend([1, 2, 3]). To copy a list, you can use the copy() function.

Set:

The contents of the collection are out of order and the elements are not repeated. To build a collection, you can use () to include the elements:

If you want to create an empty set, do not use (), because this will create an empty dict instead of a set. If you want to create an empty set, you must use set(). You can use the add() method for adding elements and the remove() method for removing elements. You can use the in method to test whether elements are included.

names = set()
names.add('James')
names.add('Curry')
print(names)
names.remove('James')
print(names)
print('James' in names)
print('Curry' in names)


'''
{'Curry', 'James'}
{'Curry'}
False
True
'''

You can also use copy() as mentioned earlier. To merge set s, you can use update().

x1 = {'you', 'good'}
x2 = {'you', 'yes'}
a = x1.copy()
a.update(x2)
print(a)


'''
{'you', 'yes', 'good'}
'''

Dictionary (dict):

The dictionary is used to store two corresponding key values:

_id = {'James' : 31, 'Curry' : 30}
print(_id['James'])
print(_id['Curry'])
_id['Kevin'] = 19
print(_id)
del _id['James']
print(_id)


'''
31
30
{'James': 31, 'Curry': 30, 'Kevin': 19}
{'Curry': 30, 'Kevin': 19}
'''

items():

_id = {'James' : 31, 'Curry' : 30}
print(list(_id.items()))
print(list(_id.keys()))
print(list(_id.values()))


'''
[('James', 31), ('Curry', 30)]
['James', 'Curry']
[31, 30]
'''

Use Dict to build a dictionary:

_id = dict(James = 31, Curry = 30, Kevin = 19)
print(_id)
_id = dict.fromkeys(['James', 'Curry'], 'NBA')
print(_id)

'''
{'James': 31, 'Curry': 30, 'Kevin': 19}
{'James': 'NBA', 'Curry': 'NBA'}
'''

You can also use copy() as mentioned earlier. To merge dict s, you can use update().

x1 = {'a' : 1, 'b' : 2}
x2 = {'b' : 2.1, 'c' : 3}
y = x1.copy()
y.update(x2)
print(y)

'''
{'a': 1, 'b': 2.1, 'c': 3}
'''

Tuple:

Tuple is similar to list in many ways. Oh!! it is an ordered structure. You can use [] to specify the index to obtain elements.

Sometimes Tuple is used when you want to return a set of related values without specifically defining a type.

data = 29, 'Curry', False
number, name, verified = data
print(data)
print(number)
print(name)
print(verified)

'''
(29, 'Curry', False)
29
Curry
False
'''

The elements in Tuple can be disassembled and assigned to each Variable.

ant = 30, 'Curry', bool
print(ant)
print(type(ant))

'''
(30, 'Curry', <class 'bool'>)
<class 'tuple'>
'''

number, name, verified = [29, 'Curry', False]
print(number)
print(name)
print(verified)

'''
29
Curry
False
'''

3-2. Operator

3-2-1. Operator + - */

print(0.1 + 0.1 + 0.1)
print(1.0 - 0.8)


'''
0.30000000000000004
0.19999999999999996
'''

Developers should basically know the IEEE 754 floating point arithmetic standard. Instead of using decimal points, they use fractions and exponents to represent decimals:
– 0.5 in 1 / 2
– 0.75 in 1 / 2 + 1 / 4 – 0.875 in 1 / 2 + 1 / 4 + 1 / 8
– 0.1 is 1 / 16 + 1 / 32 + 1 / 256 + 1 / 512 + 1 / 4096 + 1 / 8192 +... No end

Use the decimal.Decimal class to solve the above problem:

import decimal

y1 = decimal.Decimal((input()))
y2 = decimal.Decimal((input()))

print(f'{y1} + {y2} = {y1 + y2}')
print(f'{y1} - {y2} = {y1 - y2}')
print(f'{y1} * {y2} = {y1 * y2}')
print(f'{y1} / {y2} = {y1 / y2}')


'''
1
0.8
'''

'''
1 + 0.8 = 1.8
1 - 0.8 = 0.2
1 * 0.8 = 0.8
1 / 0.8 = 1.25
'''

Power * *:

print(2 ** 3)
print(5 ** 5)
print(3 ** 0.5)


'''
8
3125
1.7320508075688772
'''

Division/    //:

print(10 / 3)
print(10 // 3)
print(10 // 3.0)


'''
3.3333333333333335
3
3.0
'''

Combined string application:

str1 = 'James'
str2 = 'Curry'
print(str1 + str2)
print(str1 * 5 + str2 * 2)


'''
JamesCurry
JamesJamesJamesJamesJamesCurryCurry
'''
print('20' + str(1))
print(int('9') + 6)


'''
201
15
'''

list, tuple application:

x1 = ['apple', 'group']
x2 = ['Kevin', 'Xiang']
print(x1 + x2)
print(x2 * 2 + x1 * 2)


'''
['apple', 'group', 'Kevin', 'Xiang']
['Kevin', 'Xiang', 'Kevin', 'Xiang', 'apple', 'group', 'apple', 'group']
'''
x1 = ['apple', 'group']
x2 = ['Kevin', 'Xiang']
y = (x1, x2)
print(y)


'''
(['apple', 'group'], ['Kevin', 'Xiang'])
'''

3-2-2. Comparison operator:

  • – >,>=,<,<=,==,!=,<>

  • < > the effect is the same as! = but it is recommended not to use it again

x1 = input()
x2 = input()

print(f'"{x1}" > "{x2}"  ? {x1 > x2}')
print(f'"{x1}" < "{x2}"  ? {x1 < x2}')
print(f'"{x1}" = "{x2}"  ? {x1 == x2}')
print(f'"{x1}" != "{x2}"  ? {x1 != x2}')


'''
6
5
"6" > "5"  ? True
"6" < "5"  ? False
"6" = "5"  ? False
"6" != "5"  ? True
'''

Specify operator:

+=a += ba = a + b
 -=a -= ba = a - b
*=a *= ba = a * b
/=a /= ba = a / b
%=a %= ba = a % b
&=a &= ba = a & b
|=a |= ba = a | b
^=a ^= ba = a ^ b
>>=a >>= ba = a >> b
<<=a <<= ba = a << b

3-2-3. Logical operators

*And     and

*Or     or

*On the contrary     not

x1 = input()
x2 = input()

print('Are the two numbers capitalized?', x1.isupper() and x2.isupper())
print('Is a number capitalized?', x1.isupper() or x2.isupper())
print('Neither number is capitalized?', not (x1.isupper() or x2.isupper()))


'''
a
D
 Are the two numbers capitalized? False
 Is a number capitalized? True
 Neither number is capitalized? False
'''

3-2-4. & (and) | (or) ^ (XOR) ~ (complement) operator

(bloggers are too lazy to write. It's important to learn)

3-2-5. Slice operator

name = 'Kevinjay'
print(name[0:2])
print(name[2:])
print(name[:3])
print(name[:])
print(name[:-2])
print(name[-4:-1])

'''
Ke
vinjay
Kev
Kevinjay
Kevinj
nja
'''
x = 1, 2, 3, 4, 5
print(x[0:2])
print(x[1:])
print(x[:4])
print(x[-5:-1])
print(x[::-1])


'''
(1, 2)
(2, 3, 4, 5)
(1, 2, 3, 4)
(1, 2, 3, 4)
(5, 4, 3, 2, 1)
'''

3-2-6. Disassembly operator ***

#tuple
a, *b = (1, 2, 3, 4, 5)
print(a)
print(b)
print() #Line feed

#list
a, *b, c = (1, 2, 3, 4, 5)
print(a)
print(b)
print(c)
print()

#set
a, *b = {1, 2, 3}
print(a)
print(b)
print()

#range
a, *b, c = range(5)
print(a)
print(b)
print(c)
print()

#dict
a, *b = {'x' : 1, 'y' : 2, 'z' : 3}
print(a)
print(b)




'''
1
[2, 3, 4, 5]

1
[2, 3, 4]
5

1
[2, 3]

0
[1, 2, 3]
4

x
['y', 'z']
'''
x1 = {'you', 'good'}
x2 = {'you', 'yes'}
y = {*x1, *x2}
print(y)


'''
{'yes', 'good', 'you'}
'''

dict figured out that the key and value use * *, as long as the key uses *:

x1 = {'a' : 1, 'b' : 2}
x2 = {'b' : 3, 'c' : 4}
y1 = {*x1, *x2}
y2 = {**x1, **x2}
print(y1)
print(y2)


'''
{'c', 'a', 'b'}
{'a': 1, 'b': 3, 'c': 4}
'''

Tags: Python

Posted on Sat, 11 Sep 2021 16:16:04 -0400 by atitthaker