python - 此代码会导致无效的语法错误。为什么?
问题描述
我正在练习代码大战。下面的代码给了我一个无效的语法错误。我不明白语法哪里出错了。
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句法
解决方案
您+
在此行中缺少连接运算符 ( ):
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}")
推荐阅读
- visual-studio-code - VSCode 调试控制台不断跳到顶部
- python - 如何在基类中使用子类的函数属性?
- php - PHP多维数组按值排序
- ruby-on-rails - 获取关系计数的活动记录查询
- c# - SqlException:INSERT 语句与 FOREIGN KEY 约束“FK_Users_Companies_CompanyId”冲突
- sql - 如何根据psql中的一条记录的值排除具有相同ID的所有行?
- javascript - Zapier 自定义响应对象
- express - 无法使用 passport-jwt 访问受保护的路线
- tensorflow - 如何在 TensorFlow 中计算次梯度?
- scala - 为什么 Scala 强制使用 Await 而不是 Awaitable?