在了解 Python 的基本概念和数据结构后, 再了解一下基本语法来将这些零件合理的组合起来,这样就可以用 Python 干一下复杂的任务了,再熟悉一下文件操作来扩展一下输入输出。
基本语法
条件语句
代码演示
score = 70
if score > 100 :
print 'the score is out of range.'
elif score > 60 :
print 'your score is from 60 to 100.'
elif score > 0 :
print 'your score is from 0 to 60.'
else :
print 'the score is out of range.'
for循环语句
代码演示
colors = ['red','blue','green']
for color in colors
print 'color is ' + color
# print the numbers from 0 through 99
for i in range(100):
print i
while循环语句
代码演示
# list中元素a在哪个位置
i = 0
while i < len(list):
if list[i] == a :
print i
break
else :
i += 1
文件操作
Python 处理文件也是有一手的,所以熟练掌握文件操作对日后的任务操作非常有利.
打开/关闭文件
代码演示
# 显示文本
f = open('foo.txt', 'rU') ## r/w/a同c里面的意义,U代表通用,最终的结尾符转换成'\n'
for line in f: # 遍历文件的每一行
print line, # 紧跟 ,这样print就不会输出换行符,因为line里面就有换行符
f.close()
读写文本
读文本到内存,返回一个 list
f.readlines()
读文本到字符串,返回字符串(配合正则表达式)
f.read()
写数据到输出文件
f.write(string)
print >>f ,string
print(string, file=f)
unicode文本操作
codecs模块支持
import codecs
f = codecs.open('foo.txt', 'rU', 'utf-8')
for line in f:
# here line is a *unicode* string
# 用f.write()写文件,print不完全支持unicode
如果该文章对您产生了帮助,麻烦动手点赞支持一下。