iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >我的python学习--第四天
  • 347
分享到

我的python学习--第四天

第四天python 2023-01-31 01:01:00 347人浏览 薄情痞子

Python 官方文档:入门教程 => 点击学习

摘要

一、首先是对前三天的学习内容进行复习  1、Python基础的数据结构      数字(int/float,包括整数和浮点数)          布尔(boolean => True/False)      字符串(str,使用''或

一、首先是对前三天的学习内容进行复习

  1、Python基础数据结构

      数字(int/float,包括整数和浮点数)   

      布尔(boolean => True/False)

      字符串(str,使用''或""括起来)


      列表(list)

        列表是使用[]括起来的一组数组,在内存中是连续的,可以对其增删改查

      字典(dict)

       字典是使用{}括起来的k/v键值对,经过哈希计算随机分布在内存中,是无序的,可以对其增删改查

      元组(tuple)

        元组与列表类似,不同之处在于元组的元素不能修改,元组使用小括号()

  2、python的语法

      定义变量 a=1

      if else语句


      if 布尔值:

          True执行这里

      else:

          False执行这里


      for循环

          循环list或者dict


      while循环

          while 布尔值:

              布尔值真,一直执行

      break/continue


      调试方法(print)


      help()函数和dir()函数

       help()函数是查看函数或模块用途的详细说明,而dir()函数是查看函数或模块内的操作方法,输出的是 方法列表。


  3、list和dict的区别

      list有顺序

       查找、追加很快,插入、删除很慢,命中cpu缓存的概率大     

      dict没顺序

        查找、修改、删除都很快


      dict->list : for key,value in dict.items()

      list转成dict : for index,value in enumerate(list)


  4、文件读取

      open:打开文件

     read、readline、readlines:读取文件内容

     write、writelines:文件写入

     close:关闭文件

  

     tell()和seek()

       文件刚打开时,只能在开始的位置,每次read、readline、readlines时都会移动指针到读取数据的地方

     tell():返回文件所在指针的当前位置

    seek(#,whence=0):从文件中移动#个文件指针,正数则往结束方向移动,负数则向开始方向移动,如果设定了whence参数,就以whence设定的起始位置为准,0表示文件开始处、1表示当前位置、2表示文件结尾处



二、对第三天的统计Nginx访问日志,获取访问前十的ip地址,并用html的格式呈现的练习进行优化

#!/usr/bin/Python
#coding:utf-8

res = {}
'''
f = open('access.log')                             # 优化前的文件开启,关闭
...
f.close()
'''
with open('access.log') as f:                      # 优化后的文件开启,关闭
    for line in f:
        tmp = line.split(' ')
        ip,url = tmp[0],tmp[6]
        '''
        if (ip,url) in res:                        # 优化前的数据统计
            res[(ip,url)] += 1
        else:
            res[(ip,url)] = 1
        '''
        res[(ip,url)] = res.get((ip,url),0)+1      # 优化后的数据统计
res_list = res.items()
# print res_list

'''                                                # 优化前,使用冒泡法进行排序
for j in range(11):
    for i in range(len(res_list)-1):
        if res_list[i][1] > res_list[i+1][1]:
            res_list[i],res_list[i+1]=res_list[i+1],res_list[i]
'''

res_list = sorted(res_list,key=lambda x:x[1],reverse=True) # 优化后使用sorted函数排序

i = 0
html_str = '<table border="1px">'
# res_list.reverse()
for r in res_list[:10]:
    i = i+1
# (('218.200.66.204', '/data/uploads/2014/0707/12/small_53ba21ee5cbde.jpg'), 1),
    html_str += '<tr><td>No%s</td> <td>%s</td><td>%s</td><td>%s</td>'%(i,r[0][0],r[0][1],r[1])
html_str+='</table>'

html_f = open('res.html','w')
html_f.write(html_str)
html_f.close()



三、函数(第四天重点)


  函数是组织好的,可重复使用的,用来实现单一,或相关联功能的代码段。

  函数能提高应用的模块性,和代码的重复利用率。Python提供了许多内建函数,比如print()。但你也可以自己创建函数,这被叫做用户自定义函数。


  定义函数的规则:

    函数代码块以 def 关键词开头,后接函数标识符名称和圆括号()。

    任何传入参数和自变量必须放在圆括号中间。圆括号中间可以用于定义默认参数。

    函数的第一行语句可以选择性地使用文档字符串—用于存放函数说明。

    函数内容以冒号起始,并且缩进。

    return [表达式] 结束函数,选择性地返回一个值给调用方。不带表达式的return相当于返回 None。


  语法:

    def func_name(parameters):

      func_suite

      return [expression]

    

  示例:定义一个函数,实现阶乘

def f(num):
    fact = 1
    if num<0:
        return "No negative factorial"
    elif num==0:
        return 1
    for i in range(1,num+1):
        fact *= i
    return fact


  参数:

    调用函数时使用的函数类型:


      必备参数:

        调用函数时,必须以正确的顺序传入,并且传入的参数必须与声明的参数一致

>>> def hello(name):
...     return 'hello '+name
...
>>> hello('world')
'hello world'


     关键字参数:

        关键字参数和函数调用关系紧密,函数调用使用关键字参数来确定传入的参数值。使用关键字参数允许函数调用时参数的顺序与声明时不一致,因为 Python 解释器能够用参数名匹配参数值。

>>> def hello(name,age):
...     return 'hello %s,your age is %s'%(name,age)
...

>>> hello(age=20,name='Alice')
'hello Alice,your age is 20'


     缺省参数:

        调用函数时,缺省参数的值如果没有传入,则使用预先定义的默认值。

>>> def hello(name,age=20):
...     return 'hello %s,your age is %s'%(name,age)
... 
>>> hello('Bob')
'hello Bob,your age is 20'


     不定长参数:

        你可能需要一个函数能处理比当初声明时更多的参数。这些参数叫做不定长参数。

        *开头的参数,收集所有剩下的参数(位置参数),适用于元祖

        **开头的参数,收集所有剩下的参数(关键字参数),适用于字典

>>> def hello(name,*msg):
...     return 'hello %s,your msg is %s'%(name,msg)
... 
>>> hello('Catalina',20,'Female')
"hello Catalina,your msg is (20, 'Female')"


  匿名函数:

    lambda

      语法:lambda [arg1 [,arg2,.....argn]]:expression


      示例:写一个函数,求两个数字之和

>>> sum = lambda x,y:x+y
>>> print sum(10,5)
15


  作用域:

    一个程序的所有的变量并不是在哪个位置都可以访问的。访问权限决定于这个变量是在哪里赋值的。变量的作用域决定了在哪一部分程序你可以访问哪个特定的变量名称。函数内部变量,先在函数内部找,找不到才会去全局找,内部变量想修改为全局变量,只需用global声明一下。多个函数之间尽量避免使用全局变量


    示例:

#!/usr/bin/python
#coding: utf-8

total = 0                                              #这是一个全局变量
def sum(arg1,arg2):
   total = arg1 + arg2                                 # total在这里是局部变量
   print "函数内是局部变量: ",total
   return total


sum(10,20)
print "函数外是全局变量: ",total
[root@test python]# python examp.py
函数内是局部变量:  30
函数外是全局变量:  0


   

  将局部变量变为全局变量:

num = 100                                            # 全局变量
def func():
    global num                                       # 使用global将局部变量定义为全局变量
    num = 200                                        # 局部变量
    print num

func()
print num

 结果:    

[root@test python]# python examp3.py
200
200


四、使用函数对'二'中的练习进行改造

def oper_file(file_name):                            # 定义函数,根据访问数对ip、url排序
    res = {}
    with open(file_name) as f:
        for line in f:
            tmp = line.split(' ')
            ip,url = tmp[0],tmp[6]
            res[(ip,url)] = res.get((ip,url),0)+1
    return sorted(res.items(),key=lambda x:x[1],reverse=True)

def get_html(arr):                                   # 将排序后的数据写成html格式
    tmpl = '<tr><td>No%s</td> <td>%s</td><td>%s</td><td>%s</td></tr>'
    
    html_str = '<h1>IP COUNT TABLE</h1>'
    html_str += '<table border="1px">'
    html_str += tmpl%(' ','IP','URL','COUNT')

    for index,value in enumerate(arr[:10]):
        html_str += tmpl%(index,value[0][0],value[0][1],value[1])
    html_str+='</table>'
    return html_str

def start_operate(file_name):                        # 将html格式的数据写入文件
    res = oper_file(file_name)
    with open('res.html','w') as f:
        f.write(get_html(res))

start_operate('access.log')


  html文件效果图:

wKioL1eVqCviuxVBAAA4C5SLjDM287.png



五、使用函数,对第三天的用户注册,登录功能进行改造

#!/usr/bin/python
#coding:utf-8

service = raw_input('which service you want to choose,reGISter or login: ').strip()

def file():
    name_list = []
    with open('user.txt') as fo:
        for msg in fo:
            msg_name = msg.strip('\n').split(':')[0]
            name_list.append(msg_name)
    return name_list

def test(arr):
    while True:
        name = raw_input('Please Input your name: ').strip()
        passwd = raw_input('Please Input your passWord: ').strip()
        repasswd = raw_input('Please Input your password again: ').strip()

        if not name:
            print 'Name can not be null'
            continue
        elif name in arr:
            print 'User already exist.'
            continue
        elif not passwd or passwd!=repasswd:
            print 'Wrong password'
            continue
        else:
            return name,passwd
            break

def write_in(name,passwd):
    with open('user.txt','a+') as fo:
        fo.write('%s:%s\n'%(name,passwd))
        print 'Registration completed'

def register():
    res = file()
    name,passwd = test(res)
    write_in(name,passwd)

def login():
    with open('user.txt') as fo:
        d = {}
        for user in fo:
            user_name = user.strip('\n').split(':')[0]
            user_passwd = user.strip('\n').split(':')[1]
            d[user_name] = user_passwd 
    return d

def judge(arr):
    while True:
        name = raw_input('Please input your name: ').strip()
        passwd = raw_input('Please input your passwd: ').strip()

        if not name:
            print 'Name can not be null'
            continue
        elif name not in arr:
            print 'No such user'
            continue
        elif not passwd or passwd!=arr[name]:
            print 'Wrong password'
            continue
        else:
            print 'login successfully'
            break

def msg():
    if service=='login':
	    arr = login()
 	    judge(arr)
    elif service=='register':
	    register()
    else:
	    print 'No other choice.'	

msg()


运行结果:

[root@test python]# python homework_04.py 
which service you want to choose,register or login: register
Please Input your name: hello
Please Input your password: 1234
Please Input your password again: 1234
Registration completed
[root@test python]# python homework_04.py 
which service you want to choose,register or login: login
Please input your name: hello
Please input your passwd: 1234
login successfully


--结束END--

本文标题: 我的python学习--第四天

本文链接: https://www.lsjlt.com/news/184757.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • 我的python学习--第四天
    一、首先是对前三天的学习内容进行复习  1、python基础的数据结构      数字(int/float,包括整数和浮点数)          布尔(boolean => True/False)      字符串(str,使用''或...
    99+
    2023-01-31
    第四天 python
  • 我的python学习--第十四天(一)
    一、运维管理系统(基于Flask)回顾1、权限控制  通过session实现权限控制,session是一个全局字典,当用户登录时,可以获取到用户的用户名,通过查找数据库获取用户的权限保存进session中,在每次页面跳转时同过查询sessi...
    99+
    2023-01-31
    第十四天 python
  • python 学习第四天
    目录 基本运算符 算术运算符 比较运算符 赋值运算符 逻辑运算符 身份运算符 pyth...
    99+
    2023-01-31
    第四天 python
  • 我的python学习--第五天
    一、函数的定义:  def 函数名(name,age=20,*params):    函数体    return 返回值  示例:def hello():     print 'hello world'               # pr...
    99+
    2023-01-31
    第五天 python
  • 我的python学习--第三天
    第三天  1:列表及Python基础回顾  2:字典 列表字典生成式及应用场景  3:字符串 字典字符串转换及应用场景  4:文件操作 文件字典转换及应用场景  5:总结基础数据结构的知识脑图 -- 增删查改1、列表的操作:  help(l...
    99+
    2023-01-31
    python
  • 学习python的第四天(python的
    一.Jupyter的安装以及运行 1.Jupyter的安装 运行CMD,在CMD中输入pip3 --default-timeout=100 install -U jupyter 再输入pip3 install jupyter_contr...
    99+
    2023-01-31
    第四天 python
  • 我的python学习--第十三天
    nginx + uwsgi + flask一、安装1、安装uwsgi[root@yaoliang day_13]# wget http://projects.unbit.it/downloads/uwsgi-2.0.4.tar.gz [ro...
    99+
    2023-01-31
    第十三天 python
  • 我的python学习--第七、八天
    Flask的HTTP方法HTTP(与web应用会话的协议)有许多不同的URL方法。默认情况下,路由只回应GET请求,但是通过route()装饰器传递methods参数可以改变这个行为。HTTP方法告知服务器,客户端想对请求的页面 做些什么。...
    99+
    2023-01-31
    python
  • 我的python学习--第十一天
    上午:作业讲解bootstrap-multiselect插件sweetalert插件下午:datatables----表格插件datetimepicker----时间插件Validform----表单验证插件锁定用户禁止登录---...
    99+
    2023-01-31
    第十一天 python
  • 我的python学习--第十二天(二)
    Python异常处理  Python的异常处理能力是很强大的,可向用户准确反馈出错信息。在Python中,异常也是对象,可对它进行操作。所有异常都是基类Exception的成员,所有异常都从基类Exception继承,而且都在excepti...
    99+
    2023-01-31
    二天 python
  • 学习python的第十四天(可变长参数,
    一.可变长参数 1.可变长形参之(*) 形参中的会将溢出的位置实参全部接收,然后存储元组的形式,然后把元组赋值给后的参数。需要注意的是:*后的参数名约定俗成为args。 def sum_self(*args): res = 0 ...
    99+
    2023-01-31
    变长 参数 第十四天
  • 学习python第二天
    一、python的版本选择与安装后的操作 python 2 vs 3 1。 默认支持中文 2. 不兼容2.x 3. 核心语法调整,更易学 4. 新特性默认只在3.x上有 系统位数 32bit =内存的最大寻址空间是2**32, ...
    99+
    2023-01-31
    第二天 python
  • python学习第二天
    目录 操作系统 操作系统干了什么 为什么要有操作系统 操作系统有什么用 应用程序的启动和操作系统的启动 ...
    99+
    2023-01-31
    第二天 python
  • python学习第二天 -----201
    第二周-第02章节-Python3.5-模块初识 #!/usr/bin/env python #-*- coding:utf-8 _*- """ @author:chenjisong @file: sys.py @time: 2019/...
    99+
    2023-01-31
    第二天 python
  • 学习python的第三天(变量)
    一.关于python 1.交互式 说一句解释一句 2.命令行式 1.编写文件并且保存 2.打开python解释器,在pyrhon中打开文本,读入内存(python打开的时候,翻译不是瞬间) 3.python解释文本 注意:第二阶段相当于...
    99+
    2023-01-31
    变量 python
  • 学习python的第二十天(dateti
    1.datetime模块(用于修改日期) import datetime print(datetime.datetime.now(),type(datetime.datetime.now())) 2019-06-10 19:37:55....
    99+
    2023-01-31
    十天 python dateti
  • 第四天-代码练习
      1.用户输入账号密码验证码,登录验证。 1 # 登录验证 2 from random import randint 3 num = 0 4 verify_code = "" 5 while num < 4: 6 ...
    99+
    2023-01-30
    第四天 代码
  • Python学习笔记:第一天python
    目录 1. python简介 2. python的安装 3. 编写第一个helloword 4. 变量和常量 5. 数据...
    99+
    2023-01-30
    学习笔记 Python python
  • 学习python的第二十一天(loggi
    1.logging模块 用于程序的运行日志 1.初级 #首先程序运行分会出现5中情况 1.logging.info('info') #程序正常运行级别为10 2.logging.debug('debug') #程序调试...
    99+
    2023-01-31
    python loggi
  • 学习python的第二十一天(hashl
    1.hashlib模块(文件传输中将传输内容用指定算法进行处理) hash是一种算法(Python3.版本里使用hashlib模块代替了md5模块和sha模块,主要提供 SHA1、SHA224、SHA256、SHA384、SHA512、...
    99+
    2023-01-31
    python hashl
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作