Booleans in Python¶
- 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
Number in Python¶
- Numbers in Python come in different types, including integers, floating-point numbers, and complex numbers.
- Python supports four different numerical types :
- int (signed integers)
- long (long integers, they can also be represented in octal and hexadecimal)
- float (floating point real values)
- complex (complex numbers)
int | long | float | complex |
---|---|---|---|
5 | 51924361L | 0.0 | 3.14j |
5 | -0x19323L | 15.20 | 45.j |
-9 | 0122L | -21.9 | 9.322e-36j |
090 | 0xDEFABCECBDAECBFBAEl | 32.3+e18 | .876j |
-0290 | 535633629843L | -90. | -.6545+0J |
-0x160 | -052318172735L | -32.54e100 | 3e+26J |
0x64 | -4721885298529L | 70.2-E12 | 4.53e-7j |
Python allows you to use a lowercase l with long, but it is recommended that you use only an uppercase L to avoid confusion with the number. Python displays long integers with an uppercase L.
A complex number consists of an ordered pair of real floating-point numbers denoted by x + yj, where x and y are the real numbers and j is the imaginary unit.
In [ ]:
# int
a = 1
#Float
b = 1.65
# Float can also be scientific numbers with an "e" to indicate the power of 10.
c = 40e1
#Complex
d = 1+2j
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. base specifies the base if x is a string. |
long(x [,base] ) | Converts x to a long integer. base specifies the base if x is a string. |
float(x) | Converts x to a floating-point number. |
complex(real [,imag]) | Creates a complex number. |
str(x) | Converts object x to a string representation. |
repr(x) | Converts object x to an expression string. |
eval(str) | Evaluates a string and returns an object. |
tuple(s) | Converts s to a tuple. |
list(s) | Converts s to a list. |
set(s) | Converts s to a set. |
dict(d) | Creates a dictionary. d must be a sequence of (key,value) tuples. |
frozenset(s) | Converts s to a frozen set. |
chr(x) | Converts an integer to a character. |
unichr(x) | Converts an integer to a Unicode character. |
ord(x) | Converts a single character to its integer value. |
hex(x) | Converts an integer to a hexadecimal string. |
oct(x) | Converts an integer to an octal string. |