我正在制作一個非常基本的計算器,我目前正在努力讓我的錯誤例外在 python 中列印它下面的行。
我的代碼包括:
loops = int(input("How many math problems do you need: "))
for i in range(loops):
while True:
method = input("What math method would you like to use. m = multiplication, d = division, a = addition, s = subtraction:, ex = exponent: ")
try:
if method in ['m','M','d','D','a','A','s','S','Ex','ex','EX','eX']:
break
except:
print("Error your method is not viable")
while True:
num1 = input("What is the first number you want to input into your method: ")
try:
num1 = float(num1)
break
except ValueError:
print("Error your first number needs to be a number")
while True:
num2 = input("What is the second number you want to input into your method: ")
try:
num2 = float(num2)
break
except ValueError:
print("Error your second number needs to be a number")
if method in ['m', 'M']:
finalans = num1 * num2
print("Your answer is",finalans)
if method in ['d', 'D']:
finalans = num1 / num2
print("Your answer is",finalans)
if method in ['a', 'A']:
finalans = num1 num2
print("Your answer is",finalans)
if method in ['s', 'S']:
finalans = num1 - num2
print("Your answer is",finalans)
if method in ['Ex', 'ex', 'EX', 'eX']:
finalans = num1 ** num2
print("Your answer is",finalans)
exit()
在第 10 行,我在列印出它下面的行時遇到了問題,有人知道我做錯了什么嗎?
uj5u.com熱心網友回復:
我可以看到的第一個錯誤是您忘記將第 3 行下的所有內容縮進,for i in range(loops):然后將exit(). 第二個是if method in [...]不要拋出任何錯誤。所以你必須用[...].index(method)或替換它
try:
if method in [...]:
break
except:
print("<error message>")
和
if method in [...]:
break
else:
print("<error message>")
[...]您的所有可能操作的串列在哪里
uj5u.com熱心網友回復:
如果您想使用例外來處理無效方法,您可以像這樣使用它:
loops = int(input("How many math problems do you need: "))
for i in range(loops):
while True:
method = input("What math method would you like to use. m = multiplication, d = division, a = addition, s = subtraction:, ex = exponent: ")
try:
if method not in ['m','M','d','D','a','A','s','S','Ex','ex','EX','eX']:
raise Exception()
break
except:
print("Error your method is not viable")
然而,用一個簡單的if-else指令來處理它要好得多:
loops = int(input("How many math problems do you need: "))
for i in range(loops):
while True:
method = input("What math method would you like to use. m = multiplication, d = division, a = addition, s = subtraction:, ex = exponent: ")
if method in ['m','M','d','D','a','A','s','S','Ex','ex','EX','eX']:
break
else:
print("Error your method is not viable")
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/317951.html
