刚学习python,已经有一个星期了,试着写点代码,欢迎拍砖
[root@localhost tmp]# awk '{print NR,$0}' hh5.py
1 #!/usr/bin/python
2
3 zd={}
4 def newuser(): #newuser函数用来创建新用户。检查名字是否已存在,如果是个新名字,将要求输入
其密码(密码是明文的),用户的密码存储在字典里,以其名字做字典中的键
5 a='亲,请输入你想要创建的用户名: '
6 while True:
7 name=raw_input(a)
8 if name in zd: #判断键name是否在字典db中,存在返回True,否False
9 print '亲,用户名已存在,请重新输入: '
10 continue
11 else:
12 break
13 pwd=raw_input('亲,请输入你想要创建的密码: ')
14 zd[name]=pwd
15 def olduser(): #olduser函数用来处理已注册的老用户。如果用户名跟密码匹配,打印欢迎信息,否
则通知登录错误并返回菜单
16 name=raw_input('亲,用户名: ')
17 pwd=raw_input('亲,密码: ')
18 passwd=zd.get(name) #获得字典zd键name对应的value
19 if passwd==pwd:
20 print '亲,欢迎回来',name
21 else:
22 print '登录错误'
23
24 def showmenu(): #showmenu是主函数,给用户一个友好的界面。try-expect处理异常情况
25 a='''
26 (N)ew User Login
27 (E)xisting User Login
28 (Q)uit
29
30 Enter choice: ''' #给用户提供的菜单
31 while True:
32 while True:
33 try: #监控异常
34 choice=raw_input(a).strip().lower()
35 except(EOFError,KeyboardInterrupt): #处理异常
36 choice='q'
37 print '\n亲,你选择了: [%s]'%choice
38 if choice not in 'neq':
39 print '亲,你输入的选择无效,请重新输入'
40 else:
41 break
42 if choice=='q':break
43 if choice=='n':newuser()
44 if choice=='e':olduser()
45 if __name__=='__main__': #如果本脚本是直接被执行(不是通过import),会调用showmenu主函数
46 showmenu()
47
48
[root@localhost tmp]# python hh5.py
(N)ew User Login
(E)xisting User Login
(Q)uit
Enter choice: n
亲,你选择了: [n]
亲,请输入你想要创建的用户名: sina
亲,请输入你想要创建的密码: 123
(N)ew User Login
(E)xisting User Login
(Q)uit
Enter choice: e
亲,你选择了: [e]
亲,用户名: sina
亲,密码: wer
登录错误
(N)ew User Login
(E)xisting User Login
(Q)uit
Enter choice: e
亲,你选择了: [e]
亲,用户名: sina
亲,密码: 123
亲,欢迎回来 sina
(N)ew User Login
(E)xisting User Login
(Q)uit
Enter choice: q
亲,你选择了: [q]
[root@localhost tmp]#
对于代码34行strip()的作用,主要是用来去除字符串首尾的\n、\t、空格之类的。例子如下:
[root@localhost tmp]# python
Python 2.4.3 (#1, Jun 11 2009, 14:09:58)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-44)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> a='\n\t sina yanfa\nyunwei\tpython\t\n'
>>> a
'\n\t sina yanfa\nyunwei\tpython\t\n'
>>> print a
sina yanfa
yunwei python
>>> b=a.strip()
>>> b
'sina yanfa\nyunwei\tpython'
>>> print b
sina yanfa
yunwei python
>>>
对于代码34行lower()的作用,主要是用来转换成小写字母的。例子如下:
[root@localhost tmp]# python
Python 2.4.3 (#1, Jun 11 2009, 14:09:58)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-44)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> a='SINA python'
>>> a
'SINA python'
>>> print a
SINA python
>>> b=a.lower()
>>> b
'sina python'
>>> print b
sina python
>>>
阅读(831) | 评论(0) | 转发(0) |