在pycharm中編輯Python程式 迴圈、IF語句報錯的原因(格式問題)
在pycharm中編輯程式時候,往往程式碼正確,但不知道哪裡報錯,這裡以下面一個例子來說明程式碼格式的規範性在pycharm中的重要性。
題目:編寫函式,接受一個正偶數為引數,輸出2個素數,且這2個素數之和等於原正偶數,存在多組符合的素數,則全部輸出。
import math def IsPrime(n): m=int (math.sqrt(n))+1 for i in range(2,m): if n%i==0: return False return True def judge(n): ifisinstance(n,int) and n>0 and n%2==0: for i in range(3, int(n/2)+1): if i%2==1 and IsPrime(i) and IsPrime(n-i): print(i,'+',n-i,'=',n) judge(80)
結果報錯如下所示;
D:\learn\python\python.exe D:/learn/code/MyFirstPython.py
File "D:/learn/code/MyFirstPython.py", line 11
for i in range(3, int(n/2)+1):
^
IndentationError: unindent does not match any outer indentation level
Process finished with exit code 1
修改後將judge函式中for語句移到上面if語句後面即可。這是由於for語句是承接if語句進行處理的,注意if語句後面的“:”!
如下圖所示:
import math def IsPrime(n): m=int (math.sqrt(n))+1 for i in range(2,m): if n%i==0: return False return True def judge(n): if isinstance(n,int) and n>0 and n%2==0: fori in range(3, int(n/2)+1): if i%2==1 and IsPrime(i) and IsPrime(n-i): print(i,'+',n-i,'=',n) judge(80)
D:\learn\python\python.exe D:/learn/code/MyFirstPython.py
5 + 75 = 80
7 + 73 = 80
9 + 71 = 80
11 + 69 = 80
13 + 67 = 80
15 + 65 = 80
17 + 63 = 80
19 + 61 = 80
21 + 59 = 80
23 + 57 = 80
25 + 55 = 80
27 + 53 = 80
29 + 51 = 80
31 + 49 = 80
33 + 47 = 80
35 + 45 = 80
37 + 43 = 80
39 + 41 = 80
Process finished with exit code 0
這就提示我們,以後用pycharm要注意編寫格式問題。細節決定成敗!