第一个python程序

Alex posted @ 2011年8月22日 23:48 in python , 2033 阅读

    很早很早就想学python,一直没开动,今天突然兴起,照着书敲了2个demo,第一个if语句那一直报错,不知道错哪。。。。

     

#!/usr/bin/env python
'makeTextFile.py -- create text file'

import os
ls = os.linesep

#get filename
while True:

if os.path.exists(fname):
    print "ERROR: '%s' already exists" %fname
else:
    break

#get file content (text) lines
all = []
print "\nEnter lines ('.' by itself to quit).\n"

#loop until user terminates input
while True:
    entry = raw_input('>')
        break;
    else:
        all.append(entry)

#write lines to file with proper line ending
fobj = open(fname,'w')
fobj.writelines(['%s%s' % (x,ls) for x in all])
fobj.close()
print 'DONE!'

 

第2个 可以运行了。。

 

#!/user/bin/env python

'readTextFile.py -- read and display text file'

# get filename
fname = raw_input('Enter filename:')
print

#attempt to open file for reading
try:
    fobj = open(fname,'r')
except IOError,e:
    print "***file open error:",e
else:
    #display contents to the screen
    for eachLine in fobj:
        print eachLine,
    fobj.close()

先这样了  还要做俯卧撑,然后洗澡睡觉~

 

 

2011-08-23  09:13

经过网友的热心帮助  修改makeTestFile.py如下 

 

#!/usr/bin/env python
'makeTextFile.py -- create text file'
 
import os
ls = os.linesep
 
#get filename
while True:
 
    if os.path.exists(fname):
        print "ERROR: '%s' already exists" %fname
    else:
        break
 
#get file content (text) lines
all = []
print "\nEnter lines ('.' by itself to quit).\n"
 
#loop until user terminates input
while True:
    entry = raw_input('>')
    break;
else:
    all.append(entry)
 
#write lines to file with proper line ending
fobj = open(fname,'w')
fobj.writelines(['%s%s' % (x,ls) for x in all])
fobj.close()
print 'DONE!'
Avatar_small
Garfileo 说:
2011年8月23日 08:08

第一个出错的原因是 while 中的代码没有缩进。

python 是要求代码必须有正确的缩进,才可以被解析成功。

Avatar_small
shayo 说:
2011年8月23日 09:07

@Garfileo: 谢谢阿 改了下 发现 后那个while的break缩进也错了。。


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter