您好问题是,当我尝试在python中运行try expect块时,它似乎没有捕获我的错误。
代码捕获错误,但它没有捕获我设置的错误,我已经尝试if else语句来捕获错误,现在尝试捕获但似乎它只是没有被传递到这些块。
import sys
INVALID_NUM_ARGS_ERROR = "At least two arguments not provided"
INVALID_NUM_ERROR = "Invalid number provided"
def your_main_program(args):
# Call your methods from here, using the
# relevant items in args
num1 = int(sys.argv[1])
num2 = int(sys.argv[2])
try:
if len(sys.argv) == 3:
multiply(num1, num2)
elif len(sys.argv) == 4:
if(num1 or num2 == 0):
raise_string(num1, num2)
formula = ''
formula += (str(num1) + ' * ') * (num2 - 1)
formula += str(num1)
print(formula)
raise_string(num1, num2)
except ValueError:
print(INVALID_NUM_ERROR)
我期待[Invalid number provided]
的输出,但实际输出结果是[Traceback (most recent call last):]
提高字符串代码
def raise_string(num1, num2):
"Prints our the two numbers to the power of itself"
answer = num1**num2
print(answer)
return answer
追溯*
Traceback (most recent call last):
File "script1.py", line 50, in <module>
your_main_program(sys.argv)
File "script1.py", line 15, in your_main_program
num2 = int(sys.argv[2])
ValueError: invalid literal for int() with base 10: 'a'calls
您的代码可能如下所示:
import sys
INVALID_NUM_ARGS_ERROR = "At least two arguments not provided"
INVALID_NUM_ERROR = "Invalid number provided"
def your_main_program(args):
# Call your methods from here, using the
# relevant items in args
try:
num1 = int(args[1])
num2 = int(args[2])
except ValueError:
print(INVALID_NUM_ERROR)
length = len(args)
if length == 3:
multiply(num1, num2)
elif length == 4:
if num1 == 0 or num2 == 0:
raise_string(num1, num2)
else:
formula = " * ".join([str(num1)] * num2)
print(formula)
raise_string(num1, num2)
def multiply(n1, n2):
print(f"{n1} * {n2} = {n1*n2}")
def raise_string(n1, n2):
print(f"{n1} ** {n2} = {n1**n2}")
if __name__ == "__main__":
your_main_program(sys.argv)