Python編程
本實驗使用Ubuntu系統
Python官網下載 www.python.org
Ubuntu官網下載 www.ubuntu.org.cn
wangchao@wangchao-virtual-machine:~$ python–V //查看python版本
Python 2.7.6
本實驗適用python版本爲2.6、2.7
編程風格:
語法要求:統一縮進
變量:標識符第一個字符必須是字母表中的字母或下劃線,標識符由下劃線、字母、數字組成,標識符對大小寫敏感
wangchao@wangchao-virtual-machine:~$ 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 //設置別名
wangchao@wangchao-virtual-machine:~$ 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鍵可補全命令配置
wangchao@wangchao-virtual-machine:~$ cd/usr/lib/python2.7/
wangchao@wangchao-virtual-machine:/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
wangchao@wangchao-virtual-machine:/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') //將一路徑加入系統路徑
angchao@wangchao-virtual-machine:/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
wangchao@wangchao-virtual-machine:~/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)
程序結果:
wangchao@wangchao-virtual-machine:~/python$python ask_name.py
name:wang
age:22
sex:nang
job:IT
---------------------------
name:wang
age:22
sex:nang
job:IT
Python流程控制
If………else…..
wangchao@wangchao-virtual-machine:~/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
程序運行結果
wangchao@wangchao-virtual-machine:~/python$python ask_name.py
name:aaa
age:22
sex:nang
job:IT
---------------------------
1
name:aaa
age:22
sex:nang
job:IT
wangchao@wangchao-virtual-machine:~/python$python ask_name.py
name:wang
age:30
sex:nang
job:IT
---------------------------
good
name:wang
age:30
sex:nang
job:IT
wangchao@wangchao-virtual-machine:~/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不輸出。
wangchao@wangchao-virtual-machine:~$ vimfor.py
for i in range(1,9):
if i == 3:
print "good", i
else:
print 'The number is :', i
wangchao@wangchao-virtual-machine:~$ 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 跳出本次循環
編寫程序:
程序功能:判斷用戶名,密碼是否正確,不正確無限循環
參考方法:
wangchao@wangchao-virtual-machine:~/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
程序運行結果
wangchao@wangchao-virtual-machine:~/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
wangchao@wangchao-virtual-machine:~/python$vim continue.py
wangchao@wangchao-virtual-machine:~/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
查詢關鍵字:姓名
參考代碼
wangchao@wangchao-virtual-machine:~/python$vim contact_list.txt //將內容寫入文件
1 cai chengxnew 1885
2 ru gongchengshi 1886
3 chao gongchengshi 1887
4 yao chengxuyuan 1888
wangchao@wangchao-virtual-machine:~/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
程序結果:
wangchao@wangchao-virtual-machine:~/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
部分語法使用講解
wangchao@wangchao-virtual-machine:~/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() //關閉文件
>>>
wangchao@wangchao-virtual-machine:~/python$ls //文件已創建
new.txt
wangchao@wangchao-virtual-machine:~/python$cat new.txt
hello,world
wangchao@wangchao-virtual-machine:~/python$python
>>> f=file('new.txt','w') //重新打開文件
>>> f.write('hehe')
>>> f.flush() //將內存中數據寫入硬盤
>>> f.write('yyy!\n') //未重新打開不會被覆蓋
>>> f.flush()
>>> f.close() //關閉
wangchao@wangchao-virtual-machine:~/python$cat new.txt
heheyyy!
>>> f=file('new.txt','a') //文件進入追加模式,不覆蓋原文件
>>> f.write('\n ddd')
>>> f.flush()
>>>
wangchao@wangchao-virtual-machine:~/python$cat new.txt
heheyyy!
ddd