0

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?

4
  • 3
    Why are you trying to iterate over a float? Commented Apr 10, 2020 at 23:41
  • 1
    What are you trying to do with for y in root1 exactly? Commented Apr 10, 2020 at 23:41
  • Uhhh I don't even know what I'm doing so I don't know what it means to be iterating over a float. I thought using a for loop would let me use the if statement? I don't know. :) Commented Apr 10, 2020 at 23:43
  • You don't need a for loop to use an if statement. Remove the for loops and you should be fine. Commented Apr 10, 2020 at 23:44

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.