A. Melih Yılmaz

First steps with conditions in Python

Using if, elif and else in a discriminant exercise.

Screenshot of the Python example prepared and run for this article.
Screenshot of the Python example prepared and run for this article.

An if statement runs a block when its condition is true. elif checks another possibility; else runs when none of the earlier conditions hold. Indentation defines code blocks in Python.

For a quadratic equation, the discriminant is b² − 4ac. A positive value indicates two distinct real roots; zero indicates one repeated real root. A negative value means there are no real roots. In this example a is nonzero; if a were zero, the equation would not be quadratic.

a, b, c = 1, 5, 4
d = b ** 2 - 4 * a * c
if d > 0:
    print("Two distinct real roots")
elif d == 0:
    print("One repeated real root")
else:
    print("No real roots")
All articles