Bool & other data type

本文介绍了Python中的几种数据类型,包括布尔型(Bool),不可变集合型(Frozenset),字节型(Bytes),可变字节型(bytearray)以及范围型(Range)。布尔型用于表达真和假;Frozenset用于创建不可变集合,不能进行修改操作;Bytes类型用于表示一组字节,适用于处理二进制数据;bytearray与Bytes类似,但元素可变;Range类型则用于生成指定范围内的数字序列,通常与for循环结合使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Bool data type

In Pythin, to represent boolean values (True and False) we use the bool data type. Boolean values are used to evaluate the value of the expression. For example, when we compare two values, the expression is evaluated, and Python retuns the boolean True or False.

Example:

x = 25
y = 30

z = x > y
print(z) # True
print(type(z)) # class 'bool'

Frozenset data type

The frozenset data type is used to create the immutable set. Once we create a frozenset, then we can't perform any changes on it.

Use a frozenset() class to create a frozenset.

Example:

set = {11, 33, 55, 77, 99}
print(type(set)) # class 'set'

# creating frozenset
f_set = frozenset(set)
print(type(f_set)) # class 'frozenset'

Note: If we try to perform operations like add, remove on fronzenset, you will get an error.

Bytes data type

The bytes data type represents a group of byte numbers just like an array. We use the bytes() constructor to create bytes type, which also returns a bytes object.

Bytes are immutable (cannot be changed).

Use bytes data type if we want to handle binary data like images, vaideo, and audio files.

Example:

a = [1, 3, 5, 7, 9]
b = bytes(a)
print(type(b)) # class 'bytes'
print(b[0]) # 1
print(b[-1]) # 9

In bytes, allowed values 0 to 256. If we are trying to use any other values, then we will get a valueError.

Example:

a = [333, 555, 777, 999] # Give error range must be in 0 to 256
b = bytes(a)
print(type(b))
# ValueError: bytes must be in range(0, 256)

bytearray data type

The bytearray data type same as the bytes type except bytearray mutable (we can modify its elements). The bytearray() constructor returns a bytearray object.

Example:

# create a bytearray
list1 = [1, 3, 5, 7, 9]
b_array = bytearray(list1)
print(b_array)
print(type(b_array) # class 'bytearray'

# modifying bytearray
b_array[1] = 11
print(b_array[1]) # 11

# iterate bytearray
for i in b_array:
    print(i, end=" ") #  1 11 5 7 9

Range data type

In Python, the built-in function range() used to generate a sequence of numbers from a start number up to the stop number. For example, if we want to represet the roll number from 1 to 20, we can use the range() type. By default, it returns an iterator object that we can iterate using a for loop.

Example:

# Generate integer number from 10 to 24
numbers = range(10, 15, 1)
print(type(numbers)) # class 'range'

# iterate range using for loop
for i in range(10, 15, 1):
    print(i, end= " ") # Output 10 11 12 13 14

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值