首页 > 解决方案 > 此代码会导致无效的语法错误。为什么?

问题描述

我正在练习代码大战。下面的代码给了我一个无效的语法错误。我不明白语法哪里出错了。

def is_divisible(n,x,y):
    
    a = n%x
    b = n%y
    
    if a == 0:
        if b == 0:
            print("true because " + str(n) + " is divisible by " +str(x) + " and " + str(y))
            
        else:
            print("false because " + str(n) + " is not divisible by " + str(y))
    elif a != 0:
        if b == 0:
            print("false because " + str(n) + " is not divisible by " +str(x))
        else:
            print("false because " + str(n) + " is neither divisible by "+str(x) " nor " +str(y))

我得到的错误是:

Traceback(最近一次调用最后一次):
文件“tests.py”,第 2 行,
从解决方案导入 is_divisible

文件 "/workspace/default/solution.py",第 16 行
print("false 因为 " + str(n) + " 既不能被 "+str(x) " 也不能被 " +str(y) 整除)
^
SyntaxError: invalid句法

标签: python

解决方案


+在此行中缺少连接运算符 ( ): print("false because " + str(n) + " is neither divisible by "+str(x) " nor " +str(y))

将其更改为:

print("false because " + str(n) + " is neither divisible by "+str(x) + " nor " +str(y))

正如其他人所建议的,如果您有 Python 版本 >= 3.6,请使用f-string更具可读性且不易出错的替代方案:

print(f"false because {n} is neither divisible by {x} nor {y}")


推荐阅读