Python Forum
problem with complex number - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: problem with complex number (/thread-17496.html)



problem with complex number - jodrickcolina - Apr-13-2019

I have a problem when I wanna work with complex number in python 3, the problem is that I do not know how to convert a string to "complex" when I save a complex number in a variable, for example, the next code:

import math
import cmath
print("calculo de las constantes generalizadas")
Z=input("ingrese el parametro Z ohm/km: ")
Y=input("ingrese el parametro Y siemen/km: ")
g=cmath.sqrt(Z*Y)
print(g)
In Z, I put for example: 5+5j
In Y, I put 2j

and this is the problem:
Error:
Traceback (most recent call last): File "C:/Users/Usuario/AppData/Local/Programs/Python/Python37-32/test.py", line 6, in <module> g=cmath.sqrt(Z*Y) TypeError: can't multiply sequence by non-int of type 'str'
I need to work with complex number but I don't know how to covert str to "complex"


RE: problem with complex number - Yoriz - Apr-13-2019

Turn the input str into a complex number using complex
https://docs.python.org/3/library/functions.html?highlight=complex#complex Wrote:class complex([real[, imag]])
  • Return a complex number with the value real + imag*1j or convert a string or number to a complex number. If the first parameter is a string, it will be interpreted as a complex number and the function must be called without a second parameter. The second parameter can never be a string. Each argument may be any numeric type (including complex). If imag is omitted, it defaults to zero and the constructor serves as a numeric conversion like int and float. If both arguments are omitted, returns 0j.

    Note When converting from a string, the string must not contain whitespace around the central + or - operator. For example, complex('1+2j') is fine, but complex('1 + 2j') raises ValueError.
    The complex type is described in Numeric Types — int, float, complex.

    Changed in version 3.6: Grouping digits with underscores as in code literals is allowed
.