2013-04-28 74 views
0

這是怎麼回事? (我只是一個初學者,所以沒有什麼複雜的,拜託了!)縮進問題! (Python 2.7)

#!usr/bin/python 

import os 
import sys 
import pdb 
import time 
import array 

red = chr(00), chr(00), chr(255) 
blue = chr(255), chr(00), chr(00) 

print "Monochrome Bitmap Color Changer" 
print "Supported colors: " 
print "Black, White, Blue, Red, Yellow," 
print "Green, Orange, Purple, Pink, Brown, Grey" 
print "" 

filename = raw_input("Please enter filename or directory of monochrome bitmap: ") 
whitevalue = raw_input("Change all white pixels to? ") 
blackvalue = raw_input("Change all black pixels to? ") 
with open (filename, 'r+b') as f: 
    f.seek(54) 
    if whitevalue is "red" or "Red": 
     f.write(red) 
    elif whitevalue is "blue" or "Blue": 
      f.write(blue) 
      f.seek(58) 
      if blackvalue is "red" or "Red": 
     f.write(red) 
     elif blackvalue is "blue" or "Blue": 
      f.write(blue) 
      exit 
    #print "Done" 
    #time.sleep(3) 
    #exit 

第二f.write(red)線後,它顯示了一個紅粉紅色的亮點,並說:

「取消縮進不匹配任何外部縮進級別'

這是什麼意思,以及如何幫助/修復它?

非常感謝!

回答

2

elif語句與if語句不在同一個範圍內,所以它會給你一個錯誤。只有在相同範圍/縮進中已經存在if語句的情況下,才能存在Elif語句。

如果你希望它是符合的elif的語句

if blackvalue is "red" or "Red": 

然後在縮進它多了一個標籤。如果你想讓它在相同的範圍內

if whitevalue is "red" or "Red": 

elif whitevalue is "blue" or "Blue": 

然後取消選項卡中的一次。但總而言之,你自己不能有elif聲明(就像你本身不能有其他聲明一樣)。

1

您的elif不是縮進的方式,它屬於if語句。

改變這樣的:

with open (filename, 'r+b') as f: 
    f.seek(54) 
    if whitevalue is "red" or "Red": 
     f.write(red) 
    elif whitevalue is "blue" or "Blue": 
     f.write(blue) 
     f.seek(58) 
     if blackvalue is "red" or "Red": 
      f.write(red) 
     elif blackvalue is "blue" or "Blue": 
      f.write(blue) 
     exit