When working with Python, you might come across situations where you need to perform calculations with complex numbers.
A complex number is a number of the form a + bi
, where a
and b
are real numbers, and i
represents the imaginary unit, with the property i^2 = -1
. In this tutorial, we will learn how to print complex numbers in Python, as well as some basic operations to deal with them.
Step 1: Representing Complex Numbers in Python
Python provides a built-in data type called complex to represent complex numbers. You can create a complex number by using the complex()
function or by directly writing the number in the form of a + bj
, where ‘a’ and ‘b’ are real numbers, and ‘j’ is the imaginary unit.
1 2 3 4 |
z1 = complex(2, 3) z2 = 3 + 4j print(z1) print(z2) |
Output:
(2+3j) (3+4j)
Step 2: Accessing Real and Imaginary Parts
When you have a complex number, you can access its real and imaginary parts using the real
and imag
attributes, respectively.
1 2 3 4 |
z = 2 + 3j real_part = z.real imaginary_part = z.imag print(real_part, imaginary_part) |
Output:
2.0 3.0
Step 3: Basic Operations with Complex Numbers
Python allows you to perform basic arithmetic operations with complex numbers, such as addition, subtraction, multiplication, and division.
1 2 3 4 5 6 7 8 9 10 11 12 |
z1 = 2 + 3j z2 = 3 + 4j add = z1 + z2 sub = z1 - z2 mul = z1 * z2 div = z1 / z2 print(add) print(sub) print(mul) print(div) |
Output:
(5+7j) (-1-1j) (-6+17j) (0.72+0.04j)
Step 4: Formatting Complex Numbers for Printing
To print complex numbers in a more readable format, you can use formatted string literals or str.format()
method.
Using formatted string literals (f-strings):
1 2 |
z = 2 + 3j print(f"The complex number is {z.real} + {z.imag}j") |
Output:
The complex number is 2.0 + 3.0j
Using str.format()
:
1 2 |
z = 2 + 3j print("The complex number is {} + {}j".format(z.real, z.imag)) |
Output:
The complex number is 2.0 + 3.0j
Full Code
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 |
# Representing complex numbers z1 = complex(2, 3) z2 = 3 + 4j print(z1) print(z2) # Accessing real and imaginary parts z = 2 + 3j real_part = z.real imaginary_part = z.imag print(real_part, imaginary_part) # Basic operations with complex numbers z1 = 2 + 3j z2 = 3 + 4j add = z1 + z2 sub = z1 - z2 mul = z1 * z2 div = z1 / z2 print(add) print(sub) print(mul) print(div) # Formatting complex numbers for printing z = 2 + 3j print(f"The complex number is {z.real} + {z.imag}j") print("The complex number is {} + {}j".format(z.real, z.imag)) |
Conclusion
Now you know how to represent, print, and perform basic operations with complex numbers in Python. Remember to use the complex
data type and the handy real and imaginary attributes to make working with complex numbers easier.