2020-09-08python十二

#!/usr/bin/python3
print('Python十二')

#121、全局变量和局部变量
# 定义在函数内部的变量拥有一个局部作用域,定义在函数外的拥有全局作用域。
# 局部变量只能在其被声明的函数内部访问,而全局变量可以在整个程序范围内访问。调用函数时,所有在函数内声明的变量名称都将被加入到作用域中。
total = 0 # 这是一个全局变量
# 可写函数说明
def sum( arg1, arg2 ):
    #返回2个参数的和."
    total = arg1 + arg2 # total在这里是局部变量.
    print ("函数内是局部变量 : ", total)
    return total

#调用sum函数
sum( 10, 20 )
print ("函数外是全局变量 : ", total)

#122、global 和 nonlocal关键字
# 当内部作用域想要修改外部作用域的变量时,就要用到global和nonlocal关键字。
#修改全局变量num
num = 1
def fun1():
    global num  # 需要使用 global 关键字声明
    print(num) 
    num = 123
    print(num)
fun1()
print(num)

#123、如果要修改嵌套作用域(enclosing 作用域,外层非全局作用域)中的变量则需要 nonlocal 关键字了。
def outer():
    num = 10
    def inner():
        nonlocal num   # nonlocal关键字声明
        num = 100
        print(num)
    inner()
    print(num)
outer()
#修改 a 为全局变量,通过函数参数传递,可以正常执行输出结果为:
a = 10
def test(a):
    a = a + 1
    print(a)
test(a)

#124、Python3标准库概览
import os
print(os.getcwd())#返回当前工作目录
print(os.chdir('/Users/q'))#修改当前的工作目录
print(os.system('mkdir testfile'))#执行系统命令 mkdir
# 在使用 os 这样的大型模块时内置的 dir() 和 help() 函数非常有用
# dir(os)
# help(os)
'''
针对日常的文件和目录管理任务,:mod:shutil 模块提供了一个易于使用的高级接口:
>>> import shutil
>>> shutil.copyfile('data.db', 'archive.db')
>>> shutil.move('/build/executables', 'installdir')

文件通配符
glob模块提供了一个函数用于从目录通配符搜索中生成文件列表:
>>> import glob
>>> glob.glob('*.py')
['primes.py', 'random.py', 'quote.py']

错误输出重定向和程序终止
sys 还有 stdin,stdout 和 stderr 属性,即使在 stdout 被重定向时,后者也可以用于显示警告和错误信息。
>>> import sys
>>> sys.stderr.write('Warning, log file not found starting a new one\n')
Warning, log file not found starting a new one
大多脚本的定向终止都使用 "sys.exit()"。

数学
math模块为浮点运算提供了对底层C函数库的访问:
>>> import math
>>> math.cos(math.pi / 4)
0.70710678118654757
>>> math.log(1024, 2)
10.0

random提供了生成随机数的工具。
>>> import random
>>> random.choice(['apple', 'pear', 'banana'])
'apple'
>>> random.sample(range(100), 10)   # sampling without replacement
[30, 83, 16, 4, 8, 81, 41, 50, 18, 33]
>>> random.random()    # random float
0.17970987693706186
>>> random.randrange(6)    # random integer chosen from range(6)
4
'''

#125、访问互联网
# 有几个模块用于访问互联网以及处理网络通信协议。
# 最简单的两个是用于处理从 urls 接收的数据的 urllib.request 以及用于发送电子邮件的 smtplib:
from urllib.request import urlopen
for line in urlopen('https://www.baidu.com'):
    line = line.decode('utf-8')  # Decoding the binary data to text.
    if 'EST' in line or 'EDT' in line:  # look for Eastern Time
        print(line)
'''
需要本地有一个在运行的邮件服务器
>>> import smtplib
>>> server = smtplib.SMTP('localhost')
>>> server.sendmail('soothsayer@example.org', 'jcaesar@example.org',
... """To: jcaesar@example.org
... From: soothsayer@example.org
...
... Beware the Ides of March.
... """)
>>> server.quit()
'''

#126、日期和时间
# datetime模块为日期和时间处理同时提供了简单和复杂的方法。
# 支持日期和时间算法的同时,实现的重点放在更有效的处理和格式化输出。该模块还支持时区处理:
from datetime import date
now=date.today()
print(now)#默认输出格式2020-09-08
print(now.strftime('%C'))
#通过datetime函数获取时间数据
import datetime
#取当前时间
print(datetime.datetime.now())
#取年
print(datetime.datetime.now().year)
#取月
print(datetime.datetime.now().month)
#取日
print(datetime.datetime.now().day)
#取时
print(datetime.datetime.now().hour)
#取分
print(datetime.datetime.now().minute)
#取秒
print(datetime.datetime.now().second)

# 127、数据压缩
# 以下模块直接支持通用的数据打包和压缩格式:zlib,gzip,bz2,zipfile,以及 tarfile。
import zlib
s=b'this is test'
print('s len:',len(s))
t=zlib.compress(s)
print('t len:',(len(t)))
print(zlib.decompress(t))
print(zlib.crc32(s))

# 128、性能度量
# Python 提供了一个度量工具,为这些问题提供了直接答案。
# 例如,使用元组封装和拆封来交换元素看起来要比使用传统的方法要诱人的多,timeit 证明了现代的方法更快一些。
# 相对于 timeit 的细粒度,profile 和 pstats 模块提供了针对更大代码块的时间度量工具。
from timeit import Timer
print(Timer('t=a; a=b; b=t', 'a=1; b=2').timeit())
print(Timer('a,b = b,a', 'a=1; b=2').timeit())

#129、字符串正则匹配
# re模块为高级字符串处理提供了正则表达式工具。对于复杂的匹配和处理,正则表达式提供了简洁、优化的解决方案:
import re
print(re.findall(r'\bf[a-z]*', 'which foot or hand fell fastest'))
print(re.sub(r'(\b[a-z]+) \1', r'\1', 'cat in the the hat'))
# 如果只需要简单的功能,应该首先考虑字符串方法,因为它们非常简单,易于阅读和调试:
print('tea for too'.replace('too', 'two'))

#130、命令行参数
# 通用工具脚本经常调用命令行参数。这些命令行参数以链表形式存储于 sys 模块的 argv 变量。
# 例如在命令行中执行 "python demo.py one two three" 后可以得到以下输出结果:
import sys
print('test:',sys.argv)
['demo.py', 'one', 'two', 'three']

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值