我是 python 的初學者,我目前正在研究一個不是這樣的計算器: Enter Something: add
"Enter 1 number : 1"
"Enter 2 number : 3"
The answer is 5 not like that or using eval()
I Want to create a計算器,他們在其中輸入如下內容:“add 1 3”,輸出應該是 4。但我必須檢查第一個單詞是字串第二個是整數或浮點數,第三個也是數字我創建了一個腳本,但我有一個我不知道如何檢查輸入是整數、字串還是浮點數的問題,我用過isdigit()它可以作業,但它不計算負數和浮點數,我也用過isinstance()但它不起作用,并認為輸入是一個整數,即使它是一個字串,我不知道如何在這個腳本上使用 try 和 except 方法
while True:
exitcond = ["exit","close","quit"]
operators =["add","subtract","multiply","divide"]
uinput = str(input())
lowereduin = uinput.lower()
splited = lowereduin.split(" ")
if lowereduin in exitcond:
break
if splited[0] == operators[0]:
if isinstance(splited[1],int) == True:
if isinstance(splited[2] , int) == True:
result = int(splited[1]) int(splited[2])
print(result)
else:
print("enter a number")
else:
print("enter a number")
當我運行這個腳本并輸入 add 1 3 它說輸入一個數字,當我只輸入 add 它給出這個錯誤
Traceback (most recent call last):
File "C:\Users\Tyagiji\Documents\Python Projects\TRyinrg differet\experiments.py", line 11, in <module>
if isinstance(splited[1],int) == True:
IndexError: list index out of range
有人能告訴我這個錯誤是什么嗎?如果這不起作用,你能告訴我如何try:在這個腳本上使用方法。
uj5u.com熱心網友回復:
您可以嘗試以下方法并使用型別檢查
import operator
while True:
exitcond = ["exit","close","quit"]
operators ={"add": operator.add,"subtract":operator.sub,"multiply": operator.mul,"divide":operator.truediv}
uinput = str(input())
lowereduin = uinput.lower()
splited = lowereduin.split(" ")
if lowereduin in exitcond or (len(splited) !=3):
break
try:
if splited[0] not in operators.keys():
raise ValueError(f"{splited[0]} not in {list(operators.keys())}")
op = operators.get(splited[0])
val = op(
*map(int, splited[1:])
)
print(val)
except (ValueError, ZeroDivisionError) as err:
print(err)
break
uj5u.com熱心網友回復:
以迪帕克的回答為基礎。運算子名稱到函式的字典是一種好方法。您可以添加,splits直到您有足夠的數字繼續。
import operator as op
while True:
exitcond = ["exit","close","quit"]
operators = {"add": op.add,"subtract": op.sub, "multiply": op.mul, "divide": op.truediv}
splits = str(input()).lower().split()
if any(part in exitcond for part in splits):
break
while len(splits) < 3:
splits.append(input('Enter number: '))
try:
print(operators[splits[0]](*map(lambda x: float(x.replace(',','')), splits[1:3])))
except ZeroDivisionError:
print("Can't divide by 0")
except:
print('Expected input: add|subtract|multiply|divide [number1] [number2] -- or -- exit|quit|close')
需要注意的是,lambda 函式在浮點數失敗時洗掉所有逗號,,然后將所有數字字串轉換為浮點數。因此,答案將始終是一個浮點數,這會打開add 1.1 2.2不完全是 3.3 的蠕蟲罐,這是由于浮點算術和計算機方面的有據可查的問題
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/515921.html
