Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
problem with complex number
#1
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"
Reply
#2
Turn the input str into a complex number using complex
https://docs.python.org/3/library/functi...ex#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
.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Problem with "Number List" problem on HackerRank Pnerd 5 2,084 Apr-12-2022, 12:25 AM
Last Post: Pnerd
  number accuracy problem? roym 5 1,821 Dec-24-2021, 07:57 AM
Last Post: roym
  Problem : Count the number of Duplicates NeedHelpPython 3 4,361 Dec-16-2021, 06:53 AM
Last Post: Gribouillis
  P3, openpyxl, csv to xlsx, cell is not number, problem with colorize genderbee 1 2,128 Sep-29-2020, 03:20 PM
Last Post: Larz60+
  can't figure out problem with number guess Galoxys 4 3,338 Oct-29-2018, 01:45 PM
Last Post: snippsat
  Prime number Script Problem Codezters 4 4,044 Jul-21-2017, 03:07 AM
Last Post: Larz60+
  Number logic problem m1xzg 13 10,678 Oct-23-2016, 09:36 PM
Last Post: m1xzg

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020