Python编程
本实验使用Ubuntu系统
Python官网下载 www.python.org
Ubuntu官网下载 www.ubuntu.org.cn
[email protected]:~$ python–V //查看python版本
Python 2.7.6
本实验适用python版本为2.6、2.7
编程风格:
语法要求:统一缩进
变量:标识符第一个字符必须是字母表中的字母或下划线,标识符由下划线、字母、数字组成,标识符对大小写敏感
[email protected]:~$ python
>>> a= ‘hello,everybody,my name iswang‘
>>> a
‘hello,everybody,my name is wang‘
>>> a="hello,everybody,I‘m wang"
>>> a
"hello,everybody,I‘m wang"
>>> a=‘‘‘hello, everybody,I‘m wang\n
... 1
... 2
... 3
... A
... ‘‘‘
>>> print a
hello, everybody,I‘m wang
1
2
3
A
//单引号、双引号、三引号使用。
赋值例子:
>>> user_name=‘wang‘
>>> age=22
>>> next_year_age=age+1
运算例子
>>> 3+5
8
>>> 2*3
6
>>> a=4
>>> b=5
>>> a>b
False
>>> a<b
True
导入模块:
Import modulename //导入模块
From module import aaa //当模块太大时,只想导入某一功能
Import modulename as newname //设置别名
[email protected]:~$ python
>>> import sys //导入sys模块
>>> sys.path //使用sys.path功能sys.path列出python列表路径
[‘‘, ‘/usr/lib/python2.7‘,‘/usr/lib/python2.7/plat-i386-linux-gnu‘, ‘/usr/lib/python2.7/lib-tk‘,‘/usr/lib/python2.7/lib-old‘, ‘/usr/lib/python2.7/lib-dynload‘, ‘/usr/local/lib/python2.7/dist-packages‘,‘/usr/lib/python2.7/dist-packages‘,‘/usr/lib/python2.7/dist-packages/PILcompat‘,‘/usr/lib/python2.7/dist-packages/gtk-2.0‘,‘/usr/lib/python2.7/dist-packages/ubuntu-sso-client‘]
>>> help(sys)
在python中使用tab键可补全命令配置
[email protected]:~$ cd/usr/lib/python2.7/
[email protected]:/usr/lib/python2.7$vim tab.py
#!/usr/bin/python2.7
# python startup file
import sys
import readline
import rlcompleter
import atexit
import os
# tab completion
readline.parse_and_bind(‘tab: complete‘)
# history file
histfile = os.path.join(os.environ[‘HOME‘],‘.pythonhistory‘)
try:
readline.read_history_file(histfile)
except IOError:
pass
atexit.register(readline.write_history_file,histfile)
del os, histfile, readline, rlcompleter
[email protected]:/usr/lib/python2.7$python
>>> import tab //导入tab模块·,可使用tab键补全
>>> import sys
>>> sys.version_info //可使用TAB键补全命令
sys.version_info(major=2, minor=7, micro=6,releaselevel=‘final‘, serial=0)
>>> sys.path.append(‘/pathon‘) //将一路径加入系统路径
[email protected]:/usr/lib/python2.7$python
>>> from sys import path
>>> path
[‘‘, ‘/usr/lib/python2.7‘,‘/usr/lib/python2.7/plat-i386-linux-gnu‘, ‘/usr/lib/python2.7/lib-tk‘,‘/usr/lib/python2.7/lib-old‘, ‘/usr/lib/python2.7/lib-dynload‘,‘/usr/local/lib/python2.7/dist-packages‘, ‘/usr/lib/python2.7/dist-packages‘,‘/usr/lib/python2.7/dist-packages/PILcompat‘,‘/usr/lib/python2.7/dist-packages/gtk-2.0‘,‘/usr/lib/python2.7/dist-packages/ubuntu-sso-client‘]
>>> sys.version_info
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name ‘sys‘ is not defined
//只导入sys中path,path可以用了,sys.version_info不可以用
>>> from sys importpath,version_info
>>> version_info
sys.version_info(major=2, minor=7, micro=6,releaselevel=‘final‘, serial=0)
//导入两个version_info可使用了
>>> import sys,os //同时导入多个模块,os可调用shell的命令
>>> os.system(‘pwd‘) //使用pwd命令
/usr/lib/python2.7
0
>>> os.system(‘uname -a‘)
Linux wangchao-virtual-machine3.16.0-30-generic #40~14.04.1-Ubuntu SMP Thu Jan 15 17:45:15 UTC 2015 i686 i686i686 GNU/Linux
0
>>> from sys import version_infoas v //当名字过长时可设置别名
>>> v //v使用别名(sys.version_info)
sys.version_info(major=2, minor=7, micro=6,releaselevel=‘final‘, serial=0)
>>> os.system(‘df -h‘)
Filesystem Size Used Avail Use% Mounted on
/dev/sda1 19G 3.5G 15G 20% /
none 4.0K 0 4.0K 0% /sys/fs/cgroup
udev 493M 4.0K 493M 1% /dev
tmpfs 101M 1.3M 100M 2% /run
none 5.0M 0 5.0M 0% /run/lock
none 502M 152K 502M 1% /run/shm
none 100M 44K 100M 1% /run/user
/dev/sr0 1003M 1003M 0 100% /media/wangchao/Ubuntu 14.04.2 LTSi386
0
//最后一个值为0,表示命令执行成功。非0表示执行失败,可用于判断命令执行是否成功
>>> os.system(‘aaa‘)
sh: 1: aaa: not found
32512
>>> if os.system(‘aaa‘)!=0:print‘command excution failed!‘
...
sh: 1: aaa: not found
command excution failed!
用户交互
Raw_input()
小程序:1.询问用户姓名,年龄,性别,工作,工资;2.以格式化方式输出:
Information of company staff
Name:xx
Age:XX
Sex:xx
Job:xx
[email protected]:~/python$vim ask_name.py
#!/usr/bin/env python
name = raw_input(‘name:‘)
age =int( raw_input(‘age:‘))
sex = raw_input(‘sex:‘)
job = raw_input(‘job:‘)
#print‘\tname:‘,name,‘\n\tage:‘,age,‘\n\tsex‘,sex,‘\n\tjob‘,job
print(‘---------------------------\n‘)
#if age < 28:
# print"1"
#elif name ==‘wang‘:
print"good"
#else:
# print"2"
print ‘‘‘\tname:%s
\tage:%d
\tsex:%s
\tjob:%s ‘‘‘%(name,age,sex,job)
程序结果:
[email protected]:~/python$python ask_name.py
name:wang
age:22
sex:nang
job:IT
---------------------------
name:wang
age:22
sex:nang
job:IT
Python流程控制
If………else…..
[email protected]:~/python$vim ask_name.py
#!/usr/bin/env python
name = raw_input(‘name:‘)
age =int( raw_input(‘age:‘))
sex = raw_input(‘sex:‘)
job = raw_input(‘job:‘)
#print‘\tname:‘,name,‘\n\tage:‘,age,‘\n\tsex‘,sex,‘\n\tjob‘,job
print(‘---------------------------\n‘)
if age < 28:
print"1"
elif name ==‘wang‘:
print"good"
else:
print"2"
print ‘‘‘\tname:%s
\tage:%d
\tsex:%s
\tjob:%s ‘‘‘%(name,age,sex,job)
//如果年龄小于28,打印1;年龄大于28,姓名为wang打印good;否则打印2
程序运行结果
[email protected]:~/python$python ask_name.py
name:aaa
age:22
sex:nang
job:IT
---------------------------
1
name:aaa
age:22
sex:nang
job:IT
[email protected]:~/python$python ask_name.py
name:wang
age:30
sex:nang
job:IT
---------------------------
good
name:wang
age:30
sex:nang
job:IT
[email protected]:~/python$python ask_name.py
name:aaa
age:40
sex:nang
job:IT
---------------------------
2
name:aaa
age:40
sex:nang
job:IT
python流程控制2
>>> range(1,10) //输出1-9
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> for i in range(1,9): //输出1-8
... print ‘The number is: %d‘ % i
...
The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 5
The number is: 6
The number is: 7
The number is: 8
再加个判断
>>> for i in range(1,9):
... if i ==3:
... print "good", i
... print ‘The number is: %d‘ % i
...
The number is: 1
The number is: 2
good 3
The number is: 3
The number is: 4
The number is: 5
The number is: 6
The number is: 7
The number is: 8
在以上程序上,输出good,了下一行3不输出。
[email protected]:~$ vimfor.py
for i in range(1,9):
if i == 3:
print "good", i
else:
print ‘The number is :‘, i
[email protected]:~$ pythonfor.py
The number is : 1
The number is : 2
good 3
The number is : 4
The number is : 5
The number is : 6
The number is : 7
The number is : 8
流程控制3
While Ture:
Break 跳出循环
Continue 跳出本次循环
编写程序:
程序功能:判断用户名,密码是否正确,不正确无限循环
参考方法:
[email protected]:~/python$vim while.py
while True:
input = raw_input("please input your username:")
if input ==‘wang‘:
password =raw_input("please input your passwd:")
p = ‘123‘
while password != p:
password =raw_input("please input your passwd again:")
else:
print "welcometo"
break
else:
print "Sorry,user %s notfound" % input
程序运行结果
[email protected]:~/python$python while.py
please input your username:aaa
Sorry,user aaa not found
please input your username:rrr
Sorry,user rrr not found
please input your username:wang
please input your passwd:eee
please input your passwd again:123
welcome to
[email protected]:~/python$vim continue.py
[email protected]:~/python$python continue.py
while True:
input = raw_input("please input your username:")
if input ==‘wang‘:
password =raw_input("please input your passwd:")
p = ‘123‘
while password != p:
password =raw_input("please input your passwd again:")
else:
print "welcometo"
continue
else:
print "Sorry,user %s notfound" % input
程序运行结果
please input your username:qqq
Sorry,user qqq not found
please input your username:wang
please input your passwd:ddd
please input your passwd again:ccc
please input your passwd again:123
welcome to
please input your username:aaa
Sorry,user aaa not found
please input your username:
两个程序不同处为break、continue。Break为输入用户密码正确后,跳出循环;continue输对后,跳出本次循环,继续输入。
Python练习程序
编写可供用户查询的员工信息表
- 需用户认证
- ID name department phone
- 查询关键字:姓名
参考代码
[email protected]:~/python$vim contact_list.txt //将内容写入文件
1 cai chengxnew 1885
2 ru gongchengshi 1886
3 chao gongchengshi 1887
4 yao chengxuyuan 1888
[email protected]:~/python$vim chaxun.py
#!/usr/bin/python
while True:
input=raw_input(‘input uname:\n‘)
if input == ‘admin‘:
upasswd = raw_input(‘inputpasswd:\n‘)
p=‘123‘
while upasswd != p:
upasswd =raw_input(‘input passwd again\n‘)
else:
print ‘Welcome login\n‘
while True:
match_yes=0
input=raw_input("\033[32mPlease input name forsearch:\033[0m")
contact_file =file(‘contact_list.txt‘)
while True:
line =contact_file.readline()
if len(line)==0:break
ifinput in line:
print ‘Match item \033 %s\033‘ % line
match_yes = 1
else:
pass
if match_yes ==0 :print ‘NO match item found‘
else:
print "sorry,user %s notfound" % input
程序结果:
[email protected]:~/python$python chaxun.py
input uname:
admin
input passwd:
123
Welcome login
Please input name for search:cai
Match item cai chengxnew 1885
Please input name for search:wang
NO match item found
Please input name for search:chao
Match item chao gongchengshi 1887
部分语法使用讲解
[email protected]:~/python$python
>>> file(‘contact_list.txt‘) //导入文件
<open file ‘contact_list.txt‘, mode ‘r‘at 0xb7443180>
>>>file(‘contact_list.txt‘).read() //读取该文件
‘1 cai chengxnew 1885\n2 ru gongchengshi 1886\n3 chao\tgongchengshi 1887\n4 yao chengxuyuan 1888\n‘
>>> c=file(‘contact_list.txt‘) //赋值
>>> c.readline() //读取每一行
‘1 cai chengxnew 1885\n‘
>>> c.readline()
‘2 ru gongchengshi 1886\n‘
>>> c.readline()
‘3 chao\tgongchengshi 1887\n‘
>>> c.readline()
‘4 yao chengxuyuan 1888\n‘
>>> c.readline()
‘‘
>>> len(c.readline()) //读取该行有多少字符
0
>>> c = file(‘contact_list.txt‘)
>>> c.readline()
‘1 cai chengxnew 1885\n‘
>>> len(c.readline())
26
>>> while True:
... line=c.readline()
... if len(line)==0:break
... print line
...
3 chao gongchengshi 1887
4 yao chengxuyuan 1888
>>> c.close() //关闭文件
>>> f=file(‘new.txt‘,‘w‘) //打开新文件
>>> f.write(‘hello,world‘) //写入内容
>>> f.close() //关闭文件
>>>
[email protected]:~/python$ls //文件已创建
new.txt
[email protected]:~/python$cat new.txt
hello,world
[email protected]:~/python$python
>>> f=file(‘new.txt‘,‘w‘) //重新打开文件
>>> f.write(‘hehe‘)
>>> f.flush() //将内存中数据写入硬盘
>>> f.write(‘yyy!\n‘) //未重新打开不会被覆盖
>>> f.flush()
>>> f.close() //关闭
[email protected]:~/python$cat new.txt
heheyyy!
>>> f=file(‘new.txt‘,‘a‘) //文件进入追加模式,不覆盖原文件
>>> f.write(‘\n ddd‘)
>>> f.flush()
>>>
[email protected]:~/python$cat new.txt
heheyyy!
ddd