算法部分
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:song
Date:18-3-20
connect:[email protected]
esac:
"""
users = {
'root':{
'name':'root',
'passwd':'westos',
'age':18,
'gender':"",
'email':['[email protected]','[email protected]']
},
'student':{
'name':'student',
'passwd':'redhat',
'age':22,
'gender':"",
'email':['[email protected]','[email protected]']
},
}
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()
(2)定義集合
定義一個空集合:
s = set()
print type(s)
字典轉化爲集合:
d = dict(a=1,b=2,c=3)
print set(d)
(3)集合特性
增加:
集合是無序的數據類型,在增加的時候會自動按照大小排序
s = {32,21,3,45,41}
s.add(13)
print s
集合不支持索引,切片,重複,連接
集合支持成員操作符:
print 1 in s
集合是可迭代的,因此支持for循環遍歷元素:
for i in s:
print i,
(4)集合的增刪改查
增加
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 ##沒有也不會報錯
題目:華爲–調查問卷
import random
N = input('生成多個個隨機數:')
s = set()
for i in range(N):
a = random.randint(1,1000)
s.add(a)
print N - len(s) ##計算重複的個數
print sorted(s)
或者:
li = list(s)
li.sort()
print li ##轉化成列表進行排序
總結:
數值類型: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':['[email protected]','[email protected]']
},
'student':{
'name':'student',
'passwd':'redhat',
'age':22,
'gender':"",
'email':['[email protected]','[email protected]']
},
}
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與微信
#
!/usr/bin/env python
encoding=utf-8
from __future__ import division
"""
Name:python與微信.py
Author:song
Date:3/21/18
connect:[email protected]
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)