我正在使用vim编辑器作为python IDE。下面是一个简单的python程序来计算数字的平方根:
import cmath
def sqrt():
try:
num = int(input("Enter the number : "))
if num >= 0:
main(num)
else:
complex(num)
except:
print("OOPS..!!Something went wrong, try again")
sqrt()
return
def main(num):
squareRoot = num**(1/2)
print("The square Root of ", num, " is ", squareRoot)
return
def complex(num):
ans = cmath.sqrt(num)
print("The Square root if ", num, " is ", ans)
return
sqrt()
警告是:
1-square-root.py|2 col 1 C| E302 expected 2 blank lines, found 0 [pep8]
1-square-root.py|15 col 1 C| E302 expected 2 blank lines, found 1 [pep8]
1-square-root.py|21 col 1 C| E302 expected 2 blank lines, found 0 [pep8]
你能说出为什么这些警告会来吗?
答案 0 :(得分:34)
import cmath
def sqrt():
try:
num = int(input("Enter the number : "))
if num >= 0:
main(num)
else:
complex_num(num)
except:
print("OOPS..!!Something went wrong, try again")
sqrt()
return
def main(num):
square_root = num**(1/2)
print("The square Root of ", num, " is ", square_root)
return
def complex_num(num):
ans = cmath.sqrt(num)
print("The Square root if ", num, " is ", ans)
return
sqrt()
之前的问题将解决您的PEP8问题。导入后,您需要在启动代码之前有2个新行。此外,在每个def foo()
之间,您还需要有2个。
在您的情况下,导入后您有0,并且每个函数之间有1个换行符。作为PEP8的一部分,您需要在代码结束后使用换行符。不幸的是,当我将代码粘贴到此处时,我不知道如何显示它。
注意命名,它也是PEP8的一部分。我将complex
更改为complex_num
,以防止与内置complex
混淆。
最后,他们只是警告,如果需要可以忽略它们。
答案 1 :(得分:1)
您需要在有意义的代码块之间添加两个空行。
这些包括(例如):
答案 2 :(得分:1)
以下是文档的链接:
PEP8 Style Guide for Python
您应该在函数之间添加两个空格,如下所示:
import cmath
def sqrt():
try:
num = int(input("Enter the number : "))
if num >= 0:
main(num)
else:
complex_num(num)
except:
print("OOPS..!!Something went wrong, try again")
sqrt()
return
def main(num):
square_root = num**(1/2)
print("The square Root of ", num, " is ", square_root)
return
def complex_num(num):
ans = cmath.sqrt(num)
print("The Square root if ", num, " is ", ans)
return
sqrt()
答案 3 :(得分:0)
with warnings:-
import math
def my():
print("hello world")
my()
Without warnings:-
import math
def my():
print("hello world")
my()
这里,如果你看到第二个代码片段的import语句之后的两行空格,它们不会给出任何警告。 再次,如果您正在编写两个方法定义,则在代码块之间有两行作为空格。
答案 4 :(得分:0)
所有答案似乎都是正确的。为避免手动执行此操作,您还可以使用autopep8
package(pip install autopep8)。调用autopep8 filename.py
的结果是相同的:
import cmath
def sqrt():
try:
num = int(input("Enter the number : "))
if num >= 0:
main(num)
else:
complex(num)
except:
print("OOPS..!!Something went wrong, try again")
sqrt()
return
def main(num):
squareRoot = num**(1/2)
print("The square Root of ", num, " is ", squareRoot)
return
def complex(num):
ans = cmath.sqrt(num)
print("The Square root if ", num, " is ", ans)
return
sqrt()