emdelalune
emdelalune

Reputation: 1

How to resolve TypeError: 'float' object is not iterable in python

I'm trying to create a code that will solve for x using the quadratic formula. For the outputs I don't want it to display the imaginary numbers...only real numbers. I set the value inside the square root to equal the variable called "root" to determine if this value would be pos/neg (if it's neg, then the solution would be imaginary).

This is the code.

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')

This is the error code:

  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

The error occurs at the line:

for y in root1:

How do I fix this error?

Upvotes: 0

Views: 983

Answers (2)

Anis R.
Anis R.

Reputation: 6902

Well, the error is pretty self explanatory: you are trying to loop over root1 and root2 which are floats, not lists.

What I believe you wanted to do instead is simply use if/else blocks:

if root >= 0:
    print("x =", root1)
    print("x =", root2)
else:
    print("x is an imaginary number")

Upvotes: 0

Sri
Sri

Reputation: 2318

I understand you are using the quadratic equation here. An iterable is something like a list. A variable with more than 1 element. In your example

root1 is a single float value. root2 is also a single float value. For your purposes, you do not need either lines with the "for". Try removing the for y and for z lines and running your code.

To help you understand, a float value is simply a number that has decimals.

Upvotes: 1

Related Questions