算法部分
from __future__ import division
print """
算法
1.加
2.减
3.乘
4.除
"""
while True:
first_num = input("请输入第一个数字:")
action = input("请输入你的选择:")
sec_num = input("请输入第二个数字:")
if action == 1:
res = first_num + sec_num
elif action == 2:
res = first_num - sec_num
elif action == 3:
res = first_num * sec_num
elif action == 4:
if sec_num == 0:
print "除数不能为0!"
continue
else:
res = first_num / sec_num
else:
print "error"
print res
使用字典
num1 = input("num1:")
oper = input("oper:")
num2 = input("num2:")
d = {
'+':num1 + num2
'-':num1 - num2
'*':num1 * num2
'/':num1 / num2
}
print d.get(oper)
用户管理系统
#!/usr/bin/env python
#encoding=utf-8
"""
Name:用户管理系统.py
Author:han
Date:18-7-20
connect:111111111@qq.com
esac:
"""
users = {
'root':{
'name':'root',
'passwd':'westos',
'age':18,
'gender':"",
'email':['westos@qq.com','redhat@126.com']
},
'student':{
'name':'student',
'passwd':'redhat',
'age':22,
'gender':"",
'email':['525065007@qq.com','redhat@126.com']
},
}
count = 0
while count < 3:
while True:
print """
用户管理系统
1. 注册
2. 登陆
3. 注销
4. 显示
5. 退出
"""
choice = raw_input("请输入你的选择:")
if choice == "1":
print
username = raw_input("请输入用户名:")
if username in users:
print "该用户名已被注册!"
else:
passwd = raw_input("请输入密码:")
while True:
gender = raw_input("0-女性,1-男性:")
if gender:
break
else:
print "该项为必填项!"
while True:
age = raw_input("请输入年龄:")
if age:
break
else:
print "该项为必填项!"
email = raw_input("请输入邮箱:")
if not email:
email = None
users[username] = {
'name': username,
'passwd': passwd,
'gender':gender,
'age': age,
'email': email,
}
print "%s用户注册成功!"%(username)
elif choice == "2":
login_user = raw_input("登陆用户名:")
login_passwd = raw_input("请输入密码:")
if login_user in users:
if login_passwd in users[login_user]["passwd"]:
print "登陆成功!"
else:
count += 1
if count == 3:
print "错误3次!!!"
exit()
print "密码错误!"
else:
print "无此用户名!"
break
elif choice == "3":
del_username = raw_input("请输入要注销的用户:")
users.pop(del_username)
elif choice == "4":
print users.keys()
elif choice == "5":
exit(0)
else:
print "登陆次数超过3次,请稍后再试!!"
ATM取款系统
info = """ ATM柜员机管理系统
1.取款 4.查询余额
2.存款 5.修改密码
3.转账 6.退出
"""
d = {
123: {
"card": 123,
"passwd": 123,
"money": 666
}
}
Times = 0
while 1:
Card = input("请输入卡号:")
Passwd = input("请输入密码:")
if Card in d and Passwd == d[Card]["passwd"]:
while 1:
print info
choice = raw_input("please input your action:")
if choice == "1":
while 1:
a = input("请输入取款金额:")
if d[Card]["money"] >= a:
print "取款成功"
a1 = d[Card]["money"] - a
d[Card].update(money=a1)
break
else:
print "余额不足!!!"
break
elif choice == "2":
b = input("请输入存款金额:")
b1 = d[Card]["money"] + b
d[Card].update(money=b1)
print "¥%d已存入,总余额为:%d" % (b, b1)
elif choice == "3":
d4 = input("请输入转账帐号:")
if d4 == Card:
print "请输入其他帐号!!!"
else:
while 1:
d1 = input("请输入转账金额:")
d2 = input("请输入密码:")
if d2 == d[Card]["passwd"]:
if d[Card]["money"] >= d1:
Times = 0
d3 = d[Card]["money"] - d1
d[Card].update(money=d3)
print "转账成功,你的余额为:%d" % (d3)
break
else:
print "余额不足!!!"
break
else:
Times += 1
if Times == 3:
print "卡已冻结!!!"
exit()
print "密码输入有误!!!"
elif choice == "4":
print "你的余额为:¥%d" % (d[Card]["money"])
elif choice == "5":
c = input("请输入原密码:")
if c == d[Card]["passwd"]:
Times = 0
while 1:
c1 = input("请输入新密码:")
c2 = input("请再次输入:")
if c1 == c2:
print "密码修改成功!!!"
d[Card].update(passwd=c2)
break
else:
print "密码输入不一致,请重新输入!!!"
else:
print "密码输入有误!!!"
Times += 1
if Times == 3:
print "卡已冻结!!!"
exit()
continue
elif choice == "6":
print "请拔出银行卡!!!"
exit()
else:
print "输入有误,请重新输入!!!"
else:
print "卡号或密码输入有误!!!"
Times += 1
if Times == 3:
print "卡已冻结!!!"
exit()
continue
集合
1.集合操作
#集合是不重复的数据类型:
s = {1,2,3,4,1,2}
#字典中的key值不能重复:
d = {
'a':1,
'b':2,
}
print s
去重:
1.转化成集合set
li = [1,2,3,4,1,2]
print set(li) ##print list(set(li))
2.转换成字典,拿出所有的key,dict()不能直接将列表转化为字典
print {}.fromkeys(li).keys()
定义集合
定义一个空集合:
s = set()
print type(s)
字典转化为集合
d = dict(a=1,b=2,c=3)
print set(d)
集合特性
增加: 集合是无序的数据类型,在增加的时候会自动按照大小排序
s = {32,21,3,45,41}
s.add(13)
print s
集合不支持索引,切片,重复,连接
集合支持成员操作符:
print 1 in s
集合是可迭代的,因此支持for循环遍历元素:
for i in s:
print i,
集合的增删改查
增加
s = {1,2,3}
s.add(4)
s.update({3,4,5,6})
s.update('hello')
s.update([1,2])
特殊计算(交集并集)
s1 = {1,2,3}
s2 = {1,3,4}
print s1.intersection(s2)
print s1.intersection_update(s2) ##更新s1为交集,返回值为none
print s1,s2 ##此时s1为交集
print s1 & s2 ##交集
print s1 | s2 ##并集
print s1 - s2 ##差集
print s1 ^ s2 ##对等差分,把不同的取出来。
print s1.issubset(s2) ##是不是子集
print s2.issuperset(s1) ##是不是真子集
print s1.isdisjoint(s2) ##不是子集为真,是子集为假
删除
print s1.pop() ##随机弹出
s1.remove(5)
print s1 ##没有会报错
s1.discard('a')
print s1 ##没有也不会报错
总结:
数值类型:int,long,float,complex,bool
str,list,tuple,dict,set
可变数据类型list,dict,set
不可变数据类型:
#直接改变数据本身,没有返回值
可迭代的数据类型:str,list,tuple,dict,set
不可迭代的数据类型:数值类型
#是否可以for循环遍历元素
有序的数据类型:str,list,tuple,
无序的数据类型:dict,set
#是否支持索引,切片,重复,连接等特性
函数
python中如果函数无返回值,默认返回none
def 函数名(形参)
函数体
return 返回值
函数名(实参)
print 函数名
#定义了一个函数
def fun(name,age,sex) #形式参数(形参)
print "hello %s"%(name)
#调用函数
fun("python",22,0) #实参
在python中提供一个可变形参:
def fun(*args):
print args
fun("python",12,0)
#必选参数
#默认参数
#可变参数》》》》》*args args = 元组类型
def fun(name='python'):
print name
fun()
##这里**kwargs表示传的是字典
def fun(name,age,**kwargs):
print name,age,kwargs
fun('fentiao',22,city='chongqing',country='China')
用函数的方法表示算法
from __future__ import division
a = input("num1:")
action = raw_input("运算符:")
b = input("num2:")
def add(a, b):
return a + b
def minus(a, b):
return a - b
def times(a, b):
return a * b
def div(a, b):
if b == 0:
raise IOError
else:
return a / b
d = {
'+':add,
'-':minus,
'*':times,
'/':div,
}
if action in d:
print d[action](a,b)
else:
print "请输入正确的运算符!"
函数的形式参数的默认值不要是可变参数
def add_end(L=[]): #默认参数
L.append('END')
return L
print add_end([1,2,3])
print add_end()
print add_end()
参数组合时候顺序:必选参数>默认参数>可变参数>关键字参数
def fun(a,b=0,*args,**kwargs):
print a,b,args,kwargs
fun(1,2,3,4,5,6,x=1,y=2,z=3)
用户管理系统(用函数方法)
users = {
'root':{
'name':'root',
'passwd':'westos',
'age':18,
'gender':"",
'email':['westos@qq.com','redhat@126.com']
},
'student':{
'name':'student',
'passwd':'redhat',
'age':22,
'gender':"",
'email':['525065007@qq.com','redhat@126.com']
},
}
print """
用户管理系统
1. 注册
2. 登陆
3. 注销
4. 显示
5. 退出
"""
def Usercreate():
username = raw_input("请输入用户名:")
if username in users:
print "该用户名已被注册!"
else:
passwd = raw_input("请输入密码:")
while True:
gender = raw_input("0-女性,1-男性:")
if gender:
break
else:
print "该项为必填项!"
while True:
age = raw_input("请输入年龄:")
if age:
break
else:
print "该项为必填项!"
email = raw_input("请输入邮箱:")
if not email:
email = None
users[username] = {
'name': username,
'passwd': passwd,
'gender': gender,
'age': age,
'email': email,
}
print "%s用户注册成功!" % (username)
def Userlogin():
login_user = raw_input("登陆用户名:")
login_passwd = raw_input("请输入密码:")
if login_user in users:
if login_passwd in users[login_user]["passwd"]:
print "登陆成功!"
else:
print "密码错误!"
else:
print "无此用户名!"
def userdel():
del_username = raw_input("请输入要注销的用户:")
users.pop(del_username)
def showuser():
print users.keys()
def main():
while True:
choice = raw_input("请输入你的选择:")
if choice == "1":
Usercreate()
elif choice == "2":
Userlogin()
elif choice == "3":
userdel()
elif choice == "4":
showuser()
elif choice == "5":
exit(0)
else:
print "请输入正确的选项!"
else:
print "登陆次数超过3次,请稍后再试!!"
if __name__=="__main__"
main()
全局变量和局部变量
a = 10 ##全局变量
def fun()
a = 100 ##函数内局部变量
fun()
print a ##输出为10
python判断微信里面的男女比例
from __future__ import division
"""
Name:python与微信.py
Author:han
Date:7/20
connect:11111111@qq.com
esac:
"""
import itchat
itchat.auto_login(hotReload=True)
# itchat.send('hello song',toUserName='filehelper')
# itchat.send_file('/etc/passwd',toUserName='filehelper')
info = itchat.get_friends()
yourinfo = info[0]
friendsinfo = info[1:]
male = female = other = 0
for friend in friendsinfo:
sex = friend[u'Sex']
if sex == 1:
male += 1
elif sex == 1:
male += 1
elif sex == 2:
female += 1
else:
other += 1
all = male + female + other
print "男: %.2f%%" % ((male / all) * 100)
print "女: %.2f%%" % ((female / all) * 100)
print "其他: %.2f" % ((other / all) * 100)
判断质数
def isPrime(n):
for i in range(2, n):
if n % i == 0:
return False
else:
return True
n = input("N:") + 1
print [i for i in range(2, n) if isPrime(i)]
输出a1,a2,a3,b1,b2,b3,c1,c2,c3:
print [i+j for i in 'abc' for j in '123']
找出目录下的.log结尾的文件
import os
print [i for i in os.listdir('/var/log') if i.endswith('.log')]
找出质数对
def isPrime(n):
for i in range(2, n):
if n % i == 0:
return False
else:
return True
n = input("N:") + 1
primes = [i for i in range(2, n) if isPrime(i)]
pair_primes = []
for i in primes:
for j in primes:
if i+j == n - 1 and i <= j:
pair_primes.append((i,j))
print primes
print pair_primes
print len(pair_primes)
或者
def isPrime(n):
for i in range(2, n):
if n % i == 0:
return False
else:
return True
n = input("N:") + 1
primes = [i for i in range(2, n) if isPrime(i)]
for i in primes:
if n -1 - i in primes and (i <= n -1 - i):
pair_primes.append((i,n - 1 -i))
print pair_primes
print len(pair_primes)