您的位置:首页 > 编程语言 > Python开发

python入门到精通[二]:基本语法

2016-03-18 10:47 806 查看
上一节讲了分别在windows下和linux下的环境配置,这节以linux为例学习基本语法。代码部分需要保存到以.py结尾的文件,就可以进行测试了。这里主要介绍一些常用的语法,可能并不全面,后期再根据需要添加吧。

1.编程风格
缩进要统一

有种说法:python语言是"靠缩进控制代码的语言",的确如此。

2.注释代码

单行:#

多行:'''

代码:

#!usr/bin/env python

b='hello'
c='world'
#print '1' #注释掉此行,不打印1
'''print b
print c''' #注释掉这两行,不打印hello world
print 'ok'  #打印 ok


结果:

ok


3.字符串操作

3.1 输出多行字符串

代码:

#!usr/bin/env python

a='''the first row,
the second row,
the third row!'''
print a


结果:

the first row,
the second row,
the third row!


3.2 去掉空格

语法:s.strip(rm) 删除s字符串中开头、结尾处,位于 rm删除序列的字符

代码:

c='   hello world'
print c.strip()


结果:

hello world


3.3 计算字符串长度

语法:len()

代码:

c='   hello world'
print len(c)


结果:

14


3.4 字符串转int

代码:

#!usr/bin/env python
d = int('1')
print 'values is:',d+2


结果:

value is: 3


3.5参数化输出字符串

代码:

age=12;
print 'you are',age,'years old!'


结果:

you are 12 years old!


如果有多个参数,可以用%s输出

代码:

name = 'john'
age=21
print '''my name is:%s,
i am %s years old!''' %(name,age)


结果:

my name is:john,
i am 21 years old!


4. 用户交互

raw_input 符合用户输入的习惯,把任何用户输入都转换成字符串存储,在需要其它类型的数据时,调用相应的函数进行转换

input 用户输入什么就存储什么,所以用户输入必须符合python语法要求,否则会出错

代码:

#!usr/bin/env python

name=raw_input('please input your name:') #得到的是字符串
age=input('please input your age:')   #得到的是数字
print 'your name is %s and age is %s' % (name,age)


结果:

please input your name:john
please input your age:22
your name is john and age is 22


5. 流程控制

5.1 if...elif...else...

代码:

#!usr/bin/env python

age = 18
if age < 28:
print 'too young!'
elif age == 28:
print 'right age!'
else:
print 'too old!'


结果:

too young!


5.2while...true...

代码:

#!usr/bin/env python

while True:
name = raw_input("please input your name:").strip()
if len(name) == 0:
print "empty name!try again"
continue;
break


结果:

please input your name:
empty name!try again
please input your name:
empty name!try again
please input your name:john


5.3 for...

代码:

for i in range(1,3):
print i


结果:

1
2


5.4 for...else...

在for循环完成后才执行else;如果中途从break跳出,则连else一起跳出。

代码:

#!usr/bin/env python

#i不会>10,不走break,输出>10
for i in range(1,10):
if i>10:
break;
else:
print '>10!'

#i会>5,走break,不输出>5
for i in range(1,10):
if i>5:
break;
else:
print '>5'


结果:

>10!


6.导入模块

导入模块有三种方式:

import os

from os import system

import os as operasys

代码:

#!usr/bin/env python

#直接导入os模块,调用linux系统命令
import os
os.system('df -h')

#导入os模块的一部分,调用linux命令
from os import system
system('df -h')

#导入os模块,并且重命名为operasys,调用linux命令
import os as operasys
operasys.system('df -h')


以上三种方式,执行结果相同,都调用系统命令df -h显示磁盘使用情况。

7.文件操作

7.1创建

f=file('contact_list.txt','w')    #'w'如果文件不存在,创建文件,存在则打开
f.write('hello')
f.close()


创建一个contact_list.txt文件,文件内容为'hello'.

7.2读取

file f=file('contact_list.txt')
f.read() #读取一遍之后就没了,需要再次取值需保存到变量
f.read([size]) #size为读取的长度,以byte为单位
f.readline([size]) #读一行,如果定义了size,有可能返回的只是一行的一部分
f.readlines([size]) #把文件的每一行作为一个list的一个成员,并返回这个list


7.3追加

f=file('contact_list.txt','a')
f.write('hello')
#f.flush()  #写日志的时候可以用这个
f.close()


以上代码将'contact_list.txt'文件结尾追加内容'hello'.

7.4位置

f.tell() #返回文件操作标记的当前位置,以文件开头为原点
f.next() #返回下一行,并将文件操作标记位移到下一行
f.seek(offset[,whence]) #将文件的操作标记移到offset的位置。


7.5内容替换

#!usr/bin/env python

import fileinput
for line in fileinput.input('1.txt',inplace=1):#做完替换后,立刻回到文件的开始行
line = line.replace('004','003')
print line,#此行必须有,否则替换不成功  


关于文件的open模式:
  w 以写模式打开
  a 以追加模式打开(从EOF开始,必要时创建新文件)
  r+ 以读写模式打开
  w+ 以读写模式打开 (参见w)
  a+ 以读写模式打开 (参见a)
  rb 以二进制读模式打开
  wb 以二进制写模式打开 (参见w)
  ab 以二进制追加模式打开 (参见a)
  rb+ 以二进制读写模式打开 (参见r+)
  wb+ 以二进制读写模式打开 (参见w+)
  ab+ 以二进制读写模式打开(参见a+)

8.目录操作

import os
  os.getcwd() #获取当前目录
os.mkdir('file') 创建目录
  os.listdir('.') #返回指定目录下的所有文件和目录名
  os.remove() #删除目录下文件
  os.path.isfile() #检测路径是文件还是目录
  os.path.isdir() #检测路径是文件还是目录
  os.path.isabs() #判断是否是绝对路径
  os.path.exist() # 检验给出的路径是否真的存在

  os.path.split() #返回一个路径的目录名和文件名
  os.path.dirname() #返回一个路径的路径名
  os.path.basename() #返回一个路径的文件名

  os.rename(old,new) #目录重命名
  os.path.getsize(filename) #获取文件大小
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: