字典
一、字典的定义
d=dict(a=2,b='hello') ##直接定义赋值
d={}.fromkeys() ##采用fromkeys函数定义
打印模块pprint,使输出更美观
import pprint ##导入模块
user=[]
for i in range (10): ##生成user列表中user1 - user10用户
user.append('user%d' %(i+1))
pprint.pprint({ }.fromkeys(user.'123456')) ##赋值所有key值为:123456
二、字典的操作
1.查看key值对应的value值
print(d['b']) ##value值存在时,输出;不存在时,报错
print(d['f'])
print(d.get('b')) ##value值存在时,输出;不存在时,输出None
print(d.get('f'))
2.指定输出字典的key、value、key-value
print(d.keys()) ##打印字典中所有的key值
print(d.values()) ##打印字典中所有的value值
print(d.items()) ##打印字典中所有的key-value值对
3.修改字典元素
d['a']=100 ##key存在时,修改对应的value值;不存在时,新增
d['f']=11
d2=dict(a=110,x=0) ##key存在时,覆盖原value值;不存在时,新增
print(d.update(d2))
d.setdefault('a',100) ##key存在时,不做操作;不存在时,新增
d.setdefault('x',100)
4.遍历字典
for key,value in d.items():
print(key,value)
5.删除字典元素
del d['a'] ##key值存在则删除;不存在则报错
del d['f']
value=d.pop('a') ##key值存在则删除,返回对应的value值;不存在则报错
value=d.pop('f')
pair=d.popitem() ##随机删除,一般是最后一个,返回值为key-value值对
print(d,pair)
6.实现switch,case功能
注意:python不支持switch,case功能,需要用其他方法实现
num1 = int(input('please input a num:'))
choice = input('please make your choice:')
num2 = int(input('please input a num:'))
dict = { ##实现两个int数字加减乘除的效果
'+': num1 + num2,
'-': num1 - num2,
'*': num1 * num2,
'/': num1 / num2,
}
print(dict.get(choice, 'error')) ##get()函数默认为None
7.列表去重的第二种方法
a=[1,3,4,3,6,1]
print({}.fromkeys(a).keys()) ##拿出字典的key值
##将列表生成字典,相同key值会自动覆盖,value值默认为none
三、练习
1.生成172.25.254.1~172.25.254.200随即IP,并统计次数`
import pprint ##pprint模块,输出更美观
import random ##random模块,生成随机数
d = {} ##定义一个空字典
for num in range(200): ##生成200个随机数
ip= '172.25.254.' + str(random.randint(1,200)) ##将int型转换成str型
if ip in d: ##判断ip是否存在
d[ip] += 1 ##若存在,则对应的value值加1
else:
d[ip] = 1 ##若不存在,则赋值1
pprint.pprint(d) ##pprint打印结果
操作结果:
{'172.25.254.1': 1,
'172.25.254.10': 2,
'172.25.254.100': 1,
'172.25.254.102': 1,
'172.25.254.103': 1,
'172.25.254.104': 1,
'172.25.254.105': 1,
'172.25.254.107': 3,
'172.25.254.108': 1,
'172.25.254.109': 2,
...
2.生成1~200的随机数,升序排列并统计次数
import pprint
import random
###与练习1不同的是,需要定义随机数列表并排序
d = {} ##定义数字存储的字典
l = [] ##定义随机数的列表
for num in range(200): ##生成200个随机数字
l.append(random.randint(1,200))
l.sort() ##对数字列表进行升序排列
for N in l:
if N in d:
d[N] += 1
else:
d[N ]= 1
pprint.pprint(d)
操作结果:
{2: 1,
3: 1,
5: 1,
6: 2,
7: 2,
9: 2,
10: 1,
11: 1,
12: 4,
13: 2,
14: 2,
...
3.用户登陆优化
import pprint##优化的目的:管理系统可以新建、登陆、删除、查看用户信息等
userdict = {
'root': 'westos',
'kiosk': 'redhat'
}
menu = """
Users Operation
1).New user
2).User login
3).Delete user
4).View users
5).exit
Please input your choice:"""
while 1: ##采用死循环的格式
choice = input(menu)
if choice == '1':
print('New User'.center(30, '*'))
name = input('please input a username:')
if name in userdict: ##判断用户是否存在
print(name + ' is already exist!')
else: ##用户不存在,则在用户字典中添加用户信息
passwd = input('please set your passwd:')
userdict[name] = passwd
print(name + ' is ok!')
elif choice == '2':
print('User Login'.center(30, '*'))
for i in range(3): ##限制用户3次登陆机会
USER = input("please input username:")
if USER in userdict: ##判断登陆用户是否存在
PASS = input("please input passwd:")
if PASS == userdict[USER]: ##判断用户密码
print("Login successfully")
break
else:
print("Login failly")
else:
print(USER + " is not exist")
continue
else:
print("ERROR:Time is over")
elif choice == '3':
print('Del User'.center(30, '*'))
name = input('please input a username:')
if name in userdict: ##删除前,先判断用户是否存在
del userdict[name] ##此处可增加限制,密码匹配方可删除
print(name + ' is already deleted!')
else:
print(name + ' is not exist!!')
elif choice == '4':
print('View User'.center(30, '*'))
pprint.pprint(userdict) ##pprint打印用户信息
elif choice == '5':
print('Exit'.center(30, '*'))
break
else:
print('ERROR!!!')
函数
一、定义函数
1.函数参数:形参
def test(形参): ##函数名,形参可任意
pass ##函数体
return ##返回值,默认为none
2.有返回值,可选参数:return关键字
def test(*arges): ##可选参数,表示参数个数不限
return sum(arges) ##sum(),求和函数
print(test(1,2)) ##调用函数,不会输出返回值
print(test(1,2,3)) ##只有打印函数执行结果时,会输出返回值
3.没有返回值
def test(*arges):
print(sum(arges)) ##函数体:打印arges的和
test(1,2) ##执行函数就会有结果(跟函数写法有关)
test(1,2,3)
test(1,2,3,4,5)
4.默认参数
def test(num,x=2): ##'=':表示默认参数
print(num**x) ##实现:求平方效果
test(2,4) ##调用函数时有参数,则按参数执行
5.关键字参数
def test(name,age,**kwargs): ##'**kwargs':表示关键字参数
print(name,age,kwargs)
test('lee',20,weight=50,tall=174) ##关键字参数,以字典格式存储
6.参数组合
定义参数的顺序必须是:
必选参数、 默认参数、可选参数和关键字参数
7.return关键字
注意:当函数执行过程遇到return时,后面的代码不再执行
8.全局变量 global
局部变量: 函数中的变量,只在函数中生效
global: 使局部变量变成全局变量
二、练习
1.f(n)为完全平方和公式,给定k,a,b,求a,b之间有多少个n满足k*f(n)=n
a= int(input('a:')) ##输入范围a,b
b = int(input('b:'))
k = int(input('k:')) ##指定k值
count = 0 ##计数
def f(n): ##计算完全平方和
res = 0
for i in str(n): ##强制转换成字符串,遍历
res += int(i) ** 2 ##求完全平方和结果
return res
def isok(num): ##该函数判断是否满足条件
if k * f(num) == num: ##符合题目条件,则返回true,否则False
return True
else:
return False
for num in range(a, b + 1): ##在a、b之间尝试
if isok(num): ##满足条件,计数+1
count += 1
print(count)
2.一个整数,它加上100后是一个完全平方数,再加上168又是一个完全平方数,请问该数是多少?
def main(num): ##定义函数
for x in range(1000): ##遍历1000内的整数
if x ** 2 == num: ##当num是完全平方数时,返回True
return True
for i in range(1000): ##遍历1000内的整数
n1 = i + 100 ##题目要求+100和+168后依然是完全平方数
n2 = i + 168
if main(n1) and main(n2): ##调用函数,当n1和n2均成立,i满足要求
print(i)
3.用户管理系统——终极版
要求:用户新建时,“*“ 提示用户名和密码必须有,年龄和联系方式可不填
import pprint ##导入pprint模块,使输出更美观
userdict = { ##用户信息字典
'root': 'westos',
'kiosk': 'redhat'
}
menu = """
Users Operation
1).New user
2).User login
3).Delete user
4).View users
5).exit
Please input your choice:""" ##输入提示
def log(name, password, **kwargs): ##log()函数,关键字参数
userdict[name] = (password, kwargs)
##在userdict中新增元素key=name,value=(password, kwargs)
while 1: ##死循环
choice = input(menu) ##输入操作选项
if choice == '1':
print('New User'.center(30, '*')) ##新建用户
name = input('please input your *username:')
if name in userdict: ##判断用户是否存在
print(name + ' is already exist!')
else: ##用户需输入密码、年龄(可选)、邮箱(可选)
passwd = input('please set your *passwd:')
age = input('please input your age:')
mail = input('please input your mail:')
log(name, passwd, Age=age, Mial=mail) ##调用函数,添加新用户信息
print(name + ' is ok!') ##返回用户添加成功
elif choice == '2':
print('User Login'.center(30, '*')) ##登陆界面
for i in range(3): ##3次登陆机会
USER = input("please input username:")
if USER in userdict: ##判断用户是否存在
PASS = input("please input passwd:")
if PASS == userdict[USER]: ##判断密码是否存在
print("Login successfully")
break
else:
print("Login failly")
else:
print(USER + " is not exist")
continue ##跳出本次循环,继续执行
else:
print("ERROR:Time is over")
elif choice == '3': ##删除用户
print('Del User'.center(30, '*'))
name = input('please input a username:')
if name in userdict:
del userdict[name] ##根据key值删除userdict中信息
print(name + ' is already deleted!')
else:
print(name + ' is not exist!!')
elif choice == '4': ##查看用户信息
print('View User'.center(30, '*'))
pprint.pprint(userdict) ##可遍历输出
elif choice == '5':
print('Exit'.center(30, '*'))
break
else:
print('ERROR!!!')
4.给定整数,执行函数Collatz,若该整数为偶数,打印并返回num//2,若为奇数,打印并返回3*num+1
def Collatz(num): ##定义函数Collatz()
if num % 2 == 0: ##判断num是否为偶数
print(num // 2) ##取整
return num // 2
else:
print(3 * num + 1) ##为奇数时,重新赋值
return 3 * num + 1
n = int(input('please input an int:')) ##强制转换为int型
while 1:
n = Collatz(n) ##调用函数
if n == 1: ##当n为1时满足要求,退出
break