gpt4 book ai didi

python - 为什么我的程序会被注释干扰?

转载 作者:行者123 更新时间:2023-12-03 07:59:16 24 4
gpt4 key购买 nike

我们在学校的任务是在代码底部添加程序的测试示例:

#example

"""

<insert example of you running the code>

"""

但是当我这样做的时候,我得到了错误。我从来没有在任何其他代码上得到它,只有在这个代码上?:

C:\Users\David>C:\Users\David\Desktop\IN1900\uke38\qerror.py 1
File "C:\Users\David\Desktop\IN1900\uke38\qerror.py", line 22
"""
^
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 24-25: truncated \UXXXXXXXX escape

C:\Users\David>

我的代码如下:

from math import sqrt
import sys

a=float(sys.argv[1])
b=float(sys.argv[2])
c=float(sys.argv[3])
d=(b**2)-(4*a*c)
x1=((-b+sqrt(d))/(2*a))
x2=((-b-sqrt(d))/(2*a))

print(f'The quadratic formula with used values gives two roots {x1:.1f} and {x2:.1f}')

#example
"""
#Fra command prompt:
#C:\Users\David>C:\Users\David\Desktop\IN1900\uke38\quadratic_roots_cml.py 1 0 -1
#The quadratic formula with used values gives two roots 1.0 and -1.0
#(koden funker ikke på et eller annet magisk vis når jeg bruker
"""

最佳答案

您的部分字符串文字被解释为转义的 Unicode 字符。此类转义序列以 \U 开头。最简单的解决方法是在双引号的开头三连字符前放置一个 r。这可以防止对文本进行任何类型的转义处理:

r"""
#Fra command prompt:
#C:\Users\David>C:\Users\David\Desktop\IN1900\uke38\quadratic_roots_cml.py 1 0 -1
#The quadratic formula with used values gives two roots 1.0 and -1.0
#(koden funker ikke på et eller annet magisk vis når jeg bruker
"""

这比添加一堆额外的斜杠要容易得多,而且也不会改变文本的可读性。

这是 Python 3 文档对“原始字符串”的描述:

Both string and bytes literals may optionally be prefixed with aletter 'r' or 'R'; such strings are called raw strings and treatbackslashes as literal characters. As a result, in string literals,'\U' and '\u' escapes in raw strings are not treated specially. Giventhat Python 2.x’s raw unicode literals behave differently than Python3.x’s the 'ur' syntax is not supported.

关于python - 为什么我的程序会被注释干扰?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63981262/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com