Reason behind "SyntaxError: invalid syntax" in a simple code in Python for not using commas

Reason behind "SyntaxError: invalid syntax" in a simple code in Python for not using commas

我得到一个 SyntaxError: invalid syntax when a 运行 this code:

total = int(input("compra total: "))

if total  > 700000: totald = total - total*0.2
elif total > 300000: totald = total - total*0.15
elif total > 150000: totald = total -total*0.10
else: totald = total*1

print("Centro Comercial Unaleño\n" "Compra Más y Gasta Menos\n" "NIT: 899.999.063\n" "Total:$"+str(int(totald)) "En esta compra tu descuento fue $"+str(int(total-totald)))

我意识到错误不是在这里放置逗号或求和符号:

......"Total: $"+str(int**(totald)), "\nEn** esta compra tu descuento fue $"+str(int(total-totald)))

但我不明白为什么必须放置这两个选项中的任何一个。 为什么我不能像在其他字符串中那样只放置一个 space,这两个符号中的任何一个的 objective 是什么?

感谢帮助!!

我建议像这样格式化文本:

print("Centro Comercial Unaleño\r\nCompra Más y Gasta Menos\r\nNIT: 899.999.063\r\nTotal:${} En esta compra tu descuento fue ${}".format(totald, totald))

total = int(input("compra total: "))

if total  > 700000: totald = total - total*0.2
elif total > 300000: totald = total - total*0.15
elif total > 150000: totald = total -total*0.10
else: totald = total*1

print("Centro Comercial Unaleño\n" "Compra Más y Gasta Menos\n" "NIT: 899.999.063\n" "Total:$"+str(int(totald)) + "En esta compra tu descuento fue $"+str(int(total-totald)))

您在 print 语句中连接字符串时遗漏了 +。

因为您依赖 string-literal 连接字符串分隔的文字。见 documentation.

这仅适用于字符串文字。编译器无法将字符串连接到由 space 分隔的任意表达式,只能连接文字。

>>> "foo" "bar"
'foobar'
>>> 'foo' frobnicate()
  File "<stdin>", line 1
    'foo' frobnicate()
                   ^
SyntaxError: invalid syntax

这发生在编译时,

>>> import dis
>>> dis.dis("'foo' 'bar'")
  1           0 LOAD_CONST               0 ('foobar')
              2 RETURN_VALUE

所以它不能依赖运行时结果。

逗号有效,因为它会成为 print.

的另一个参数

例如

>>> print('hello')
hello
>>> print('hello', 'world')
hello world