【问题标题】:Python 3 TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int'Python 3 TypeError:** 或 pow() 不支持的操作数类型:'str' 和 'int'
【发布时间】:2017-04-25 13:20:47
【问题描述】:
#Import the module
from math import sqrt

#Using while loop statement to make the program not finish before the user close the program.
while True:

#Print out the introduction message, and get the input value to solve the quadratic equation.
    print("ax^2+bx+c=0의 꼴로 된 방정식을 풀 수 있습니다. a, b, c의 값을 차례대로 입력하세요.")
    a = input("a를 입력하세요 : ")
    b = input("b를 입력하세요 : ")
    c = input("c를 입력하세요 : ")

#Define function that checks whether the input values are natural number or negative number
    def func_num(n):
        if n[0] == '-':
            n = -int(n[1:])
        else:
            n = int(n)

#Execute the function for the input value a, b, c
    func_num(a); func_num(b); func_num(c);

#This if statement chekcs whether the solution of the quadratic equation going to be real number or imaginary number.
    if b ** 2 < 4*a*c:
        solution1 = ((sqrt((b ** 2)-(4*a*c)))-b) / (2*a)
        solution2 = (-(sqrt((b ** 2)-(4*a*c)))-b) / (2*a)
    else:
        square_root = sqrt( -(b**2 - 4*a*c) ) + 1j
        solution1 = ( (square_root)  - b  ) / (2*a)
        solution2 = ( -(square_root)  - b  ) / (2*a)

#Prints out the solution of the quadratic equation.
    print("정답은 바로바로... {}, {} 이거다!".format(solution1, solution2))

但它给出了错误(对于任何整数输入 a、b、c):

Python 3 TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int'

我认为问题与 func_num() 有关(因为当我使用数字和字符串进行计算时会发生错误)

但我还是找不到哪一部分错了。

【问题讨论】:

  • 您的论点是str,因为您没有解析它。看看如何将输入解析为数字类型。
  • @DJV 但我确实使用 int() 将其转换为整数(在 if 语句中)
  • 您对func_num() 的调用将用户键入的字符串转换为整数 - 然后将它们丢弃。您需要实际返回转换后的值,并将它们分配回您的 a、b、c 变量。
  • @jasonharper 我使用n = -int(n[1:]) 和n = int(n) 为变量n 分配新值。这段代码错了吗?如果是这样,为什么会出错?

标签: python python-3.x python-3.5


【解决方案1】:

出现类型错误的原因是你调用函数后没有存储和更新变量。

试试

 a = func_num(a)
 b = func_num(b)
 c = func_num(c)

并修改你的函数以返回 n,因为你只将副本 n 传递给函数

【讨论】:

  • 我把它改成了a = func_num(a); b = func_num(b); c = func_num(c);,但还是不行。给出同样的错误。
  • 并在函数末尾返回n!
  • 谢谢,它运行良好:) 但是我为什么要使用return n 让它正常运行呢?
  • @장은수 这是因为当你调用函数时,它只是传递一个副本,它与 main 中的值完全无关。当你更新 main 中的值时,函数必须返回一个值,以便你可以将该值分配给变量:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-10-01
  • 2018-02-05
  • 1970-01-01
  • 1970-01-01
  • 2016-04-15
  • 2012-11-29
相关资源
最近更新 更多