x, y, z = value.split() 这行有什么问题?为什么它不与这个字符串分开?

问题描述 投票:0回答:1
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 将保留运算符。但是它连续地显示了图像中显示的相同错误。错误的屏幕截图

python
1个回答
0
投票

您输入的每个字符之间需要有空格。因此,请输入

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()
© www.soinside.com 2019 - 2024. All rights reserved.