def calculate():
while True:
operator = input("What operator do you wanna use(*,/, ,-)? ")
possible_op = " -*/"
if operator not in possible_op:
continue
try:
number_1 = float(input("What is your first number? "))
number_2 = float(input("What is your second number? "))
except ValueError:
continue
if operator == " ":
print(number_1 number_2)
elif operator == "-":
print(number_1 - number_2)
elif operator == "*":
print(number_1 * number_2)
elif operator == "/":
print(number_1 / number_2)
try:
print("Do you wanna calculate again? ")
answer = input("(Y/N) ").lower()
possible_answers = ["y", "n"]
if answer == "y":
return calculate()
elif answer == "n":
exit()
except input != possible_answers:
print("Wrong Input")
continue
calculate()
當我嘗試在 Microsoft VS Code 中打開我的腳本時,我收到了以下錯誤訊息:
Traceback (most recent call last):
File "e:\Python\Projects\VsCode\calculator\calculator_school.py", line 31, in calculate
exit()
File "D:\Schule\Phyton\lib\_sitebuiltins.py", line 26, in __call__
raise SystemExit(code)
SystemExit: None
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "e:\Python\Projects\VsCode\calculator\calculator_school.py", line 36, in <module>
calculate()
File "e:\Python\Projects\VsCode\calculator\calculator_school.py", line 32, in calculate
except input != possible_answers:
TypeError: catching classes that do not inherit from BaseException is not allowed
當我在檔案資源管理器中打開它時,該腳本會在 Cmd 中正常關閉。但在 VS Code 中它不會。這是為什么?
uj5u.com熱心網友回復:
在這種情況下,即使有中斷,您也可以停止腳本。你在一個回圈中。
uj5u.com熱心網友回復:
您可以在不使用 try except 陳述句的情況下退出。試試這個:
def calculate():
while True:
operator = input("What operator do you wanna use(*,/, ,-)? ")
possible_op = " -*/"
if operator not in possible_op:
continue
try:
number_1 = float(input("What is your first number? "))
number_2 = float(input("What is your second number? "))
except ValueError:
continue
if operator == " ":
print(number_1 number_2)
elif operator == "-":
print(number_1 - number_2)
elif operator == "*":
print(number_1 * number_2)
elif operator == "/":
print(number_1 / number_2)
while True:
print("Do you wanna calculate again? ")
answer = input("(Y/N) ").lower()
if answer == "y":
return calculate()
elif answer == "n":
quit()
else:
print("Wrong Input")
continue
calculate()
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/480038.html
