-1

I am trying to convert a float which has an integer value into a int, so it doesn't look like e.g 5.0.

#Quadratic calculator
import math

def is_int(x):
    x = float(x)
    if x.is_integer():
        a = int(x)
        return a
    else:
        pass

print("Quadratic Equation: ax^2 + bx + c = 0" )
a = float(input("a: "))
b = float(input("b: "))
c = float(input("c: "))
if a.is_integer():
    a = int(a)
else:
    pass
is_int(b)

print(str(a)+"x + "+str(b)+"x + "+ str(c)+ " = 0")

result=[]
result.append(-b+((b**2)-(4*a*c)**0.5)/(2*a))
result.append(-b-((b**2)-(4*a*c)**0.5)/(2*a))
print("x: " + str(result[0]) + " or " + "x: " + str(result[1]))

The result is:

Quadratic Equation: ax^2 + bx + c = 0
a: 2
b: 5
c: 1
2x + 5.0x + 1.0 = 0
x: 0.5428932188134521 or x: -10.542893218813452

Is there another way of doing this?

martineau
  • 119,623
  • 25
  • 170
  • 301

4 Answers4

2

you could work a bit on yout is_int function:

def is_int(x):
    x = float(x)
    if x.is_integer():
        return int(x)
     return x

and then just use in your code:

a = is_int(a)
b = isint(b)
c = is_int(c)
kederrac
  • 16,819
  • 6
  • 32
  • 55
1
  1. First, simplify your is_int method, and make it return a value and is_integer() is false

    def is_int(x):
        x = float(x)
        if x.is_integer():
            return int(x)
        return x
    
  2. use it directly at the input place

    a = is_int(input("a: "))
    b = is_int(input("b: "))
    c = is_int(input("c: "))
    

Out

Quadratic Equation: ax^2 + bx + c = 0
a: 2.5
b: 5
c: 1.4
2.5x + 5x + 1.4 = 0
x: -0.748331477354788 or x: -9.251668522645211
azro
  • 53,056
  • 7
  • 34
  • 70
1

Look duplicate question Formatting floats without trailing zeros.

Use :g format for string

print('{a:g}x2 + {b:g}x + {c:g} = 0'.format(a=a,b=b,c=c))

Out

>>> a=5.0
>>> b=3.0
>>> c=4.0
>>> print('{a:g}x² + {b:g}x + {c:g} = 0'.format(a=a,b=b,c=c))
5x² + 3x + 4 = 0
>>> 
eri
  • 3,133
  • 1
  • 23
  • 35
  • Yes, this method is better than function and much simpler, thank u. But how did u get that x squared output? – MLG Guardian Mar 15 '20 at 20:30
  • Just unicode char. I using hotkey, but you also can google common characters `Unicode Character 'SUPERSCRIPT TWO' ` – eri Mar 16 '20 at 00:27
0

I would simply your is_int function into a one line like this:

def is_int(x):
    return int(x) if float(x).is_integer() else float(x)
marcos
  • 4,473
  • 1
  • 10
  • 24
  • @MLGGuardian It's very simple, it will return the `int` version of `x` if it is an `int` if not it will return the `float` version. You can try it. – marcos Mar 15 '20 at 20:31