How do I ask the user if they want to solve the equation again with a yes or no answer in Python?

57 views Asked by At

Here's my code.

import math

print('I will solve the equation ax^2=bx=c=0')

a = int(input('a= '))
b = int(input('b= '))
c = int(input('c= '))

d=b**2-4*a*c

if d < 0:
    print('The equation has no solution')
elif d == 0:
    x=(-b)/(2*a)
    print('This equation has one solution',x)
else:
    x1 = (-b+math.sqrt(d))/(2*a)
    x2 = (-b-math.sqrt(d))/(2*a)
    print('This equation has two solutions: ',x1, 'or',x2)

I tried guess.Number() but my logic was incorrect, this is for a Chapter 4 Python assignment and it requires the user to try multiple inputs for the quadratic equations. I'm very new to this.

1

There are 1 answers

1
Grimlock On

Welcome to Stack Overflow. What you are looking for can be solved with while loops: https://www.w3schools.com/python/python_while_loops.asp

Here's a solution for your code:

import math

print('I will solve the equation ax^2 + bx + c = 0')

# Start a loop that will continue until the user chooses to exit
while True:
    a = int(input('a= '))
    b = int(input('b= '))
    c = int(input('c= '))

    d = b**2 - 4*a*c

    if d < 0:
        print('The equation has no solution')
    elif d == 0:
        x = (-b) / (2*a)
        print('This equation has one solution', x)
    else:
        x1 = (-b + math.sqrt(d)) / (2*a)
        x2 = (-b - math.sqrt(d)) / (2*a)
        print('This equation has two solutions: ', x1, 'or', x2)

    # Ask the user if they want to solve another equation
    user_input = input('Do you want to solve another equation? (yes/no): ')

    # If the user types 'no' (in any case), break out of the loop and end the program
    if user_input.lower() == 'no':
        break