1) 编写一个简单的登录交互系统
#!/usr/bin/python
# -*- coding:utf-8 -*-
## 简单的登陆交互系统
cuser = 'admin'
cpwd = 'Passw0rd@00'
user = raw_input("Login User: ")
pwd = raw_input("Login Password: ")
n = 1
while 1:
if n < 3:
n += 1
if user != cuser or pwd != cpwd:
print "Permission denied, please try again."
user = raw_input("Login User: ")
pwd = raw_input("Login Password: ")
else:
print "Login successfully."
break
else:
print "You have tried too many times."
break
2) 模拟SQL语句的增删改查
#!/usr/bin/python
# -*- coding:utf-8 -*-
## 每个作业一个包,包里含有readme,描述如何执行
## 模拟mysql查询语句select insert update delete, 表名为user_info
sql = raw_input("Please input sql-statement here: ")
s = sql.lower().split()
f = '/root/user_info'
l = ['id', 'name', 'age', 'class']
ld = []
lf = []
lv = []
l2 = []
if s[0] == 'select' and s[2] == 'from' and s[3].startswith('user_info'): # 查
if s[1] == '*':
with open(f) as fd:
for line in fd:
print line,
elif s[1] in l:
sn = l.index(s[1])
with open(f) as fd:
for line in fd:
sline = line.split()
print sline[sn]
elif s[1].find(',') != -1:
sd = s[1].split(',')
snum = len(sd)
for i in range(snum):
if l.index(sd[i]) == -1:
print "%s: this column can't be found " % sd[i]
break
for i in range(snum):
ld.append(l.index(sd[i]))
with open(f) as fd:
for line in fd:
pline = line.split()
for i in range(snum):
print pline[ld[i]],
print
else:
print "Invalid statement"
elif s[0] == 'insert' and s[1] == 'into' and s[2] == 'user_info': # 增
r = -1
lt = lv
while s[r] != 'user_info':
l2.append(s[r])
r -= 1
l2.reverse()
s2 = ''.join(l2)
sp2 = s2.split('values')
sp2[0] = sp2[0].strip()
sp2[1] = sp2[1].strip()
sp2[0] = sp2[0][1:-1].strip()
sp2[1] = sp2[1][1:-1].strip()
spf = sp2[0].split(',')
spv = sp2[1].split(',')
fn = len(spf)
for i in range(fn):
spf[i] = spf[i].strip()
spv[i] = spv[i].strip()
if l.index(spf[i]) == -1:
print "%s: this column can't be found " % spf[i]
break
new = []
for v in l:
for i in range(fn):
if spf[i] == v:
new.append(spv[i])
i += 1
newline = '\t'.join(new)
print newline
with open(f, 'a') as fd:
fd.write(newline)
'''
elif s[0] == 'delete' and s[1] == 'from': # 删
pass
elif s[0] == 'update' and s[1] == 'user_info' and s[2] == 'set': # 改
pass
else:
print "Invalid statement"
'''