A few years ago, I worked on a small signal-analysis script for a Chicago engineering team. The input data included values such as 12+5j, and the script needed to calculate magnitudes, phase angles, and combined signals. Regular integers and floats were not enough.
That is where Python’s built-in complex() function becomes useful. It creates complex numbers, numbers with a real part and an imaginary part—without installing any module or library.
In this guide, I’ll show you how to use the Python complex() function, read its output, perform calculations, handle string input safely, and avoid the mistakes I see most often.
What Is the Python complex() Function?
The Python complex() function creates a complex number. A complex number contains two parts:
- A real part, such as
10 - An imaginary part, such as
4j
Python uses the letter j for the imaginary unit. In mathematics, you may often see i, but Python reserves j for imaginary values.
The basic format looks like this:
complex(real, imaginary)
Here:
realis the real portion of the number.imaginaryis the imaginary portion of the number.- Both arguments are optional in some cases.
For example, this code creates a complex number for a sample electrical signal:
signal = complex(12, 5)
print(signal)
Output:
(12+5j)
I executed the above example code and added the screenshot below.
The value (12+5j) means:
12+5j12 + 5j12+5j
You can also write the same value directly in Python:
signal = 12 + 5j
print(signal)
Output:
(12+5j)
Both approaches work. I usually use complex() when I receive the real and imaginary values separately, such as from a CSV file, API response, user input, or sensor record.
If you are still getting comfortable with Python values, start with this guide on Python variables. It helps you understand how Python stores numbers and other data types.
Python complex() Function Syntax
The Python complex() function supports two common syntax patterns.
complex()
complex(real, imaginary)
You can also pass a single string:
complex(string)
Create an Empty Complex Number
Calling complex() without values returns zero as both parts.
value = complex()
print(value)
Output:
0j
Python displays 0j instead of (0+0j), but both represent the same value.
This approach is useful when you need an initial value before adding complex results in a loop.
total_signal = complex()
readings = [2 + 3j, 4 - 1j, 6 + 2j]
for reading in readings:
total_signal += reading
print(total_signal)
Output:
(12+4j)
The script starts with 0j, then adds every sensor reading. This pattern works well in small automation scripts that process batches of values.
Create a Complex Number With Real and Imaginary Parts
The most readable use of complex() passes two numeric arguments.
customer_score = complex(85, 12)
print(customer_score)
Output:
(85+12j)
I executed the above example code and added the screenshot below.
The first value becomes the real part. The second value becomes the imaginary part.
Here is another example where a New York data analyst stores a pair of calculated values together:
revenue_change = 1250.75
forecast_adjustment = -220.50
financial_value = complex(revenue_change, forecast_adjustment)
print(financial_value)
Output:
(1250.75-220.5j)
This does not mean Python treats the imaginary value as currency. It only shows how complex() combines two numeric values into one complex object.
Pro Tip: I have found that
complex(real, imaginary)is much easier to maintain than manually building values likereal + imaginary * 1j. It clearly tells the next developer what each number represents.
Use complex() With Strings
You can pass one valid complex-number string to the Python complex() function.
customer_input = "14+7j"
value = complex(customer_input)
print(value)
Output:
(14+7j)
This is useful when your automation receives a value from a text file, command-line prompt, spreadsheet export, or API payload.
For example, imagine a Dallas-based technician exports equipment readings as text:
equipment_reading = "8-3j"
signal = complex(equipment_reading)
print(signal)
Output:
(8-3j)
Python accepts common formats such as these:
print(complex("10+4j"))
print(complex("10-4j"))
print(complex("6j"))
print(complex("25"))
Output:
(10+4j)
(10-4j)
6j
(25+0j)
I executed the above example code and added the screenshot below.
Notice the final result. Python adds 0j when a string contains only a real number.
Handle Invalid Complex Strings
A string must follow Python’s complex-number format. If it does not, complex() raises a ValueError. An exception is an error event that interrupts normal program execution.
value = complex("10 + 4j")
print(value)
Output:
ValueError: complex() arg is a malformed string
The spaces make the input invalid. In real scripts, never assume data is clean. Use exception handling to stop one bad record from crashing the whole process.
raw_value = "10 + 4j"
try:
value = complex(raw_value)
print(f"Converted value: {value}")
except ValueError:
print(f"Invalid complex number: {raw_value}")
Output:
Invalid complex number: 10 + 4j
If you want to strengthen your error-handling skills, read this guide on catching multiple exceptions in Python.
Access Real and Imaginary Parts
Each Python complex number includes two useful attributes:
.realreturns the real part..imagreturns the imaginary part.
An attribute is a value attached to an object. In this case, the complex number object stores both portions for you.
signal = complex(18, -6)
print(f"Complex value: {signal}")
print(f"Real part: {signal.real}")
print(f"Imaginary part: {signal.imag}")
Output:
Complex value: (18-6j)
Real part: 18.0
Imaginary part: -6.0
Python returns the values as floats, even if you originally passed integers.
This example processes a sample radio signal for a Seattle monitoring script:
radio_signal = complex(24, 9)
real_component = radio_signal.real
imaginary_component = radio_signal.imag
print(f"Real component: {real_component}")
print(f"Imaginary component: {imaginary_component}")
Output:
Real component: 24.0
Imaginary component: 9.0
You can use those values in other calculations, format them for reports, or store them in a dictionary. Learn more about storing structured values in this article on how to initialize a dictionary in Python.
Perform Calculations With complex() Values
Complex numbers support standard arithmetic operations:
- Addition with
+ - Subtraction with
- - Multiplication with
* - Division with
/ - Exponents with
**
You do not need a separate module. Python handles the math directly.
Add and Subtract Complex Numbers
Here is a complete example using two signal readings from a Boston lab:
morning_signal = complex(10, 4)
afternoon_signal = complex(6, -2)
combined_signal = morning_signal + afternoon_signal
difference = morning_signal - afternoon_signal
print(f"Combined signal: {combined_signal}")
print(f"Difference: {difference}")
Output:
Combined signal: (16+2j)
Difference: (4+6j)
Python adds and subtracts the real and imaginary parts separately.
For addition:
(10+4j)+(6−2j)=16+2j(10 + 4j) + (6 – 2j) = 16 + 2j(10+4j)+(6−2j)=16+2j
Multiply Complex Numbers
Multiplication is especially useful in signal processing, electrical engineering, and scientific calculations.
signal_a = complex(3, 2)
signal_b = complex(1, 4)
result = signal_a * signal_b
print(result)
Output:
(-5+14j)
Python handles the imaginary-number rules automatically. You do not need to calculate j² = -1 yourself.
Divide Complex Numbers
You can also divide one complex value by another.
input_signal = complex(10, 6)
reference_signal = complex(2, 1)
ratio = input_signal / reference_signal
print(ratio)
Output:
(5.2+0.4j)
Division becomes important when you compare a measured value against a reference value in a data-processing script.
Pro Tip: In my experience, complex arithmetic is reliable, but I always test division with realistic values first. A zero denominator still causes a
ZeroDivisionError, just like regular numeric division.
Find Magnitude and Conjugate Values
Complex-number work often involves a few useful operations beyond regular arithmetic.
Find the Magnitude With abs()
The magnitude is the distance of a complex number from zero. You can calculate it with Python’s built-in abs() function.
signal = complex(3, 4)
magnitude = abs(signal)
print(magnitude)
Output:
5.0
Python calculates the magnitude using this formula:
real2+imaginary2\sqrt{real^2 + imaginary^2}real2+imaginary2​
For (3+4j), the result is:
32+42=5\sqrt{3^2 + 4^2} = 532+42​=5
Here is a practical script that flags weak readings:
signals = [3 + 4j, 1 + 1j, 8 - 6j]
for signal in signals:
strength = abs(signal)
print(f"Signal: {signal}, Strength: {strength:.2f}")
Output:
Signal: (3+4j), Strength: 5.00
Signal: (1+1j), Strength: 1.41
Signal: (8-6j), Strength: 10.00
The .2f format rounds the display to two decimal places. For more formatting examples, see how to format decimal places with Python f-strings.
Find the Conjugate With conjugate()
A conjugate keeps the real part but reverses the sign of the imaginary part.
signal = complex(7, 5)
conjugate_signal = signal.conjugate()
print(conjugate_signal)
Output:
(7-5j)
This operation is common in engineering calculations and advanced data analysis. You may use it when multiplying complex values to remove the imaginary part.
signal = complex(7, 5)
result = signal * signal.conjugate()
print(result)
Output:
(74+0j)
The result equals:
72+52=747^2 + 5^2 = 7472+52=74
Although Python displays +0j, the result behaves like a real-number value stored as a complex number.
Build a Small Complex Number Calculator
Let’s combine the key ideas into a small command-line calculator. A command-line app runs in a terminal and accepts input through the keyboard.
This script asks a user for two complex values, adds them, and shows the real part, imaginary part, and magnitude.
def read_complex_number(prompt):
while True:
raw_value = input(prompt).strip()
try:
return complex(raw_value)
except ValueError:
print("Enter a valid value such as 10+4j, 8-2j, or 5j.")
first_value = read_complex_number("Enter the first complex number: ")
second_value = read_complex_number("Enter the second complex number: ")
total = first_value + second_value
print("\n--- Calculation Result ---")
print(f"First value: {first_value}")
print(f"Second value: {second_value}")
print(f"Sum: {total}")
print(f"Real part: {total.real}")
print(f"Imaginary part: {total.imag}")
print(f"Magnitude: {abs(total):.2f}")
Sample Output:
Enter the first complex number: 12+5j
Enter the second complex number: 3-2j
--- Calculation Result ---
First value: (12+5j)
Second value: (3-2j)
Sum: (15+3j)
Real part: 15.0
Imaginary part: 3.0
Magnitude: 15.30
The read_complex_number() function keeps the input validation in one place. It loops until the user enters a valid value. That makes the main part of the script clean and easier to extend.
If you need a refresher on creating reusable functions, see this guide on how to define a function in Python.
Things to Keep in Mind
- Use
j, noti: Python represents the imaginary unit with lowercasej. Writing10+5icauses an error because Python does not recognizeias an imaginary suffix. - Do not add spaces in string input:
complex("10+4j")works, butcomplex("10 + 4j")raises aValueError. - Expect float attributes: The
.realand.imagattributes return floats, even when you create the number with integers. - Validate external input: Always wrap
complex()intryandexcept ValueErrorwhen you read values from users, files, forms, or APIs. - Avoid zero division: Check the divisor before dividing complex values. Dividing by
0jraises aZeroDivisionError. - Use complex values only when needed: For ordinary prices, counts, dates, and measurements, stick with integers, floats, or the appropriate data type. Complex numbers solve specific math problems.
Frequently Asked Questions
What does complex() do in Python?
The Python complex() function creates a complex number with a real and imaginary part. For example, complex(4, 3) returns (4+3j). You can use it in mathematical, engineering, and signal-processing calculations.
How do I create a complex number in Python?
Use complex(real, imaginary) or write the value directly with j. For example, complex(5, 2) and 5 + 2j both create (5+2j). Use complex() when your parts come from separate values.
Can complex() convert a string in Python?
Yes, complex() can convert valid text such as "10+5j" or "8-3j". The string must not contain spaces inside the number. Invalid text raises a ValueError.
Why does Python use j for complex numbers?
Python uses j as the imaginary suffix, so 4+2j represents a complex number. This convention avoids conflicts with common variable names such as i. You should always use lowercase j in Python code.
How do I get the real and imaginary parts of a complex number?
Use the .real and .imag attributes. For example, (8+3j).real returns 8.0, while (8+3j).imag returns 3.0. These values are useful when you need to display or process each component separately.
How do I find the magnitude of a complex number in Python?
Use the built-in abs() function. For example, abs(3+4j) returns 5.0. Python calculates the magnitude from the real and imaginary parts automatically.
The Python complex() function gives you a clean way to create, inspect, calculate, and validate complex numbers in everyday Python scripts. Start with complex(real, imaginary), validate text input when needed, and use .real, .imag, abs(), and conjugate() as your calculations grow.
You May Also Like
- Understand complex numbers in Python
- Explore Python built-in functions
- Learn the Python round() function
- Use the Python pow() method
- Understand floating-point numbers in Python
Bijay Kumar is an experienced Python and AI professional who enjoys helping developers learn modern technologies through practical tutorials and examples. His expertise includes Python development, Machine Learning, Artificial Intelligence, automation, and data analysis using libraries like Pandas, NumPy, TensorFlow, Matplotlib, SciPy, and Scikit-Learn. At PythonGuides.com, he shares in-depth guides designed for both beginners and experienced developers. More about us.