Skip to main content
  • Python is available now. All other compilers are coming soon.

    Python
  • Popular Tutorials

    • Getting Started With Python
    • Python if Statement
    • while Loop in Python
    • Python Lists
    • Dictionaries in Python
    All Python Tutorials

    Reference Materials

    Built-in FunctionsList MethodsDictionary MethodsString Methods
    View all

Online Compilers

  • Python Compiler
  • Python Playground
  • Python Projects
  • Exercises

Tutorials

  • Learn Python
  • Python for Beginners
  • Variables and Types
  • Python Strings
  • Python Lists
  • Python If Else
  • Python For Loops
  • Python Functions
  • Python Classes

Examples

  • Python Examples
  • Hello World
  • Add Two Numbers
  • Even or Odd
  • Factorial
  • Fibonacci
  • Prime Check
  • Palindrome Check

Company

  • About
  • Contact
  • Privacy Policy
  • Terms of Use
  • Disclaimer

© 2026 ILoveCompiler. All rights reserved.

  1. Home
  2. Python Examples
  3. Quadratic Equation Roots

Mathematical Programs · Python example

Quadratic Equation Roots

Use the quadratic formula and math.sqrt to find real roots.

Open the compilerAll examples
intermediatemathformulaconditions

The quadratic formula finds the roots of ax² + bx + c = 0. The discriminant decides how many real solutions exist.

example.py
import math

a, b, c = 1, -3, 2
discriminant = b ** 2 - 4 * a * c

if discriminant > 0:
    root1 = (-b + math.sqrt(discriminant)) / (2 * a)
    root2 = (-b - math.sqrt(discriminant)) / (2 * a)
    print(f"Two real roots: {root1:.1f} and {root2:.1f}")
elif discriminant == 0:
    root = -b / (2 * a)
    print(f"One real root: {root:.1f}")
else:
    print("No real roots")

How the code works

  • The discriminant is 9 - 8 = 1.
  • The two roots are (3 + 1) / 2 and (3 - 1) / 2.
  • Formatted output shows 2.0 and 1.0.

Key ideas

  • a, b, c = 1, -3, 2 unpacks a tuple into three variables.
  • The discriminant is b² - 4ac.
  • math.sqrt is only called when the discriminant is non-negative.

Try changing it

  • Read the coefficients from input and validate that a is not zero.
  • Print the roots as fractions with the fractions module.
  • Use complex numbers when the discriminant is negative.

Related examples

beginner

Area and Circumference of a Circle

Import the math module and use pi to calculate circle measurements.

beginner

Celsius to Fahrenheit

Convert a temperature with a formula and formatted output.

Previous exampleA Function with a Default ArgumentNext exampleStar Pyramid Pattern

Expected output

Two real roots: 2.0 and 1.0

Output is compared after trimming trailing whitespace on each line. Run the code to see it produced by CPython in your browser.

Practice next

Apply the same idea with automatic tests or browse a guided project.

ExercisesProjects