在pycharm中編輯Python程式 迴圈、IF語句報錯的原因(格式問題)__Python

來源:互聯網
上載者:User

      在pycharm中編輯程式時候,往往代碼正確,但不知道哪裡報錯,這裡以下面一個例子來說明代碼格式的規範性在pycharm中的重要性。

      題目:編寫函數,接受一個正偶數為參數,輸出2個素數,且這2個素數之和等於原正偶數,存在多組符合的素數,則全部輸出。

     

import mathdef IsPrime(n):    m=int (math.sqrt(n))+1    for i in  range(2,m):        if n%i==0:            return  False        return Truedef judge(n):    if isinstance(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 mathdef IsPrime(n):    m=int (math.sqrt(n))+1    for i in  range(2,m):        if n%i==0:            return  False        return Truedef judge(n):    if isinstance(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
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要注意編寫格式問題。細節決定成敗。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.