为什么这行不通?
Traceback(最近一次调用是最后一次):File"/用户/ianyi/PycharmProjects/code作业/calculator.py",第23行,在calnum1=iof(input("把第一个数字放在这里:\n"))File"/用户/ianyi/PycharmProjects/代码作业/calculator.py",第4行,在iof if y!=True: number=int(number)ValueError:int()的无效文字以10为底:'123.123'
def iof(number):
y = isinstance(number, float)
if y != True: number = int(number)
else: number = float(number)
return number
def calculation(x:int, y:int, operator:str):
if operator in ["+"]: sum = iof(x + y)
elif operator in ["-"]: sum = iof(x - y)
elif operator in ["*"]: sum = iof(x * y)
elif operator in ["/"]: sum = iof(x / y)
elif operator in ["%"]: sum = iof(100 * x / y)
elif operator in ["^"]: sum = iof(x ** y)
elif operator in ["√"]: sum = x ** 0.5
return sum
mathmatical, calnum2 = [None, "+", "-", "*", "/", "%", "^", "√"], None
print("\nHello. This is a Calculator.")
for i in range(1):
if calnum2 == None:
calnum1 = iof(input("Put the first number here: \n"))
choice = str(input(f'''Which mathmatical symbol?
(+ = 1, - = 2, * = 3, / = 4)
(% = 5, ^ = 6, √ = 7)\n'''))
if choice == "x": choice = "*"
if choice.isnumeric(): choice = mathmatical[int(choice)]
if choice == "%": calnum2 = iof(input(f"{calnum1}% of? "))
elif choice == "^": calnum2 = iof(input(f"{calnum1} raised to the power of: "))
elif choice == "√": pass
elif choice not in ["√", "%"]: calnum2 = iof(input(f"{calnum1} {choice} "))
else: raise ValueError("um put the right numbers next time")
sum = calculation(calnum1, calnum2, choice)
print(sum)
原因是因为input返回str
类型,当您执行is实例(number, flot)
时,它将始终为False。然后,您尝试将类似于浮点数的字符串转换为int,这会导致它抛出错误。