首页 > 解决方案 > 如何解决 TypeError:'float' 对象在 python 中不可迭代

问题描述

我正在尝试创建一个使用二次公式求解 x 的代码。对于输出,我不希望它显示虚数……只有实数。我将平方根内的值设置为等于名为“root”的变量,以确定该值是否为 pos/neg(如果为 neg,则解决方案将是虚构的)。

这是代码。

import math

print("Solve for x when ax^2 + bx + c = 0")

a = float(input("Enter a numerical value for a: "))
b = float(input("Enter a numerical value for b: "))
c = float(input("Enter a numerical value for c: "))

root = math.pow(b,2) - 4*a*c

root2 = ((-1*b) - math.sqrt(root)) / (2*a)
root1 = ((-1*b) + math.sqrt(root)) / (2*a)

for y in root1:
    if root>=0:
        print("x =", y)       
    elif root<0:
        print('x is an imaginary number')

for z in root2:
    if root>=0:
        print("or x =", z)
    elif root<0:
        print('x is an imaginary number')

这是错误代码:

  File "/Users/e/Documents/Intro Python 2020/Project 1/Project 1 - P2.py", line 25, in <module>
    for y in root1:

TypeError: 'float' object is not iterable

错误发生在以下行:

for y in root1:

如何修复此错误?

标签: pythontypeerroriterable

解决方案


我知道你在这里使用二次方程。可迭代对象类似于列表。具有超过 1 个元素的变量。在你的例子中

root1 是单个浮点值。root2 也是一个浮点值。出于您的目的,您不需要任何带有“for”的行。尝试删除 for y 和 for z 行并运行您的代码。

为了帮助您理解,浮点值只是一个带有小数的数字。


推荐阅读