登录  /  注册

Python的一些小练习

PHP中文网
发布: 2017-06-21 15:22:32
原创
1092人浏览过

作业一:                                                                                                                        

利用*字典*输出目录,可以选择目录进入,可以回退、退出!

<span style="color: #808080; font-style: italic">#conding:utf8<span style="color: #000080; font-weight: bold"><br><br><br>menu = {<span style="color: #008080; font-weight: bold">'北京':{<span style="color: #008080; font-weight: bold">'昌平':{<span style="color: #008080; font-weight: bold">'沙河':{<span style="color: #008080; font-weight: bold">'昌平妇幼',}},<span style="color: #008080; font-weight: bold">'海淀':{<span style="color: #008080; font-weight: bold">'海淀一区':{<span style="color: #008080; font-weight: bold">'海淀二区'},}},}  <span style="color: #808080; font-style: italic">#字典嵌套<br><span style="color: #808080; font-style: italic"><br>current_layer = menu                              <span style="color: #808080; font-style: italic">#利用此变量来记录当前的层的位置<br>pre_menu = []                                     <span style="color: #808080; font-style: italic">#用【】来记录每一层<br><span style="color: #808080; font-style: italic"><br><span style="color: #000080; font-weight: bold">while True:<br><span style="color: #000080; font-weight: bold">for k <span style="color: #000080; font-weight: bold">in current_layer:<br><span style="color: #000080">print (k)<br>    choice = <span style="color: #000080">input(<span style="color: #008080; font-weight: bold">'&gt;&gt;&gt;&gt;&gt;&gt;&gt;:').strip()            <span style="color: #808080; font-style: italic">#去除输入选项连边的空格<br><span style="color: #808080; font-style: italic">    <span style="color: #000080; font-weight: bold">if <span style="color: #000080">len(choice) == <span style="color: #0000ff">0:                          <span style="color: #808080; font-style: italic">#通过len的长度来判断用户是否输入了<br><span style="color: #808080; font-style: italic">        <span style="color: #000080; font-weight: bold">continue<br><span style="color: #000080; font-weight: bold"><br><span style="color: #000080; font-weight: bold">    if choice <span style="color: #000080; font-weight: bold">in current_layer:<br>        pre_menu.append(current_layer)<br>        current_layer = current_layer[choice]<br><span style="color: #000080; font-weight: bold">elif choice == <span style="color: #008080; font-weight: bold">'b':<br><span style="color: #000080; font-weight: bold">if <span style="color: #000080">len(pre_menu) &gt; <span style="color: #0000ff">0:                    <span style="color: #808080; font-style: italic">#通过大于0 来判断,还有目录可退<br><span style="color: #808080; font-style: italic">            current_layer = pre_menu.pop()       <span style="color: #808080; font-style: italic">#利用pop来弹出上面的一层。<br><span style="color: #808080; font-style: italic">    <span style="color: #000080; font-weight: bold">elif choice == <span style="color: #008080; font-weight: bold">'q':<br><span style="color: #000080">exit()</span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span>
登录后复制

作业二                                                                                                              

list的小练习:实现购物车功能

product_list = [[
登录后复制

作业三                                                                                                        

冒泡算法小练习

a_list = [
登录后复制
登录后复制

作业四                                                                                                    

插入算法小练习

实现方法一

a_list = [
登录后复制
登录后复制

实现方法二

arr1 = [
登录后复制

做业五                                                                                                          

打印99乘法表

#! /usr/bin/python
# Filename : table_9x9.py
 
print '\n9x9 Table\n'
 
for i in range(1, 10) :
    for j in range(1, i+1) :
        print j, 'x', i, '=', j*i, '\t',
        # print '%d x %d = %d\t' %(j, i, j*i),
    print '\n'
print '\nDone!'
 
 
关于该程序的说明:
1. 第一行是特殊注释行,称为组织行,用来告诉GNU/Linux系统应该使用哪个解释器来执行该程序。
2. 第二行至第四行都是一般的注释行,用来说明一些信息的(如文件名,作者,时间等)。
3. 第六行打印一个字符串。
4. 第八行i取值范围为1, 2, 3, 4, 5, 6, 7, 8, 9
5. 第九行j取值范围为1, 2, ..., i
6. 第十行和第十一行效果一样,最后的逗号都是用来取消自动换行的。
7. 第十二行作用是在每个内层for循环结束后换行,即在输出完九九乘法表一行后换行。
8. 第十四行打印一个字符串。
 
 
小结:通过这个程序熟悉print的用法,for循环的用法,以及range函数的特点。

课堂中提到的方法:

for i in range(1,10):<br>    output = ''<br>    for j in range(1,i+1):<br>        output+= "%s*%s=%2s "%(i,j,i*j)<br>    print output

 

---------------------------------------------------

作业六:                                                                                                       

取一个列表中前两位大的数字

<br>
登录后复制
#!/usr/bin/python<br><br>NumList = [1,2,3,2,12,3,1,3,21,2,2,3,4111,22,3333,444,111,4,5,777,4222,46,33,45,65555]<br><br>max_num = 0<br>sec_num = 0<br><br>for n in NumList:<br>if max_num         sec_num=max_num      <br>#获取最大数之前的比较的哪个数肯定是在这之前第二大的<br>        max_num = n<br>#但是后面如果再出现比最大的大,比之前比较出料的第二大<br>        #小的数时需要再比较下。<br>    if n and n > sec_num:<br>            sec_num = n<br><br><br>print ('The bigest NUM is : %s' %(max_num))<br>print ('The second one is : %s' %(sec_num))
登录后复制
 <br>
登录后复制

利用单循环来同事去除两个两个数。

作业七                                                                                                      

二分查找法(利用递归函数)

num_list = [
登录后复制

作业八                                                                                                                

利用函数完成用户的注册登录功能

 

#!/usr/bin/python<br>#encoding: utf-8

import getpass

user_list = {}

def new_user():<br>    username = raw_input('please input your new name:')<br>    if username in user_list:<br>        print '%s is already exits!!' %username<br>    else:<br>        passwd = getpass.getpass()               #已密码不显示的方式输入。<br>        user_list[username] = passwd

def old_user():<br>    username = raw_input('please input your name:')<br>    passwd = raw_input('please input your passwd:')<br>    if username in user_list:<br>        if user_list[username] == passwd:<br>            print 'login successfull!!'<br>        else:<br>            print 'login fail!!'<br>    else:<br>        print 'login fail!!!'

CMD = {'n' : new_user , 'o' : old_user}

def main_menu():<br>    ppp = '''<br>        新用户注册:n<br>        老用户登录:o<br>        推出:q

'''<br>    while True:<br>        try:<br>            choice = raw_input(ppp)<br>        except (KeyboardInterrupt, EOFError):       #捕捉ctrl+ D 的错误输出。<br>            choice = 'q'

if choice not in 'noq':<br>            print 'please input again'<br>            continue<br>        if choice == 'q':<br>            break<br>        CMD[choice]()          #通过取字典的key,选择来执行函数

 

if __name__ == '__main__':<br>    main_menu()

作业九

log日志前十排序,其中包括重复的。利用函数简单的html输出

#!/usr/bin/python
#coding:utf8

def openFile(log):
    with open(log) as f:
        content = f.readlines()
    return content

def countLine(fn):
    content = fn
    count_dict = {}
    for line in content:
        line = line.split(' ')  # string 通过split 转换为list
        local_ip,uri,code = line[0],line[6],line[8]
登录后复制
        #利用元组来作为key,然后统计数量
登录后复制
        count_dict[(local_ip,uri,code)] = count_dict.get((local_ip,uri,code),0) + 1
登录后复制
    #这个排序的功能网上copy的,不了解原理
登录后复制
    count_dict = sorted(count_dict.items() ,key=lambda item:item[1],reverse=True)        
    return count_dict

def detailLine(fn):
    count_dict = fn
    #下面进行重复行计数为一行。
    n = 1                              #取行计数
    num = 0                            #用于判断'统计数量'是否出现一样的
    # print ('-----IP------------------URI----------CODE---count---')
    # for i in count_dict:
    #     if n no%s' % (i[0][0], i[0][1], i[0][2], i[1], n))
    #             num = i[1]
    #             n += 1
    #         elif i[1] == num:
    #             print('%-10s%20s%5s%10s' % (i[0][0], i[0][1], i[0][2], i[1]))

    with open('count.html','w') as f:
        res = "
登录后复制
"         res += ''         for i in count_dict:             if n '% (i[0][0],                      i[0][1], i[0][2], i[1])                     num = i[1]                     n += 1                 elif i[1] == num:                     res += '' % (i[0][0],                      i[0][1], i[0][2], i[1])         res +='
IP URI CODE COUNT
%s %s %s %s
%s %s %s %s
'         f.write(res) def main():     first = openFile('access.log')     second = countLine(first)     detailLine(second) if __name__ == '__main__':     main()
作业十,

 生成随机验证码:

方法一:
import string,random

source = string.digits + string.ascio_lowercase
print ("".join(random.sample(source,6)))

方法二:
checkcode = ''
for i in range(6):
    current = random.randrange(0,6)
    if current != i:
        temp = chr(random.randint(65,90))
    else:
        temp = random.randint(0-9)
    checkcode += str(temp)
print(checkcode)
登录后复制

 

 
 

 

以上就是Python的一些小练习的详细内容,更多请关注php中文网其它相关文章!

智能AI问答
PHP中文网智能助手能迅速回答你的编程问题,提供实时的代码和解决方案,帮助你解决各种难题。不仅如此,它还能提供编程资源和学习指导,帮助你快速提升编程技能。无论你是初学者还是专业人士,AI智能助手都能成为你的可靠助手,助力你在编程领域取得更大的成就。
相关标签:
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
最新问题
关于CSS思维导图的课件在哪? 课件
凡人来自于2024-04-16 10:10:18
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2024 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号