def calculation(values):
x, y, z = values.split()
x = float(x)
z = float(z)
if y == "+":
return x+z
elif y == "-":
return x-z
elif y == "*":
return x*z
elif y == '/':
return x/z
values = input("Enter mathematical values: ")
print(calculation(values))
我尝试将 split(""),split( ),split(" ") 也为每个变量放置一个空格,我原以为算术值将分配给 x,z,y 将保留运算符。但是它连续地显示了图像中显示的相同错误。错误的屏幕截图
您输入的每个字符之间需要有空格。因此,请输入
1+1
,而不是 1 + 1
。
如果您不想使用空格,则可以使用正则表达式通过以下方法进行拆分:
import re
# Define regular expression pattern to match operators
operator_pattern = r'[-+*/]'
# Split the expression using the operator pattern
operands = re.split(operator_pattern, values)
# Extract operands and operator
x = int(operands[0])
z = int(operands[1])
y = re.search(operator_pattern, values).group()