在 python 中使用条件错误
using errors in conditions in python
我的二次计算程序需要帮助。我在 If 中使用了一个表达式,该表达式显然会导致数学错误。但是我不希望代码在错误发生时崩溃,而是希望发生其他事情。
import math
def quad(a, b, c):
# creating a variable for all the parts that make the expression
first_nu = int(a)
second_nu = int(b)
third_nu = int(c)
four = 4
two = 2
det = second_nu ** 2 - (four * (first_nu * third_nu))
if math.sqrt(det) == 0:
print(' the discriminant is 0 hence the quadratic has no real roots')
else:
# calculating the roots
root_det = math.sqrt(det)
def printing():
option1 = (-third_nu + root_det) / (two * first_nu)
option2 = (-third_nu - root_det) / (two * first_nu)
print(option1, option2)
if det < 0:
printing()
print('The roots are not real roots')
elif det == 0:
print('mathematical error in a situation where there is root of 0')
print('The roots has just one real root')
elif det > 0:
printing()
print('The roots has two real roots')
first_num = input("enter your first number of the quadratic")
second_num = input("enter your second number of the quadratic")
third_num = input("enter your third number of the quadratic")
quad(first_num, second_num, third_num)
对要测试的代码使用try:,并将其余代码放在except中。我希望这能解决问题。 For more information about Python error handling here or check from w3schools
try
块可让您测试代码块的错误。
except
块可让您处理错误。
我的二次计算程序需要帮助。我在 If 中使用了一个表达式,该表达式显然会导致数学错误。但是我不希望代码在错误发生时崩溃,而是希望发生其他事情。
import math
def quad(a, b, c):
# creating a variable for all the parts that make the expression
first_nu = int(a)
second_nu = int(b)
third_nu = int(c)
four = 4
two = 2
det = second_nu ** 2 - (four * (first_nu * third_nu))
if math.sqrt(det) == 0:
print(' the discriminant is 0 hence the quadratic has no real roots')
else:
# calculating the roots
root_det = math.sqrt(det)
def printing():
option1 = (-third_nu + root_det) / (two * first_nu)
option2 = (-third_nu - root_det) / (two * first_nu)
print(option1, option2)
if det < 0:
printing()
print('The roots are not real roots')
elif det == 0:
print('mathematical error in a situation where there is root of 0')
print('The roots has just one real root')
elif det > 0:
printing()
print('The roots has two real roots')
first_num = input("enter your first number of the quadratic")
second_num = input("enter your second number of the quadratic")
third_num = input("enter your third number of the quadratic")
quad(first_num, second_num, third_num)
对要测试的代码使用try:,并将其余代码放在except中。我希望这能解决问题。 For more information about Python error handling here or check from w3schools
try
块可让您测试代码块的错误。
except
块可让您处理错误。