Python3 简单语句
Python3 数据类型转换
Python3 内置函数
Python3 运算符
Python3 数学函数
Python3 随机数函数
Python3 三角函数
Python3 字符串格式化符号
Python3 字符串内建函数
Python3 format()格式化
[python numpy, plot, random,time, calendar]
包(Package):子包和模块组成。包内第一个文件为 __init__.py
。
模块:.py
文件,内定义函数
、类
、变量
#!/usr/local/bin/python3
# -*- coding:utf-8 -*-
#!/usr/bin/env python
# -*- coding:utf-8 -*-
#!/usr/bin/python
# -*- coding:utf-8 -*-
#coding=utf-8
#coding:utf-8
#-*- coding:utf-8 -*-
assert isinstance(str, object)
# 查看python版本:win+R运行cmd,打开命令提示符,键入python --version
# 或者在开始菜单中,搜索IDLE,打开IDLE Shell,键入python --version
# 终端上键入 python --version 查看python版本
# 终端上键入 which python3 查看python3位置 /usr/local/bin/python3
# / 表示根目录
# . 代表当前所在目录 ./ 代表当前所在目录下的某个文件夹或文件
# .. 代表当前所在目录的父目录 ../代表当前所在目录的父目录下的某个文件夹或文件
# windows 下的文件目录路径使用\分隔,但是Python字符串中的\是转义字符,可以在路径前加r避免转移,可以添加转移字符\,可以正斜杠/
# os.path.exists('E:/test/file.txt')
# os.path.exists('E:\\test\\file.txt')
# os.path.exists(r'E:\test\file.txt')
# 查看 python 保留关键字。
>>>import keyword
>>>keyword.kwlist
age = input("请输入年龄:")
# 数值的除法包含两个运算符:/ 返回一个浮点数,// 返回一个整数(向下取整)。
# 可以使用 ** 运算符计算幂乘方。
# 在交互模式中,最后被输出的表达式结果被赋值给变量_
>>> a = 1
>>> a + 2
3
>>> 4 + _
7
if __name__ == '__main__':
Python3 相关内容
前缀:r/b/u/f
r'input\n' # 非转义的原始字符串
b'input\n' # bytes字节符
u'李中\n' # unicode编码字符串
name="李中"
f'name is {name}' # format()格式化操作
多行语句
# 可以使用反斜杠\来实现多行语句
s1 = 'Hello ' + \
'World!'
# Python 三引号允许一个字符串跨多行,字符串中可以包含换行符、制表符以及其他特殊字符。
s2 = '''这是一个多行字符串的实例
多行字符串可以使用制表符
TAB ( \t )。
也可以使用换行符 [ \n ]。
'''
print(s1, s2)
# 可以在同一行显示多条语句,用分号;分割
import sys; x = 'www.Runoob.com'; sys.stdout.write(x + '\n')
# print 默认输出是换行的,若实现不换行需要在变量末尾加上 end=''
print('end=', '\n\n', end='')
'''
多行注释
'''
None 类型
Python 中的 None
是一个特殊的常量,和 False 不同,它不表示 0,也不表示空字符串,而表示没有值,也就是空值。这里的空值并不代表空对象,即None
和 []、“” 不同,它属于 NoneType
类型。
None
是 NoneType
数据类型的唯一值(其他编程语言可能称这个值为 null、nil 或 undefined)。除此之外,None
常用于 assert
、判断以及函数无返回值的情况。
>>> None is []
False
>>> None is ""
False
>>> type(None)
<class 'NoneType'>
>>> spam = print('Hello!')
Hello!
>>> None == spam
True
条件控制
if 'Runoob' in s3:
print('Runoob 在集合中')
elif 'Runoob' not in s3:
print('Runoob 不在集合中')
else:
print('other')
循环控制
count = 0
while count < 5:
print (count, " 小于 5")
count = count + 1
else:
print (count, " 大于或等于 5")
sites = ["Baidu", "Google","Runoob","Taobao"]
for site in sites:
if site == "Runoob":
print("菜鸟教程!")
break
print("循环数据 " + site)
else:
print("没有循环数据!")
print("完成循环!")
Python3 模块
import 与 from…import
- 将整个模块导入:
import somemodule
- 从某个模块中导入某个函数:
from somemodule import somefunction
- 从某个模块中导入多个函数:
from somemodule import firstfunc, secondfunc, thirdfunc
- 将某个模块中的全部函数导入:
from somemoudle import *
__name__属性 & dir() 函数
可以用
__name__
属性来使该程序块仅在该模块自身运行时执行
内置函数dir()
可以显示模块内定义的所有名称。
# !/usr/local/bin/python3
# Filename: support.py
def print_func(par):
print ("Hello : ", par)
if __name__=='__main__':
print('程序自身在运行')
else:
print('我来自另一模块')
return
# !/usr/local/bin/python3
# Filename: test.py
# 导入模块
import support
# 现在可以调用模块里包含的函数了
support.print_func("Runoob")
print(dir(support))
print(support.__name__)
'''
内置属性:
__doc__:模块中用于描述的文档字符串
__name__:模块名
__file__:模块保存的路径
__dict__:类的属性
__module__:类定义所在的模块
__bases__:类的所有父类构成元素
'''
Python3 输入输出
可以使用
repr()
或str()
函数将输出值转成字符串
-str()
:返回一个用户易读的表达形式
-repr()
:返回一个解释器易读的表达形式
import sys
sys.stdout.write("hello"+'\n')
print("hello")
# repr() 函数可以转义字符串中的特殊字符
s = 'hello python\n'
print(s)
print(repr(s))
# repr() 函数的参数可以是Python的任何对象
s1 = (3.25, 1.1+2.2j, ('google', 'facebook'))
print(repr(s1))
for x in range(1, 11):
print(repr(x).rjust(2), repr(x**2).rjust(3), end=' ')
# 注意前一行 'end' 的使用
print(repr(x**3).rjust(4))
for x in range(1, 11):
print('{0:2d} {1:3d} {2:4d}'.format(x, x**2, x**3))
for x in range(1, 11):
print('%2d %3d %4d' %(x, x**2, x**3))
# !a (使用 ascii()), !s (使用 str()) 和 !r (使用 repr()) 可以用于在格式化某个值之前对其进行转化:
print('{} {!s} {!r}'.format('hello\n', 'hello\n', 'hello\n'))
Python3 错误和异常
# 异常处理
import sys
try:
f = open('a.txt', 'w')
s = f.readline()
i = int(s.strip())
except OSError as err:
print("OS error: {0}".format(err))
except ValueError:
print("Could not convert data to an integer.")
except:
print("Unexpected error:", sys.exc_info()[0])
# sys.exc_info() 返回是一个元组,exc_type 是异常的对象类型,exc_value 是异常的值,exc_tb 是一个 traceback 对象,对象中包含出错的行数、位置等数据。
raise
else:
print("没有异常时执行的代码")
print(i)
finally: #定义清理行为
print("不管有没异常都会执行的代码")
f.close()
# 抛出异常
try:
raise Exception('spam', 'eggs')
except Exception as inst:
print(type(inst))
print(inst, inst.args)
x, y = inst.args
print("x=", x)
print("y=", y)
# 用户自定义异常
class MyError(Exception):
def __init__(self, value):
self.value = value # 实例变量 value
def __str__(self):
return repr(self.value)
try:
raise MyError(2*2)
except MyError as err:
print("My exception occurred, value", err.value)
finally: # 定义清理行为
print("Goodbye, world!")
assert 语句
# assert 语句条件为真,继续执行。否则,抛出错误 AssertionError
def zero(s):
a = int(s)
assert a > 0
print(a)
zero("-2")
Python3 命名空间和作用域
三种命名空间:
内置名称:built-in
全局名称:global
局部名称:local
命名空间查找顺序:local → Enclosing → global → built-in
Python3 内置变量和方法可通过模块 builtins 查看:
>>> import builtins
>>> dir(builtins)
global 和 nonlocal关键字
# 局部变量只能在其被声明的函数内部访问,而全局变量可以在整个程序范围内访问.
# 当内部作用域想修改外部作用域的变量时,就要用到 global 和nonlocal 关键字.
num = 1
def fun():
global num # global 关键字声明
print(num)
num = 123
print(num)
fun()
print(num)
def outer():
num = 10
def inner():
nonlocal num # nonlocal 关键字声明
num = 100
print(num)
inner()
print(num)
outer()
Python 闭包与嵌套函数类似,不同之处在于,闭包中外部函数返回的不是一个具体的值,而是一个函数。一般情况下,返回的函数会赋值给一个变量,这个变量可以在后面被继续执行调用。
#闭包函数,其中 exponent 称为自由变量
def nth_power(exponent):
def exponent_of(base):
return base ** exponent
return exponent_of # 返回值是 exponent_of 函数
square = nth_power(2) # 计算一个数的平方
cube = nth_power(3) # 计算一个数的立方
print(square(2)) # 计算 2 的平方
print(square.__closure__) # 该属性记录着自由变量的地址(也就是 exponent 参数存储的地址)
print(cube(2)) # 计算 2 的立方
print(cube.__closure__)