python字典与函数

字典

一、定义

d = dict(a=2,b='westos')            ##直接定义赋值
d ={}.fromkeys()                    ##采用fromkeys函数定义
User = []
for i in range(10):
    User.append('User%d' %(i+1))
d ={}.fromkeys(User,'0000')
pprint.pprint(d)

#运行结果:
/usr/local/python3/bin/python3.6 "/home/kiosk/PycharmProjects/10day 博客练习.py"
{'User1': '0000',
 'User10': '0000',
 'User2': '0000',
 'User3': '0000',
 'User4': '0000',
 'User5': '0000',
 'User6': '0000',

打印模块pprint,使输出更美观

import  pprint  ##导入pprint模块
user =[]
for i in range(10):
    user.append('User%d' %(i+1))  ##生成user列表user1-user10用户
pprint.pprint({}.fromkeys(user,'1234'))   ##赋值所有key:1234

二、字典的操作

1.查看key值对应的value值

d = dict(a=2,b='westos')
print(d['b'])    ##value值存在时,输出;不存在时,报错
print(d['c'])    ##报错!!注释后可运行
print(d.get('a'))    ##value值存在时,输出;不存在时,输出None
print(d.get('hello'))   ##输出none

2.指定输出字典的key、value、key-value

d = dict(a='hello',b='westos',c='python')
print(d.keys())    ##打印字典中所有的key值
print(d.values())  ##打印字典中所有的value值
print(d.items())   ##打印字典中所有的key-value值对

输出结果:
dict_keys(['a', 'b', 'c'])
dict_values(['hello', 'westos', 'python'])
dict_items([('a', 'hello'), ('b', 'westos'), ('c', 'python')])

3.修改字典元素

d = dict(a='hello',b='westos',c='python')
d ['a'] = 100   ##key存在时,修改对应的value值
d ['f'] =11     # 不存在时,新增
print(d)
d2=dict(a=110,b=0) ##key存在时,覆盖原value值;不存在时,新增
print(d.update(d2))
print(d)
d.setdefault('a',100)   ##key存在时,不做操作;不存在时,新增
d.setdefault('e',100)
print(d)
结果如下:
{'a': 100, 'b': 'westos', 'c': 'python', 'f': 11}
None
{'a': 110, 'b': 0, 'c': 'python', 'f': 11}
{'a': 110, 'b': 0, 'c': 'python', 'f': 11, 'e': 100}

4.遍历字典

d = dict(a='hello',b='westos',c='python')
for key,value in d.items():
    print(key,value)
结果如下:
a hello
b westos
c python

5.删除字典元素

d = dict(a='hello',b='westos',c='python')
del d['a']    ##key值存在则删除
del d['f']   ##不存在则报错

value=d.pop('a')  ##key值存在则删除,返回对应的value值
value=d.pop('f')  ##不存在则报错
print(value)
效果如下:
hello
pair=d.popitem()  ##随机删除,一般是最后一个,返回值为key-value值对
print(d,pair)
效果如下:
{'a': 'hello', 'b': 'westos'} ('c', 'python')

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
效果如下:
please input a num:23
please make your choice:+
please input a num:45
68

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))  ##随机取出200个数并将int型转换成str型
    if ip in d:   ##判断ip是否存在
        d[ip] += 1  ##若存在,则对应的value值加1
    else:
        d[ip] = 1   ##若不存在,则赋值1
pprint.pprint(d)  ##pprint打印结果

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)

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(),求和函数

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)  ##调用函数时有参数,则按参数执行
test(3)    ##调用函数只有一个参数,则按默认参数执行
5.关键字参数
def test(name,age,**kwargs):   ##'**kwargs':表示关键字参数
    print(name,age,kwargs)

test('lee',20,weight=50,tall=174)  ##关键字参数,以字典格式存储
效果如下:
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
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值