我想用python做一个计算器,检查用户的答案是否匹配,有这样一个问题,python给我一个错误:
else:
^
SyntaxError: invalid syntax
带代码:
while True:
def code():
print(Back.RED)
what = input("Что делаем? (+, -, *, /, %, ^): ")
if what != ("+" and "-" and "*" and "/" and "%" and "^"):
print("Не понял тебя")
code()
else:
print(Back.MAGENTA)
a = float(input("Введите первое число: "))
print(Back.CYAN)
b = float(input("Введите второе число: "))
if what == "+":
c = a + b
if what == "-":
c = a - b
if what == "*":
c = a * b
if what == "/":
c = a / b
if what == "%":
c = a % b
if what == "^":
c = a ** b
print(Back.GREEN)
print(Style.BRIGHT)
print("Результат: " + str(c))
input()
请解释一下哪里出了问题,不要骂太多,这是我继hello world之后的第二个程序
提前感谢您的回复!
如果之前没有if,则不能使用else,因为else意味着如果不是if或elif,则else,在else之前添加一个tab,两个tab之后的所有内容PS在code()tab之后添加
我建议你学习 Python 的基本语法。它与许多其他语言的不同之处在于书写缩进的严格性——它们表示块的开始和结束(在其他语言中,{} 通常用于此目的)。
这是一个很好的解释
在您的情况下,指向正确编写某些内容的位置比指出错误更容易,但是:
what != ("+" and "-" and "\*" and "/" and "%" and "^")
仅对 为真what == "^"
,并且根据其结构为假。它不能what !=
作为公因数从括号中取出。正确:what != "+" and what != "-" and what != "*" and what != "/" and what != "%" and what != "^"
如果你运用想象力去理解程序的本质并消除基本错误,它会变成这样:
评论中问题的答案:在当前的实现中,它会以这种方式发生,但您可以采取不同的方式 - 将 while True 添加到函数中,如下所示:
PS 是的,如下所述,确实可以提出条件
if what not in ('+-*/%^')
所以更简洁:
在上面带有 while 循环的示例中,它将按您的意愿工作。