3 回答

TA貢獻(xiàn)1860條經(jīng)驗(yàn) 獲得超8個(gè)贊
choices={"add","substract","multiply"}
while 1:
choice = input("Welcome to the basic calculator, please tell me if you want to add, substract or muliply: ")
if choice not in choices:
print("I think you made a typo, you'd have to try again.")
else: break
if choice == "add":
...
你在循環(huán)中完成輸入和驗(yàn)證部分,然后你的代碼進(jìn)行計(jì)算。(假設(shè)計(jì)算器只計(jì)算一次然后退出。如果沒(méi)有,你可以把整個(gè)事情放在另一個(gè)循環(huán)中進(jìn)行更多計(jì)算,也許有一個(gè)退出命令。)
在我的示例中,驗(yàn)證是通過(guò)包含您可能的命令的集合(選擇)完成的,并檢查輸入的成員資格。

TA貢獻(xiàn)1815條經(jīng)驗(yàn) 獲得超13個(gè)贊
OP = ("add", "subtract", "multiply")
while True:
choice = input("Pick an operation {}: ".format(OP))
if choice not in OP:
print("Invalid input")
else:
break
if choice == OP[0]:
#...
添加回答
舉報(bào)