How do I ask the user if he wants to use the program again?
Question:
import math
print('Enter the coefficients:')
a = float(input('a = '))
b = float(input('b = '))
c = float(input('c = '))
D = b ** 2 - 4 * a * c
if D > 0:
print('The discriminant is greater than zero, the expression has 2 roots:')
print('x1 =', (-b + math.sqrt(D)) / 2 * a)
print('x2 =', (-b - math.sqrt(D)) / 2 * a)
if D == 0:
print('The discriminant is 0, the expression has 1 root:')
print('x =', -b / 2 * a)
if D < 0:
print('The discriminant is negative, there are no roots')
Answers:
You can use a while True
and then check if the user wants to continue using the program with an input()
call:
import math
keep_looping = True
# Keep looping until user inputs anything other than yes or y
while keep_looping:
print('Enter the coefficients:')
a = float(input('a = '))
b = float(input('b = '))
c = float(input('c = '))
D = b ** 2 - 4 * a * c
if D > 0:
print('The discriminant is greater than zero, the expression has 2 roots:')
print('x1 =', (-b + math.sqrt(D)) / 2 * a)
print('x2 =', (-b - math.sqrt(D)) / 2 * a)
elif D == 0:
print('The discriminant is 0, the expression has 1 root:')
print('x =', -b / 2 * a)
elif D < 0:
print('The discriminant is negative, there are no roots')
# Check if user wants to continue
response = input("Do you want to continue using the program?")
# I chose to check for yes and y, but you can add what you want here.
if response.lower() != 'yes' or response.lower() != 'y':
keep_looping = False
import math
print('Enter the coefficients:')
a = float(input('a = '))
b = float(input('b = '))
c = float(input('c = '))
D = b ** 2 - 4 * a * c
if D > 0:
print('The discriminant is greater than zero, the expression has 2 roots:')
print('x1 =', (-b + math.sqrt(D)) / 2 * a)
print('x2 =', (-b - math.sqrt(D)) / 2 * a)
if D == 0:
print('The discriminant is 0, the expression has 1 root:')
print('x =', -b / 2 * a)
if D < 0:
print('The discriminant is negative, there are no roots')
You can use a while True
and then check if the user wants to continue using the program with an input()
call:
import math
keep_looping = True
# Keep looping until user inputs anything other than yes or y
while keep_looping:
print('Enter the coefficients:')
a = float(input('a = '))
b = float(input('b = '))
c = float(input('c = '))
D = b ** 2 - 4 * a * c
if D > 0:
print('The discriminant is greater than zero, the expression has 2 roots:')
print('x1 =', (-b + math.sqrt(D)) / 2 * a)
print('x2 =', (-b - math.sqrt(D)) / 2 * a)
elif D == 0:
print('The discriminant is 0, the expression has 1 root:')
print('x =', -b / 2 * a)
elif D < 0:
print('The discriminant is negative, there are no roots')
# Check if user wants to continue
response = input("Do you want to continue using the program?")
# I chose to check for yes and y, but you can add what you want here.
if response.lower() != 'yes' or response.lower() != 'y':
keep_looping = False