Python Booleans¶
- Boolean values in Python represent one of two values : True and False.
- Booleans are often used for conditional statements, comparisons, and controlling the flow of a program.
Boolean Values:¶
- In Python, True and False are reserved keywords representing the boolean values.
In [ ]:
x = True
y = False
Boolean Operators:¶
Python provides several operators for working with boolean values.
- and: Returns True if both operands are True.
- or: Returns True if at least one operand is True.
- not: Returns the opposite of the boolean operand.
In [ ]:
a = True
b = False
result1 = a and b # False
result2 = a or b # True
result3 = not a # False
print(result1)
print(result2)
print(result3)
False True False
Comparison Operators:¶
- You can compare values using comparison operators, which return boolean results.
==: Equal to
!=: Not equal to
<: Less than
<=: Less than or equal to
>: Greater than
>=: Greater than or equal to
In [ ]:
num1 = 5
num2 = 10
result1 = num1 == num2 # False
result2 = num1 < num2 # True
result3 = num1 != num2 # True
print(result1)
print(result2)
print(result3)
False True True
Conditional Statements:¶
- Booleans are commonly used in conditional statements like if, elif, and else to control program flow.
In [ ]:
age = 20
if age >= 18:
print("You are an adult.")
else:
print("You are a minor.")
You are an adult.
Boolean Conversion:¶
- You can convert other data types to boolean using the bool() constructor.
- In general, empty sequences (e.g., empty lists or strings) and numeric zeros are considered False, while non-empty sequences and non-zero numbers are considered True.
In [ ]:
bool_var = bool(0) # False
bool_str = bool("Hello") # True
bool_var1 = bool(15)
print(bool_var)
print(bool_str)
print(bool_var1)
False True True
Boolean Functions:¶
- You can create functions that return boolean values based on certain conditions.
In [ ]:
def is_even(number):
return number % 2 == 0
print(is_even(4)) # True
print(is_even(7)) # False
True False
- Python also has many built-in functions that return a boolean value, like the isinstance() function, which can be used to determine if an object is of a certain data type
In [ ]:
x = 200
print(isinstance(x, int))
True
Truthy Values:¶
- Values that are considered True in a boolean context:
- Any non-empty string: "hello", "0", "False", etc.
- Any non-zero number: 1, -1, 3.14, etc.
- Any non-empty list, tuple, set, or dictionary: [1, 2, 3], ("apple", "banana"), {1, 2, 3}, {"key": "value"}.
In [ ]:
# Truthy values
if "hello":
print("This is a truthy string.")
if 42:
print("This is a truthy number.")
if [1, 2, 3]:
print("This is a truthy list.")
This is a truthy string. This is a truthy number. This is a truthy list.
Falsy Values:¶
- Values that are considered False in a boolean context:
- Empty strings: "" (an empty string is falsy).
- The number 0 (zero is falsy).
- Empty collections: [] (empty list), () (empty tuple), set() (empty set), {} (empty dictionary).
In [ ]:
# Falsy values
if "":
print("This is an empty string (falsy).")
if 0:
print("This is the number 0 (falsy).")
if []:
print("This is an empty list (falsy).")
In [ ]:
# None also return false
bool(None)
Out[ ]:
False
Python Number¶
Numbers in Python come in different types, including integers, floating-point numbers, and complex numbers.
In Python 3, there are three main numeric types:
| Type | Description |
|---|---|
int |
Represents integers (positive, negative, or zero). |
float |
Represents real numbers with decimal points (floating-point values). |
complex |
Represents complex numbers in the form x + yj, where x and y are real numbers, and j is the imaginary unit. |
Examples:
| int | float | complex |
|---|---|---|
5 |
0.0 |
3.14j |
-9 |
15.20 |
45.j |
0x64 |
-32.54e100 |
3e+26j |
0b1010 |
2.75E3 |
-.6545+0j |
Note:
- Prefix
0b→ binary - Prefix
0o→ octal - Prefix
0x→ hexadecimal - Scientific notation uses
eorE(e.g., 1.2e3 = 1200.0)
In [1]:
# Integer
a = 1
print(a, type(a)) # Output: 1 <class 'int'>
# Floating point number
b = 1.65
print(b, type(b)) # Output: 1.65 <class 'float'>
# Scientific notation
c = 40e1 # 40 × 10¹ = 400.0
print(c, type(c)) # Output: 400.0 <class 'float'>
# Complex number
d = 1 + 2j
print(d, type(d)) # Output: (1+2j) <class 'complex'>
# Real and imaginary parts of complex number
print(d.real) # 1.0
print(d.imag) # 2.0
1 <class 'int'> 1.65 <class 'float'> 400.0 <class 'float'> (1+2j) <class 'complex'> 1.0 2.0
Functions for Data-Type Conversion¶
- Python provides several built-in functions for converting data from one data type to another. These functions return a new object representing the converted value, leaving the original object unchanged. Here are some commonly used data type conversion functions:
| Function | Description |
|---|---|
int(x [, base]) |
Converts x to an integer. If x is a string, the optional base specifies the numeral system (e.g., base 2 for binary, base 16 for hex). |
float(x) |
Converts x to a floating-point number. |
complex(real [, imag]) |
Creates a complex number with the specified real and imaginary parts. |
str(x) |
Converts object x to a string representation. |
repr(x) |
Converts object x to a string that can often be used with eval() to recreate the object. |
eval(str) |
Evaluates a valid Python expression string and returns the resulting object. |
tuple(s) |
Converts a sequence s to a tuple. |
list(s) |
Converts a sequence s to a list. |
set(s) |
Converts an iterable s to a set (removes duplicates). |
frozenset(s) |
Converts an iterable s to an immutable set. |
dict(d) |
Creates a dictionary; d can be a sequence of key–value pairs (e.g., list of tuples). |
chr(x) |
Converts an integer (Unicode code point) to the corresponding character. |
ord(x) |
Converts a single character to its integer Unicode code point. |
hex(x) |
Converts an integer to a lowercase hexadecimal string (prefixed with 0x). |
oct(x) |
Converts an integer to an octal string (prefixed with 0o). |
In [2]:
# Type conversion examples in Python 3
# Integer conversion
print(int("1010", 2)) # Binary to decimal -> 10
print(int(3.7)) # Float to int (truncates) -> 3
# Float conversion
print(float("2.75")) # -> 2.75
# Complex number
print(complex(3, 4)) # -> (3+4j)
# String conversion
print(str(123)) # -> '123'
print(repr([1, 2, 3])) # -> '[1, 2, 3]'
# Tuple, list, and set
print(tuple([1, 2, 3])) # -> (1, 2, 3)
print(list("AI")) # -> ['A', 'I']
print(set([1, 1, 2])) # -> {1, 2}
# Dictionary
print(dict([('a', 1), ('b', 2)])) # -> {'a': 1, 'b': 2}
# Character and Unicode
print(chr(97)) # -> 'a'
print(ord('A')) # -> 65
# Number base conversions
print(hex(255)) # -> '0xff'
print(oct(8)) # -> '0o10'
10
3
2.75
(3+4j)
123
[1, 2, 3]
(1, 2, 3)
['A', 'I']
{1, 2}
{'a': 1, 'b': 2}
a
65
0xff
0o10