forked from WebJournal/journaldev
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpython_bool_examples.py
More file actions
83 lines (64 loc) · 1.46 KB
/
python_bool_examples.py
File metadata and controls
83 lines (64 loc) · 1.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# Boolean and None examples
from decimal import Decimal
from fractions import Fraction
x = True
b = bool(x)
print(type(x)) # <class 'bool'>
print(type(b)) # <class 'bool'>
print(b) # True
x = False
b = bool(x)
print(b) # False
x = None
b = bool(x)
print(type(x)) # <class 'NoneType'>
print(type(b)) # <class 'bool'>
print(b) # False
# string examples
x = 'True'
b = bool(x)
print(type(x)) # <class 'str'>
print(type(b)) # <class 'bool'>
print(b) # True
x = 'False'
b = bool(x)
print(b) # True because len() is used
x = ''
print(bool(x)) # False, len() returns 0
# bool() with numbers
print(bool(10)) # True
print(bool(10.55)) # True
print(bool(0xF)) # True
print(bool(10 - 4j)) # True
print(bool(0)) # False
print(bool(0.0)) # False
print(bool(0j)) # False
print(bool(Decimal(0))) # False
print(bool(Fraction(0, 2))) # False
# bool() with collections and sequences
tuple1 = ()
dict1 = {}
list1 = []
print(bool(tuple1)) # False
print(bool(dict1)) # False
print(bool(list1)) # False
# bool() with custom object
class Data:
id = 0
def __init__(self, i):
self.id = i
# returns True for id > 0 else False
def __bool__(self):
print('bool function called')
return self.id > 0
# returns 0 for id <= 0, else id
def __len__(self):
print('len function called')
if self.id > 0:
return self.id
else:
return 0
d = Data(0)
print(bool(d))
d = Data(10)
print(bool(d))