Python Boolean & Complex Data Types - Complete Guide
Welcome! This guide will teach you about BOOLEAN and COMPLEX data types in Python.
You'll learn:
- Boolean (bool) - True/False values
- Complex (complex) - Numbers with real and imaginary parts
- How to use them in your programs
- Common patterns and best practices
Let's dive deep! π
Part 1: Boolean Data Type (bool)
π What is Boolean? Boolean is a data type that represents LOGICAL VALUES:
- True (something is true/correct/yes)
- False (something is false/incorrect/no)
Think of it like a light switch:
- True = Light is ON (1)
- False = Light is OFF (0)
Boolean values are used for:
- Making decisions (if conditions)
- Checking if something exists
- Comparing values
- Controlling program flow
Creating Boolean Values
is_active = True is_deleted = False Type of is_active: <class 'bool'> Type of is_deleted: <class 'bool'>
β οΈ IMPORTANT: Case Sensitivity! In Python, Boolean values MUST start with capital letters: β True (capital T) β False (capital F)
β true (small t) - ERROR! β false (small f) - ERROR!
Python will give you an error if you use lowercase!
β Correct usage: is_valid = True is_empty = False
Boolean as Numeric Values
Interesting fact: In Python, Boolean values have numeric equivalents:
- True = 1 (one)
- False = 0 (zero)
BUT: You CANNOT use 1 in place of True or 0 in place of False! They are different types, even though they have the same value.
a = True int(a) = 1 int(b) = 0
Type of True: <class 'bool'> Type of 1: <class 'int'> Even though True = 1, they are different types!
bool(1) = True bool(0) = False bool(42) = True bool(-5) = True
Boolean from Comparisons
When you compare values, you get Boolean results:
- Is 5 less than 10? β True
- Is 5 equal to 10? β False
- Is 5 greater than 10? β False
A = 5, B = 10 A < B (A is less than B): True A > B (A is greater than B): False A == B (A equals B): False A != B (A not equals B): True
Converting Other Values to Boolean
You can convert almost anything to Boolean using bool():
- Numbers: 0 = False, everything else = True
- Strings: Empty string "" = False, everything else = True
- Lists: Empty list [] = False, everything else = True
- None: Always False
Numbers: bool(0) = False bool(1) = True bool(100) = True bool(-5) = True
Strings: bool('') = False bool('Hello') = True bool(' ') = True
Lists: bool([]) = False bool([1, 2]) = True
None: bool(None) = False
Practical Examples: Using Boolean
User logged in: True
Feature enabled: False
Age: 20, Is adult: True
Shopping cart: [] Is cart empty: True Is cart empty (better way): True
Complete Code Snippet for Part 1 (Boolean Data Type (bool)):
print("=" * 70)
print("PART 1: BOOLEAN DATA TYPE (bool)")
print("=" * 70)
# ----------------------------------------------------------------------------
# What is Boolean?
# ----------------------------------------------------------------------------
print("\nπ What is Boolean?")
print("-" * 70)
print("""
Boolean is a data type that represents LOGICAL VALUES:
- True (something is true/correct/yes)
- False (something is false/incorrect/no)
Think of it like a light switch:
- True = Light is ON (1)
- False = Light is OFF (0)
Boolean values are used for:
- Making decisions (if conditions)
- Checking if something exists
- Comparing values
- Controlling program flow
""")
# ----------------------------------------------------------------------------
# Creating Boolean Values
# ----------------------------------------------------------------------------
print("\nπ Creating Boolean Values")
print("-" * 70)
# Direct assignment
is_active = True
is_deleted = False
print(f"is_active = {is_active}")
print(f"is_deleted = {is_deleted}")
print(f"Type of is_active: {type(is_active)}")
print(f"Type of is_deleted: {type(is_deleted)}")
# ----------------------------------------------------------------------------
# β οΈ IMPORTANT: Case Sensitivity!
# ----------------------------------------------------------------------------
print("\nβ οΈ IMPORTANT: Case Sensitivity!")
print("-" * 70)
print("""
In Python, Boolean values MUST start with capital letters:
β
True (capital T)
β
False (capital F)
β true (small t) - ERROR!
β false (small f) - ERROR!
Python will give you an error if you use lowercase!
""")
# Try to see the error (commented out so code runs):
# wrong = true # NameError: name 'true' is not defined
# wrong = false # NameError: name 'false' is not defined
print("β
Correct usage:")
print(" is_valid = True")
print(" is_empty = False")
# ----------------------------------------------------------------------------
# Boolean as Numeric Values
# ----------------------------------------------------------------------------
print("\nπ Boolean as Numeric Values")
print("-" * 70)
print("""
Interesting fact: In Python, Boolean values have numeric equivalents:
- True = 1 (one)
- False = 0 (zero)
BUT: You CANNOT use 1 in place of True or 0 in place of False!
They are different types, even though they have the same value.
""")
# Converting Boolean to Integer
a = True
b = False
print(f"a = {a}")
print(f"int(a) = {int(a)}") # True becomes 1
print(f"int(b) = {int(b)}") # False becomes 0
print(f"\nType of True: {type(True)}")
print(f"Type of 1: {type(1)}")
print("Even though True = 1, they are different types!")
# Converting Integer to Boolean
print(f"\nbool(1) = {bool(1)}") # Any non-zero number = True
print(f"bool(0) = {bool(0)}") # Zero = False
print(f"bool(42) = {bool(42)}") # Any non-zero = True
print(f"bool(-5) = {bool(-5)}") # Even negative = True
# ----------------------------------------------------------------------------
# Boolean from Comparisons
# ----------------------------------------------------------------------------
print("\nπ Boolean from Comparisons")
print("-" * 70)
print("""
When you compare values, you get Boolean results:
- Is 5 less than 10? β True
- Is 5 equal to 10? β False
- Is 5 greater than 10? β False
""")
A = 5
B = 10
print(f"A = {A}, B = {B}")
print(f"A < B (A is less than B): {A < B}") # True
print(f"A > B (A is greater than B): {A > B}") # False
print(f"A == B (A equals B): {A == B}") # False
print(f"A != B (A not equals B): {A != B}") # True
# ----------------------------------------------------------------------------
# Boolean from Other Values
# ----------------------------------------------------------------------------
print("\nπ Converting Other Values to Boolean")
print("-" * 70)
print("""
You can convert almost anything to Boolean using bool():
- Numbers: 0 = False, everything else = True
- Strings: Empty string "" = False, everything else = True
- Lists: Empty list [] = False, everything else = True
- None: Always False
""")
# Numbers
print("Numbers:")
print(f" bool(0) = {bool(0)}")
print(f" bool(1) = {bool(1)}")
print(f" bool(100) = {bool(100)}")
print(f" bool(-5) = {bool(-5)}")
# Strings
print("\nStrings:")
print(f" bool('') = {bool('')}") # Empty string = False
print(f" bool('Hello') = {bool('Hello')}") # Non-empty = True
print(f" bool(' ') = {bool(' ')}") # Even space = True
# Lists
print("\nLists:")
print(f" bool([]) = {bool([])}") # Empty list = False
print(f" bool([1, 2]) = {bool([1, 2])}") # Non-empty = True
# None
print("\nNone:")
print(f" bool(None) = {bool(None)}") # None = False
# ----------------------------------------------------------------------------
# Practical Examples: Using Boolean
# ----------------------------------------------------------------------------
print("\nπ Practical Examples: Using Boolean")
print("-" * 70)
# Example 1: User authentication
is_logged_in = True
print(f"User logged in: {is_logged_in}")
# Example 2: Feature flags
feature_enabled = False
print(f"Feature enabled: {feature_enabled}")
# Example 3: Validation
age = 20
is_adult = age >= 18
print(f"Age: {age}, Is adult: {is_adult}")
# Example 4: Checking if list is empty
shopping_cart = []
is_cart_empty = len(shopping_cart) == 0
print(f"Shopping cart: {shopping_cart}")
print(f"Is cart empty: {is_cart_empty}")
# Better way using bool()
is_cart_empty_v2 = not bool(shopping_cart)
print(f"Is cart empty (better way): {is_cart_empty_v2}")
Part 2: Complex Data Type (complex)
π What are Complex Numbers? Complex numbers are used in mathematics and engineering.
A complex number has TWO parts:
- Real part (regular number)
- Imaginary part (number multiplied by β(-1))
Format: a + bj
- a = real part
- b = imaginary part
- j = β(-1) (square root of negative one)
Example: 3 + 5j
- Real part: 3
- Imaginary part: 5
- This means: 3 + (5 Γ β(-1))
Why 'j' instead of 'i'?
- In mathematics, we use 'i' for β(-1)
- In Python, we use 'j' to avoid confusion
- 'i' is commonly used as a variable name in programming
Mathematical Background (Simple Explanation)
In regular math, you cannot find the square root of a negative number. For example: β(-9) doesn't exist in regular numbers.
But in complex numbers, we say: β(-9) = β(-1 Γ 9) = β(-1) Γ β(9) = i Γ 3 = 3i
So: 25 + β(-9) = 25 + 3i = 25 + 3j (in Python)
This is useful in:
- Engineering calculations
- Signal processing
- Electrical engineering
- Physics
Creating Complex Numbers: Method 1 (Direct)
x = 3 + 5j x = (3+5j)
y = 1.5 + 2.7j y = (1.5+2.7j)
z = 2 + 3J (capital J also works) z = (2+3j)
w = 5 + 0j (only real part) w = (5+0j)
v = 0 + 4j (only imaginary part) v = 4j
β οΈ Important: Python uses 'j', NOT 'i' β wrong = 3 + 5i # SyntaxError! β correct = 3 + 5j
Creating Complex Numbers: Method 2 (complex() function)
complex(3, 5) = (3+5j) Same as: 3 + 5j
complex(1.5, 2.7) = (1.5+2.7j)
complex(12) = (12+0j) When only one argument is given, imaginary part = 0
complex(0, 5) = 5j Real part = 0, imaginary part = 5
Accessing Real and Imaginary Parts
num = 1.22 + 3.55j num.real = 1.22 num.imag = 3.55
π‘ Remember:
- .real β gives real part
- .imag β gives imaginary part (NOT .img!)
More examples: (3+5j) β real: 3.0, imag: 5.0 (10+0j) β real: 10.0, imag: 0.0 7j β real: 0.0, imag: 7.0 (-2+3j) β real: -2.0, imag: 3.0
Operations on Complex Numbers
You can perform basic math operations on complex numbers:
- Addition (+)
- Subtraction (-)
- Multiplication (*)
- Division (/)
(We'll learn more about operators in later lessons)
(3+5j) + (2+1j) = (5+6j) (3+5j) - (2+1j) = (1+4j) (3+5j) * (2+1j) = (1+13j) (3+5j) / (2+1j) = (2.2+1.4j)
Practical Examples: Complex Numbers
Electrical impedance: (5+3j) ohms Real part (resistance): 5.0 ohms Imaginary part (reactance): 3.0 ohms
Point 1: (3.0, 4.0) Point 2: (1.0, 2.0)
Signal amplitude: 11.180339887498949
Complete Code Snippet for Part 2 (Complex Data Type (complex)):
print("\n\n" + "=" * 70)
print("PART 2: COMPLEX DATA TYPE (complex)")
print("=" * 70)
# ----------------------------------------------------------------------------
# What are Complex Numbers?
# ----------------------------------------------------------------------------
print("\nπ What are Complex Numbers?")
print("-" * 70)
print("""
Complex numbers are used in mathematics and engineering.
A complex number has TWO parts:
1. Real part (regular number)
2. Imaginary part (number multiplied by β(-1))
Format: a + bj
- a = real part
- b = imaginary part
- j = β(-1) (square root of negative one)
Example: 3 + 5j
- Real part: 3
- Imaginary part: 5
- This means: 3 + (5 Γ β(-1))
Why 'j' instead of 'i'?
- In mathematics, we use 'i' for β(-1)
- In Python, we use 'j' to avoid confusion
- 'i' is commonly used as a variable name in programming
""")
# ----------------------------------------------------------------------------
# Mathematical Background (Simple Explanation)
# ----------------------------------------------------------------------------
print("\nπ Mathematical Background (Simple Explanation)")
print("-" * 70)
print("""
In regular math, you cannot find the square root of a negative number.
For example: β(-9) doesn't exist in regular numbers.
But in complex numbers, we say:
β(-9) = β(-1 Γ 9) = β(-1) Γ β(9) = i Γ 3 = 3i
So: 25 + β(-9) = 25 + 3i = 25 + 3j (in Python)
This is useful in:
- Engineering calculations
- Signal processing
- Electrical engineering
- Physics
""")
# ----------------------------------------------------------------------------
# Creating Complex Numbers: Method 1 (Direct)
# ----------------------------------------------------------------------------
print("\nπ Creating Complex Numbers: Method 1 (Direct)")
print("-" * 70)
# Basic complex number
x = 3 + 5j
print(f"x = 3 + 5j")
print(f"x = {x}")
print(f"Type of x: {type(x)}")
# With float values
y = 1.5 + 2.7j
print(f"\ny = 1.5 + 2.7j")
print(f"y = {y}")
# With capital J (also works!)
z = 2 + 3J
print(f"\nz = 2 + 3J (capital J also works)")
print(f"z = {z}")
# Only real part (imaginary part is 0)
w = 5 + 0j
print(f"\nw = 5 + 0j (only real part)")
print(f"w = {w}")
# Only imaginary part (real part is 0)
v = 0 + 4j
print(f"\nv = 0 + 4j (only imaginary part)")
print(f"v = {v}")
# β οΈ Important: You CANNOT use 'i' instead of 'j'!
print("\nβ οΈ Important:")
print(" Python uses 'j', NOT 'i'")
print(" β wrong = 3 + 5i # SyntaxError!")
print(" β
correct = 3 + 5j")
# ----------------------------------------------------------------------------
# Creating Complex Numbers: Method 2 (complex() function)
# ----------------------------------------------------------------------------
print("\nπ Creating Complex Numbers: Method 2 (complex() function)")
print("-" * 70)
# Using complex(real, imag)
a = complex(3, 5)
print(f"complex(3, 5) = {a}")
print(f"Same as: 3 + 5j")
# With float values
b = complex(1.5, 2.7)
print(f"\ncomplex(1.5, 2.7) = {b}")
# With only one argument (imaginary part becomes 0)
c = complex(12)
print(f"\ncomplex(12) = {c}")
print("When only one argument is given, imaginary part = 0")
# With zero
d = complex(0, 5)
print(f"\ncomplex(0, 5) = {d}")
print("Real part = 0, imaginary part = 5")
# ----------------------------------------------------------------------------
# Accessing Real and Imaginary Parts
# ----------------------------------------------------------------------------
print("\nπ Accessing Real and Imaginary Parts")
print("-" * 70)
num = 1.22 + 3.55j
print(f"num = {num}")
# Access real part
real_part = num.real
print(f"num.real = {real_part}")
# Access imaginary part
imaginary_part = num.imag
print(f"num.imag = {imaginary_part}")
print("\nπ‘ Remember:")
print(" - .real β gives real part")
print(" - .imag β gives imaginary part (NOT .img!)")
# More examples
print("\nMore examples:")
numbers = [
3 + 5j,
10 + 0j,
0 + 7j,
-2 + 3j
]
for num in numbers:
print(f" {num:10} β real: {num.real:6.1f}, imag: {num.imag:6.1f}")
# ----------------------------------------------------------------------------
# Operations on Complex Numbers
# ----------------------------------------------------------------------------
print("\nπ Operations on Complex Numbers")
print("-" * 70)
print("""
You can perform basic math operations on complex numbers:
- Addition (+)
- Subtraction (-)
- Multiplication (*)
- Division (/)
(We'll learn more about operators in later lessons)
""")
# Addition
c1 = 3 + 5j
c2 = 2 + 1j
result_add = c1 + c2
print(f"({c1}) + ({c2}) = {result_add}")
# Subtraction
result_sub = c1 - c2
print(f"({c1}) - ({c2}) = {result_sub}")
# Multiplication
result_mul = c1 * c2
print(f"({c1}) * ({c2}) = {result_mul}")
# Division
result_div = c1 / c2
print(f"({c1}) / ({c2}) = {result_div}")
# ----------------------------------------------------------------------------
# Practical Examples: Complex Numbers
# ----------------------------------------------------------------------------
print("\nπ Practical Examples: Complex Numbers")
print("-" * 70)
# Example 1: Electrical engineering (impedance)
resistance = 5.0 # Real part
reactance = 3.0 # Imaginary part
impedance = complex(resistance, reactance)
print(f"Electrical impedance: {impedance} ohms")
print(f" Real part (resistance): {impedance.real} ohms")
print(f" Imaginary part (reactance): {impedance.imag} ohms")
# Example 2: 2D coordinates (can be represented as complex)
point1 = 3 + 4j
point2 = 1 + 2j
print(f"\nPoint 1: ({point1.real}, {point1.imag})")
print(f"Point 2: ({point2.real}, {point2.imag})")
# Example 3: Signal processing
signal = complex(10, 5)
print(f"\nSignal amplitude: {abs(signal)}") # abs() gives magnitude
print(f"Signal: {signal}")
Part 3: Common Patterns & Best Practices
Boolean Patterns
Boolean Patterns
name = 'Alice' has_name = True
empty_name = '' has_empty_name = False
Light is on: True After toggle: False After toggle again: True
age = 25, has_license = True can_drive = True
user_input = '' result = 'Default Value' (uses default if empty)
Complex Number Patterns
real = 10, imag = 20 complex_num = (10+20j)
z = 3 + 4j Magnitude (distance from origin) = 5.00
Points: [(1+2j), (3+4j), (5+6j)] Point 1: (1.0, 2.0) Point 2: (3.0, 4.0) Point 3: (5.0, 6.0)
Complete Code Snippet for Part 3 (Common Patterns & Best Practices):
print("\n\n" + "=" * 70)
print("PART 3: COMMON PATTERNS & BEST PRACTICES")
print("=" * 70)
# ----------------------------------------------------------------------------
# Boolean Patterns
# ----------------------------------------------------------------------------
print("\nπ Boolean Patterns")
print("-" * 70)
# Pattern 1: Checking if something exists
name = "Alice"
has_name = bool(name)
print(f"name = '{name}'")
print(f"has_name = {has_name}")
empty_name = ""
has_empty_name = bool(empty_name)
print(f"\nempty_name = '{empty_name}'")
print(f"has_empty_name = {has_empty_name}")
# Pattern 2: Toggle (switch on/off)
is_on = True
print(f"\nLight is on: {is_on}")
is_on = not is_on # Toggle
print(f"After toggle: {is_on}")
is_on = not is_on # Toggle again
print(f"After toggle again: {is_on}")
# Pattern 3: Multiple conditions
age = 25
has_license = True
can_drive = age >= 18 and has_license
print(f"\nage = {age}, has_license = {has_license}")
print(f"can_drive = {can_drive}")
# Pattern 4: Default values
user_input = ""
result = user_input or "Default Value"
print(f"\nuser_input = '{user_input}'")
print(f"result = '{result}' (uses default if empty)")
# ----------------------------------------------------------------------------
# Complex Number Patterns
# ----------------------------------------------------------------------------
print("\nπ Complex Number Patterns")
print("-" * 70)
# Pattern 1: Creating from separate real/imaginary parts
real = 10
imag = 20
complex_num = complex(real, imag)
print(f"real = {real}, imag = {imag}")
print(f"complex_num = {complex_num}")
# Pattern 2: Extracting parts for calculations
z = 3 + 4j
magnitude = (z.real ** 2 + z.imag ** 2) ** 0.5
print(f"\nz = {z}")
print(f"Magnitude (distance from origin) = {magnitude:.2f}")
# Pattern 3: Working with multiple complex numbers
points = [complex(1, 2), complex(3, 4), complex(5, 6)]
print(f"\nPoints: {points}")
for i, point in enumerate(points, 1):
print(f" Point {i}: ({point.real}, {point.imag})")
Part 4: Common Mistakes to Avoid
β MISTAKE 1: Using lowercase true/false wrong = true # NameError! wrong = false # NameError!
β CORRECT: Use capital letters correct = True correct = False
β MISTAKE 2: Using 1/0 instead of True/False if status == 1: # Works, but not Pythonic
β CORRECT: Use Boolean values if status == True: # Better if status: # Best (most Pythonic)
β MISTAKE 3: Using 'i' instead of 'j' for complex wrong = 3 + 5i # SyntaxError!
β CORRECT: Use 'j' correct = 3 + 5j
β MISTAKE 4: Using .img instead of .imag num.img # AttributeError!
β CORRECT: Use .imag num.imag
β MISTAKE 5: Forgetting that empty values are False if my_list: # This checks if list is NOT empty
β CORRECT: Be explicit if len(my_list) > 0: # Clearer if my_list: # Pythonic (shorter)
Complete Code Snippet for Part 4 (Common Mistakes to Avoid):
print("\n\n" + "=" * 70)
print("PART 4: COMMON MISTAKES TO AVOID")
print("=" * 70)
print("""
β MISTAKE 1: Using lowercase true/false
wrong = true # NameError!
wrong = false # NameError!
β
CORRECT: Use capital letters
correct = True
correct = False
β MISTAKE 2: Using 1/0 instead of True/False
if status == 1: # Works, but not Pythonic
β
CORRECT: Use Boolean values
if status == True: # Better
if status: # Best (most Pythonic)
β MISTAKE 3: Using 'i' instead of 'j' for complex
wrong = 3 + 5i # SyntaxError!
β
CORRECT: Use 'j'
correct = 3 + 5j
β MISTAKE 4: Using .img instead of .imag
num.img # AttributeError!
β
CORRECT: Use .imag
num.imag
β MISTAKE 5: Forgetting that empty values are False
if my_list: # This checks if list is NOT empty
β
CORRECT: Be explicit
if len(my_list) > 0: # Clearer
if my_list: # Pythonic (shorter)
""")
Part 5: Practice Exercises
Try solving these exercises to test your understanding!
EXERCISE 1: Boolean Basics
- Create a variable 'is_student' and set it to True
- Create a variable 'is_teacher' and set it to False
- Print both variables and their types
EXERCISE 2: Boolean from Comparisons
- Set x = 10, y = 5
- Check if x > y (should be True)
- Check if x == y (should be False)
- Check if x != y (should be True)
EXERCISE 3: Converting to Boolean
- Convert 0 to boolean (should be False)
- Convert 1 to boolean (should be True)
- Convert empty string "" to boolean (should be False)
- Convert "Hello" to boolean (should be True)
EXERCISE 4: Complex Number Basics
- Create complex number: 5 + 3j
- Print its real part
- Print its imaginary part
- Print its type
EXERCISE 5: Complex Number Creation
- Create complex number using: complex(7, 9)
- Create complex number using: 2.5 + 4.7j
- Create complex number with only real part: complex(10)
- Print all three
EXERCISE 6: Complex Number Operations
- Create c1 = 3 + 4j
- Create c2 = 1 + 2j
- Calculate and print: c1 + c2
- Calculate and print: c1 - c2
- Calculate and print: c1 * c2
EXERCISE 7: Real-World Boolean
- Create variables: age = 20, has_id = True
- Check if person can vote (age >= 18 and has_id)
- Check if person is senior (age >= 65)
- Print both results
EXERCISE 8: Real-World Complex
- Represent a 2D point as complex: point = 5 + 3j
- Extract x-coordinate (real part)
- Extract y-coordinate (imaginary part)
- Print: "Point is at (x, y)"
EXERCISE 9: Boolean Logic
- Set a = True, b = False
- Calculate: a and b (should be False)
- Calculate: a or b (should be True)
- Calculate: not a (should be False)
EXERCISE 10: Complex Magnitude
- Create z = 3 + 4j
- Calculate magnitude: β(realΒ² + imagΒ²)
- Print the magnitude
- (Hint: Use z.real and z.imag)
SOLUTIONS ARE BELOW - Try first, then check!
Complete Code Snippet for Part 5 (Practice Exercises):
print("\n\n" + "=" * 70)
print("PART 5: PRACTICE EXERCISES")
print("=" * 70)
print("""
Try solving these exercises to test your understanding!
EXERCISE 1: Boolean Basics
---------------------------
1. Create a variable 'is_student' and set it to True
2. Create a variable 'is_teacher' and set it to False
3. Print both variables and their types
EXERCISE 2: Boolean from Comparisons
------------------------------------
1. Set x = 10, y = 5
2. Check if x > y (should be True)
3. Check if x == y (should be False)
4. Check if x != y (should be True)
EXERCISE 3: Converting to Boolean
----------------------------------
1. Convert 0 to boolean (should be False)
2. Convert 1 to boolean (should be True)
3. Convert empty string "" to boolean (should be False)
4. Convert "Hello" to boolean (should be True)
EXERCISE 4: Complex Number Basics
---------------------------------
1. Create complex number: 5 + 3j
2. Print its real part
3. Print its imaginary part
4. Print its type
EXERCISE 5: Complex Number Creation
-----------------------------------
1. Create complex number using: complex(7, 9)
2. Create complex number using: 2.5 + 4.7j
3. Create complex number with only real part: complex(10)
4. Print all three
EXERCISE 6: Complex Number Operations
-------------------------------------
1. Create c1 = 3 + 4j
2. Create c2 = 1 + 2j
3. Calculate and print: c1 + c2
4. Calculate and print: c1 - c2
5. Calculate and print: c1 * c2
EXERCISE 7: Real-World Boolean
-------------------------------
1. Create variables: age = 20, has_id = True
2. Check if person can vote (age >= 18 and has_id)
3. Check if person is senior (age >= 65)
4. Print both results
EXERCISE 8: Real-World Complex
-------------------------------
1. Represent a 2D point as complex: point = 5 + 3j
2. Extract x-coordinate (real part)
3. Extract y-coordinate (imaginary part)
4. Print: "Point is at (x, y)"
EXERCISE 9: Boolean Logic
-------------------------
1. Set a = True, b = False
2. Calculate: a and b (should be False)
3. Calculate: a or b (should be True)
4. Calculate: not a (should be False)
EXERCISE 10: Complex Magnitude
------------------------------
1. Create z = 3 + 4j
2. Calculate magnitude: β(realΒ² + imagΒ²)
3. Print the magnitude
4. (Hint: Use z.real and z.imag)
SOLUTIONS ARE BELOW - Try first, then check!
""")
Solutions to Practice Exercises
--- EXERCISE 1: Boolean Basics --- is_student = True, type = <class 'bool'> is_teacher = False, type = <class 'bool'>
--- EXERCISE 2: Boolean from Comparisons --- x > y: True x == y: False x != y: True
--- EXERCISE 3: Converting to Boolean --- bool(0) = False bool(1) = True bool('') = False bool('Hello') = True
--- EXERCISE 4: Complex Number Basics --- z = (5+3j) Real part: 5.0 Imaginary part: 3.0 Type: <class 'complex'>
--- EXERCISE 5: Complex Number Creation --- c1 = (7+9j) c2 = (2.5+4.7j) c3 = (10+0j)
--- EXERCISE 6: Complex Number Operations --- c1 + c2 = (4+6j) c1 - c2 = (2+2j) c1 * c2 = (1+10j)
--- EXERCISE 7: Real-World Boolean --- Age: 20, Has ID: True Can vote: True Is senior: False
--- EXERCISE 8: Real-World Complex --- Point is at (5.0, 3.0)
--- EXERCISE 9: Boolean Logic --- a and b = False a or b = True not a = False
--- EXERCISE 10: Complex Magnitude --- z = (3+4j) Magnitude = 5.00
Complete Code Snippet for Solutions to Practice Exercises:
print("\n\n" + "=" * 70)
print("SOLUTIONS TO PRACTICE EXERCISES")
print("=" * 70)
print("\n--- EXERCISE 1: Boolean Basics ---")
is_student = True
is_teacher = False
print(f"is_student = {is_student}, type = {type(is_student)}")
print(f"is_teacher = {is_teacher}, type = {type(is_teacher)}")
print("\n--- EXERCISE 2: Boolean from Comparisons ---")
x = 10
y = 5
print(f"x > y: {x > y}")
print(f"x == y: {x == y}")
print(f"x != y: {x != y}")
print("\n--- EXERCISE 3: Converting to Boolean ---")
print(f"bool(0) = {bool(0)}")
print(f"bool(1) = {bool(1)}")
print(f"bool('') = {bool('')}")
print(f"bool('Hello') = {bool('Hello')}")
print("\n--- EXERCISE 4: Complex Number Basics ---")
z = 5 + 3j
print(f"z = {z}")
print(f"Real part: {z.real}")
print(f"Imaginary part: {z.imag}")
print(f"Type: {type(z)}")
print("\n--- EXERCISE 5: Complex Number Creation ---")
c1 = complex(7, 9)
c2 = 2.5 + 4.7j
c3 = complex(10)
print(f"c1 = {c1}")
print(f"c2 = {c2}")
print(f"c3 = {c3}")
print("\n--- EXERCISE 6: Complex Number Operations ---")
c1 = 3 + 4j
c2 = 1 + 2j
print(f"c1 + c2 = {c1 + c2}")
print(f"c1 - c2 = {c1 - c2}")
print(f"c1 * c2 = {c1 * c2}")
print("\n--- EXERCISE 7: Real-World Boolean ---")
age = 20
has_id = True
can_vote = age >= 18 and has_id
is_senior = age >= 65
print(f"Age: {age}, Has ID: {has_id}")
print(f"Can vote: {can_vote}")
print(f"Is senior: {is_senior}")
print("\n--- EXERCISE 8: Real-World Complex ---")
point = 5 + 3j
x = point.real
y = point.imag
print(f"Point is at ({x}, {y})")
print("\n--- EXERCISE 9: Boolean Logic ---")
a = True
b = False
print(f"a and b = {a and b}")
print(f"a or b = {a or b}")
print(f"not a = {not a}")
print("\n--- EXERCISE 10: Complex Magnitude ---")
z = 3 + 4j
magnitude = (z.real ** 2 + z.imag ** 2) ** 0.5
print(f"z = {z}")
print(f"Magnitude = {magnitude:.2f}")
Summary
β BOOLEAN (bool):
- Values: True, False (capital letters!)
- True = 1, False = 0 (numeric equivalent)
- Used for logical decisions and conditions
- Can convert other types to boolean with bool()
- Empty values (0, "", [], None) = False
- Non-empty values = True
β COMPLEX (complex):
- Format: a + bj (uses 'j', not 'i')
- Has real part and imaginary part
- Create with: 3 + 5j or complex(3, 5)
- Access parts: .real and .imag
- Used in engineering, math, and signal processing
- Can perform arithmetic operations
π‘ KEY TAKEAWAYS:
- Always use True/False (capital letters) for Boolean
- Use 'j' (not 'i') for complex numbers
- Use .real and .imag (not .img) to access complex parts
- Boolean values help make decisions in programs
- Complex numbers are useful for advanced calculations
π― NEXT STEPS:
- Practice creating Boolean and Complex values
- Try converting different types to Boolean
- Experiment with complex number operations
- Use Boolean values in if conditions (we'll learn this soon!)
Complete Code Snippet for Summary:
print("\n\n" + "=" * 70)
print("SUMMARY")
print("=" * 70)
print("""
β
BOOLEAN (bool):
- Values: True, False (capital letters!)
- True = 1, False = 0 (numeric equivalent)
- Used for logical decisions and conditions
- Can convert other types to boolean with bool()
- Empty values (0, "", [], None) = False
- Non-empty values = True
β
COMPLEX (complex):
- Format: a + bj (uses 'j', not 'i')
- Has real part and imaginary part
- Create with: 3 + 5j or complex(3, 5)
- Access parts: .real and .imag
- Used in engineering, math, and signal processing
- Can perform arithmetic operations
π‘ KEY TAKEAWAYS:
1. Always use True/False (capital letters) for Boolean
2. Use 'j' (not 'i') for complex numbers
3. Use .real and .imag (not .img) to access complex parts
4. Boolean values help make decisions in programs
5. Complex numbers are useful for advanced calculations
π― NEXT STEPS:
- Practice creating Boolean and Complex values
- Try converting different types to Boolean
- Experiment with complex number operations
- Use Boolean values in if conditions (we'll learn this soon!)
""")
print("\n" + "=" * 70)
print("Congratulations! You've learned Boolean and Complex data types! π")
print("=" * 70)
Congratulations! You've learned Boolean and Complex data types! π