Python Else语句语法错误(简单计算器)
我目前正在尝试编写一个小计算器,因为我正在学习python。我的问题是,它在结尾的else语句中不断输出语法错误,因为我还是初学者,我不知道为什么 您缺少一个冒号:with else 应该是:{你的逻辑} 更新:实际上你有冒号,但有条件。这应该是一个elif,而不是其他Python Else语句语法错误(简单计算器),python,if-statement,Python,If Statement,我目前正在尝试编写一个小计算器,因为我正在学习python。我的问题是,它在结尾的else语句中不断输出语法错误,因为我还是初学者,我不知道为什么 您缺少一个冒号:with else 应该是:{你的逻辑} 更新:实际上你有冒号,但有条件。这应该是一个elif,而不是其他 将last else更改为elif,如果没有默认检查,则不一定需要else。您的代码实际上存在一些问题 不能在字符串和整数等之间进行转换。4+5不是9,而是45,因为它是两个字符串的组合。但是如果你做int4+int5,那么你会
将last else更改为elif,如果没有默认检查,则不一定需要else。您的代码实际上存在一些问题 不能在字符串和整数等之间进行转换。4+5不是9,而是45,因为它是两个字符串的组合。但是如果你做int4+int5,那么你会得到9 执行else语句时,不存在任何条件 因此,基本的if,elif,else是:
a = "yay"
if a == "yay":
print("a likes you")
elif a == "no":
print("a doesn't like you")
else:
print("a doesn't want to respond")
Python 2.7
Python 3.6
这里需要另一份elif声明。else之后,无法检查其他条件,因此else。我将else更改为elif,但它仍然输出无效语法并将elif标记为红色。请将代码作为文本而不是图像包含。最后一行似乎是额外的缩进级别。将它备份一个等级,并将最后一个其他等级更改为elif,它应该会工作。
print ("Welcome to your friendly Python calculator. Use + for addition and - for substraction")
print ("This code uses period (.) for decmimals")
first = "Please enter your first number "
second = "Please enter your second number "
operator = raw_input("Please choose an operation (+ or -) ")
if operator == "+":
num1 = input(first)
num2 = input(second)
print ("Result: " + str(num1 + num2))
elif operator == "-":
num1 = input(first)
num2 = input(second)
print ("Result: " + str(num1 - num2))
else:
print("You didn't enter a valid operator.")
print ("Welcome to your friendly Python calculator. Use + for addition and - for substraction")
print ("This code uses period (.) for decmimals")
first = "Please enter your first number "
second = "Please enter your second number "
operator = input("Please choose an operation (+ or -) ")
if operator == "+":
num1 = int(input(first))
num2 = int(input(second))
print ("Result: " + str(num1 + num2))
elif operator == "-":
num1 = int(input(first))
num2 = int(input(second))
print ("Result: " + str(num1 - num2))
else:
print("You didn't enter a valid operator.")