python-4

import random        引用模块

l=random.randint(1,1000)   随机在1-1000  里面生成一个数
print(l)
li=[1,2,34,5,5,6]
li.sort()       排序
print(li)
l2=sorted([1,3,4,5,8,4])     排序
print(l2)
l=set()   定义一个空的集和
print(type(l))
s1={}     定义一个空   字典
print(type(s1))



/usr/local/python3/bin/python3.6 /root/PycharmProjects/untitled/day0/05_zuoye.py
<class 'set'>
<class 'dict'>

Process finished with exit code 0

1-1000里面选10个数   排序  去重
import random   引用无序模块
s=set()
n=int(input('num:'))
for i in range(n):
    item=random.randint(1,1000)   无序输出
    s.add(item)  添加到集和里面
print(sorted(s))
d={                           创建字典
    'root':[1,2,3,4,],
    'westos':[23,56,45]
}
print(d,type(d))
d1=dict(root='westos',kiosk='redhat')   创建字典
print(d1,type(d1))
user=[]
for i in range(10):
    user.append('user%s' %(i+1))
print(user)



/usr/local/python3/bin/python3.6 /root/PycharmProjects/untitled/day0/05_zuoye.py
['user1', 'user2', 'user3', 'user4', 'user5', 'user6', 'user7', 'user8', 'user9', 'user10']

Process finished with exit code 0
import pprint   引用模块 让格式变好看

user=[]
for i in range(10):
    user.append('user%s' %(i+1))
pprint.pprint({}.fromkeys(user,'000000'))

user里面的每个元素作为KEY值,所有的value值都为'000000'


/usr/local/python3/bin/python3.6 /root/PycharmProjects/untitled/day0/05_zuoye.py
{'user1': '000000',
 'user10': '000000',
 'user2': '000000',
 'user3': '000000',
 'user4': '000000',
 'user5': '000000',
 'user6': '000000',
 'user7': '000000',
 'user8': '000000',
 'user9': '000000'}

Process finished with exit code 0
d=dict(a=1,b=2)
print(d['a'])
在 字典里面不支持索引,切片,连接,重复
d=dict(a=1,b=2)
for i in d:           遍历key值
    print(i)
d=dict(a=1,b=2)   便利 key对应的  valuefor key in d:
    print('%s -> %s' %(key,d[key]))

d=dict(a=1,b=2)
print('a' in d)    成员操作符,只针对key值
print(1 in d)


/usr/local/python3/bin/python3.6 /root/PycharmProjects/untitled/day0/05_zuoye.py
True
False

Process finished with exit code 0
d=dict(a=1,b=2)
d['a']=10     添加字典    如果key存在  就覆盖
d['c']=12                  如果key不存在  就增加
print(d)
d=dict(a=1,b=2)
d2={'c':10,'a':200}
d.update(d2)       添加字典,如果key存在,就覆盖
print(d)            不存在就添加




/usr/local/python3/bin/python3.6 /root/PycharmProjects/untitled/day0/05_zuoye.py
{'a': 200, 'b': 2, 'c': 10}

Process finished with exit code 0
d=dict(a=1,b=2)
d.setdefault('f',100)   添加字典
print(d)



/usr/local/python3/bin/python3.6 /root/PycharmProjects/untitled/day0/05_zuoye.py
{'a': 1, 'b': 2, 'f': 100}

Process finished with exit code 0
d=dict(a=1,b=2)
d.setdefault('a',100)  如果一样   就不变
print(d)


/usr/local/python3/bin/python3.6 /root/PycharmProjects/untitled/day0/05_zuoye.py
{'a': 1, 'b': 2}

Process finished with exit code 0
d=dict(a=1,b=2)
print(d['f'])   当 key值不存在   会报错



/usr/local/python3/bin/python3.6 /root/PycharmProjects/untitled/day0/05_zuoye.py
Traceback (most recent call last):
  File "/root/PycharmProjects/untitled/day0/05_zuoye.py", line 45, in <module>
    print(d['f'])
KeyError: 'f'
1

Process finished with exit code 1
d=dict(a=1,b=2)
print(d.get('a'))   查看 value
print(d.get('f'))     不存在  默认 报 none
print(d.get('f',1))     不存在   报 1 




/usr/local/python3/bin/python3.6 /root/PycharmProjects/untitled/day0/05_zuoye.py
1
None
1

Process finished with exit code 0
d=dict(a=1,b=2)
print(d.values())   查看所有value值
print(d.keys())     查看所有 key值
print(d.items())      查看整个字典





/usr/local/python3/bin/python3.6 /root/PycharmProjects/untitled/day0/05_zuoye.py
dict_values([1, 2])
dict_keys(['a', 'b'])
dict_items([('a', 1), ('b', 2)])

Process finished with exit code 0
d=dict(a=1,b=2)
for key,value in d.items():
    print(key,'->',value)

遍历 key->value值的方式


/usr/local/python3/bin/python3.6 /root/PycharmProjects/untitled/day0/05_zuoye.py
a -> 1
b -> 2

Process finished with exit code 0
d=dict(a=1,b=2)

del d['a']   通过key值删除
print(d)



/usr/local/python3/bin/python3.6 /root/PycharmProjects/untitled/day0/05_zuoye.py
{'b': 2}

Process finished with exit code 0
d=dict(a=1,b=2)

item=d.pop('a')   删除对应的key值
print(item)
print(d)



/usr/local/python3/bin/python3.6 /root/PycharmProjects/untitled/day0/05_zuoye.py
1
{'b': 2}

Process finished with exit code 0
d=dict(a=1,b=2)
d.popitem()    默认删除最后一个
print(d)


/usr/local/python3/bin/python3.6 /root/PycharmProjects/untitled/day0/05_zuoye.py
{'a': 1}

Process finished with exit code 0
d=dict(a=1,b=2)
d.clear()      清空字典
print(d)


/usr/local/python3/bin/python3.6 /root/PycharmProjects/untitled/day0/05_zuoye.py
{}

Process finished with exit code 0
import pprint

s=input('juzi:')
word_list=s.split()
words_count_dirt={}
for word in word_list:
    if word in words_count_dirt:
        words_count_dirt[word] +=1
    else:
        words_count_dirt[word] =1
pprint.pprint(words_count_dirt)

统计句子中每个单词出现的次数

/usr/local/python3/bin/python3.6 /root/PycharmProjects/untitled/day0/05_zuoye.py
juzi:hello word hello python
{'hello': 2, 'python': 1, 'word': 1}

Process finished with exit code 0
import random
import pprint

all_nums=[]
for item in range(1080):
    all_nums.append(random.randint(20,100))
sorted_rums=sorted(all_nums)
num_dict={}
for num in sorted_rums:
    if num in num_dict:
        num_dict[num] +=1
    else:
        num_dict[num]=1
pprint.pprint (num_dict)

随机生成1080个整数,数字范围(20100)  升序输出所有不同的数字及重复个数


/usr/local/python3/bin/python3.6 /root/PycharmProjects/untitled/day0/05_zuoye.py
{20: 16,
 21: 18,
 22: 11,
 23: 19,
 24: 13,
 25: 21,
 26: 11,
 27: 13,
 28: 18,
 29: 15,
 30: 10,
 31: 9,
 32: 19,
 33: 12,
 34: 6,
 35: 11,
 36: 21,
 37: 12,
 38: 10,
 39: 12,
 40: 11,
 41: 9,
 42: 10,
 43: 11,
 44: 16,
 45: 17,
 46: 14,
 47: 14,
 48: 12,
 49: 16,
 50: 17,
 51: 11,
 52: 11,
 53: 10,
 54: 16,
 55: 15,
 56: 6,
 57: 11,
 58: 17,
 59: 12,
 60: 11,
 61: 14,
 62: 8,
 63: 18,
 64: 15,
 65: 12,
 66: 13,
 67: 16,
 68: 14,
 69: 15,
 70: 11,
 71: 16,
 72: 14,
 73: 14,
 74: 16,
 75: 13,
 76: 22,
 77: 12,
 78: 7,
 79: 9,
 80: 10,
 81: 13,
 82: 13,
 83: 9,
 84: 12,
 85: 11,
 86: 20,
 87: 19,
 88: 14,
 89: 15,
 90: 13,
 91: 3,
 92: 15,
 93: 14,
 94: 16,
 95: 14,
 96: 10,
 97: 22,
 98: 13,
 99: 10,
 100: 11}

Process finished with exit code 0
import random
import pprint

n=200
ip_list=[]    定义空列表
ip_count_dict={}    定义空字典
for num in range(n):    循环次数
    ip='172.25.254.'+str(random.randint(1,200))   全部转换成字符串
    ip_list.append(ip)      添加到 字典
for ip in ip_list:    
    if ip in ip_count_dict:      统计重复次数
        ip_count_dict[ip] += 1     
    else:
        ip_count_dict[ip]=1
pprint.pprint(ip_count_dict)

python 不支持 switch case

num1=int(input('num1:'))    简单计算器
choice=input('yunsua:')
num2=int(input('num2:'))
if choice=='+':
    print(num1+num2)
elif choice=='-':
    print(num1-num2)
elif choice=='*':
    print(num1*num2)
elif choice=='/':
    print(num1/num2)
else:
    print('error!')
num1=int(input('num1:'))   运用字典的简单计算器
choice=input('yunsua:')
num2=int(input('num2:'))
d={
    '+':num1+num2,
    '-':num1-num2,
    '*':num1*num2,
    '/':num1/num2,
}
if choice not in d:
    print('error:')
else:
    print(d[choice])
l=['a','b','a']

print({}.fromkeys(l,'000000'))  给value  赋值


print(list(set(l)))  去重    先变成集合   再变成列表
userinfo ={
    'root':'root',
    'kiosk':'kiosk'
}
while True:
    info="""
            用户管理系统
        1).注册新用户
        2).用户登陆
        3).注销用户
        4).显示用户信息
        5).退出系统
        请输入你的选择:"""
    choice=input(info)
    if choice=='1':
        print('注册新用户'.center(50,'*'))
        name=input('注册的用户名:')
        if name in userinfo:
            print('%s用户已经注册过了!' %(name))
        else:
            paswd=input('密码:')
            userinfo[name]=paswd
            print('%s用户注册成功!' %(name))
    elif choice=='2':
        print('用户登陆'.center(50,'*'))
        for trycount in range(3):
            name=input('用户名:')
            passwd=input('密码:')
            if name in userinfo:
                if userinfo[name]==passwd:
                    print('登陆成功!')
                    break
                else:
                    print('密码错误!')
            else:
                print('用户不存在')
    elif choice=='3':
        print('注销用户'.center(50,'*'))
        name=input('用户名:')
        passwd=input('密码:')
        if name not in userinfo:
            print('用户不存在!')
        else:
            if userinfo[name]!=paswd:
                print('密码错误!')
            else:
                pop_name=userinfo.pop(name)
                print('注销用户%s成功' %(pop_name))
    elif choice=='4':
        print('显示用户信息'.center(50,'*'))
        for key,value in userinfo.items():    很关键
            print(key,':',value)
    elif choice=='5':
        print('退出系统'.center(50,'*'))
        break
def 函数名():
    函数体
def hello():       简单的函数
    print('hello word')   

hello()         调用函数
def hello(username):
    print('hello %s' %(username))
hello('lol')      ''  对lol进行定义  确定类型




/usr/local/python3/bin/python3.6 /home/kiosk/PycharmProjects/untitled/day04/02_python_def.py
hello lol

Process finished with exit code 0
def hello(username):      定义函数    ()里面为形参,可以修改
    print('hello %s' %(username))      函数返回值
for user in ['hary','jerry','tom']:     选值
    hello(user)              调用函数  ()里面为实参,必须存在
def hello():
    return 'world'   返回值


print(hello())    必须通过打印   表示出来
def hello():
    return
print(hello())    无返回值时     打印none    


/usr/local/python3/bin/python3.6 /home/kiosk/PycharmProjects/untitled/day04/02_python_def.py
None

Process finished with exit code 0

def 函数名(行参)
函数体
return 返回值

函数名(实参)
print(函数名(实参))

def mypow(a,b):
    return a ** b   定义函数
print(mypow(2,5))
def mypow(a,b):
    print( a **  b)     定义函数

mypow(2,5)
def mypow(a,b=2):   
    print( a **  b)

mypow(2)      默认b为2
def mysum(*args):      把很多数变成元组,然后求和
    return sum(args)

print(mysum(1,2,3,4))
def hello():
    return 'ok'       函数遇到return   后面的代码不再执行
    print('hello')


print(hello())




/usr/local/python3/bin/python3.6 /home/kiosk/PycharmProjects/untitled/day04/02_python_def.py
ok

Process finished with exit code 0
def get_info(name,passwd,**kwargs):   后面的可填   可不填
    print(name,passwd,end=' ')
    print(kwargs,type(kwargs))

get_info('fentiao','redhat')
get_info('fendai','123',city="xi'an",age='10',weight=10)




/usr/local/python3/bin/python3.6 /home/kiosk/PycharmProjects/untitled/day04/02_python_def.py
fentiao redhat {} <class 'dict'>
fendai 123 {'city': "xi'an", 'age': '10', 'weight': 10} <class 'dict'>
 接收的变量为字典数据类型
Process finished with exit code 0
count=10
print('全局变量:',id(count))


def hello():
    count=20
    print('局部变量:',id(count))


hello()
print(count)



函数里面的变量只在函数内部生效 即   局部变量


/usr/local/python3/bin/python3.6 /home/kiosk/PycharmProjects/untitled/day04/02_python_def.py
全局变量: 9322752
局部变量: 9323072
10

Process finished with exit code 0
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值