初学python者禁忌,那些踩过的坑

本人是java后端开发人员,这几天在自学python,踩过一些坑,希望给大家一些帮助.

Python是有格式要求的!!!Python是有格式要求的!!!Python是有格式要求的!!!

缩进要合理,自己再写一个python输出文件的时候发现的,我把代码提供出来

dbfilename = 'people-file'
ENDDB='enddb.'
ENDREC='endrec.'
RECSEP='=>'

def  storeDbase(db):

    dbfile = open(dbfilename,'w')
    for key in db:
            dbfile.write (key)
            for(name,value) in db[key].items():
                dbfile.write(name + RECSEP + repr(value) + '\n')
            dbfile.write (ENDREC)
            dbfile.write(ENDDB)
    dbfile.close()
    
def loadDbase(dbfilename = dbfilename):
    dbfile = open(dbfilename)
    import sys
    sys.stdin = dbfile
    db = {}
    key = input()
    while key != ENDDB:
        rec = {}
        filed = input()
        while filed != ENDREC:
            name,value = filed.split(RECSEP)
            rec[name] = eval(value)
            filed = input()
        db[key] =rec
        key = input()
        return db

if __name__ == '__main__':
    from initdata import db
    storeDbase(db)
    

这个是initdata.py

bob = {'name':'bob','age':20,'pay':1000}
sus = {'name':'sus','age':30,'pay':2000}
dac = {'name':'dac','age':50,'pay':3000}
sfc = {'name':'sfc','age':40,'pay':4000}

db = {}
db['bob'] = bob
db['sus'] = sus
db['dac'] = dac
db['sfc'] = sfc

当时我写这个这段代码的时候,写成了这样子

dbfilename = 'people-file'
ENDDB='enddb.'
ENDREC='endrec.'
RECSEP='=>'

def  storeDbase(db):

    dbfile = open(dbfilename,'w')
    for key in db:
            dbfile.write (key)
            for(name,value) in db[key].items():
                dbfile.write(name + RECSEP + repr(value) + '\n')
            dbfile.write (ENDREC)
            dbfile.write(ENDDB)
    dbfile.close()
    
def loadDbase(dbfilename = dbfilename):
    dbfile = open(dbfilename)
    import sys
    sys.stdin = dbfile
    db = {}
    key = input()
    while key != ENDDB:
        rec = {}
        filed = input()
        while filed != ENDREC:
            name,value = filed.split(RECSEP)
            rec[name] = eval(value)
            filed = input()
        db[key] =rec
        key = input()
        return db

            if __name__ == '__main__':
                from initdata import db
                storeDbase(db)

细心的人已经发现了, 下面这段话的格式缩进有问题,但是在java里面只是格式不好看,并不影响编译运行,而在python里却影响,他会不执行的,因为Python是有严禁的逻辑关系的:
Python第二章——行与缩进

  if __name__ == '__main__':
                from initdata import db
                storeDbase(db)

就是这样,(>ω<)喵!!!

你可能感兴趣的:(初学python者禁忌,那些踩过的坑)