python3不完全笔记(一)基础

python3不完全笔记

python3相对于pyhton2.x做了较大的升级,但是许多基于早期python的程式都无法在python3上运行(为了减少累赘). 目前不支援python3的第三方库包括Twisted,py2exe,PIL之类.如果说需要一个过渡的话,python2.6基本使用python2的语法库, 也允许使用部分python3的语法和函数.
下面做一个对比:

changepython2python3
printcapable without ‘()’
>>>print “China”
must have ()
UnicodeASCII str(), isolate unicode()
>>>str = “我”; print (str)
’\xe6’
default utf-8
division>>> 1 / 2
0
>>>1.0 / 2.0
0.5
>>>1 / 2
0.5
//# floor, both is the same
>>>-1 // 2
-1
abnormalexcept exc, varexcept exc as var
xrange-xrange creates NameError, replace with range
Octal07770o777
# Binary: 0b111
unequal!=
<>
!=

Python2中其实没有布尔类型,0表示False,1表示True.Python3才把False和True定义成关键字, 但是值依然不变, 也可与数字相加

命令行参数

$ python -h

基础语法

编码

默认源文件UTF-8编码
也可以指定编码方式:

# -*- coding: cp-1252

标识符

首字:下划线或字母
大小写敏感

注释

单行

# 这是单行注释

多行

'''
第一行注释
下一行注释
'''

"""
这种
形式
也可
"""

不换行与换行输出

print()输出默认换行, 不需要换行在后加end=" "

print(x, end = " ")

缩进

用缩进代替大括号

多行语句

反斜杠\表示多行

tmp = item_one + \
      item_two + \
      item_three

变量赋值后用三对双引号括多行字串(像注释,需要注意)

>>> tmp = """this is a 
>>>       multi-line"""
>>> print (tmp)
this is a 
      multi-line

Process finished with exit code 0

数据类型

标准数据类型

{ 可 变 { L i s t [ ] : 元 素 类 型 不 必 相 同 D i c t i o n a r y 键 : 值 , 元 素 通 过 键 ( 必 是 不 可 变 类 型 ) 获 取 S e t { } , 也 可 用 s e t ( v a l u e . . . ) 创 建 , 可 进 行 成 员 关 系 测 试 或 去 重 ( 交 并 差 , 不 同 时 存 在 ) 不 可 变 { N u m b e r S t r i n g , 用 s t r ∗ n 重 复 输 出 n 次 , 用 T u p l e ( ) : 元 素 类 型 不 必 相 同 , 可 包 含 可 变 对 象 \begin{cases} 可变\begin{cases} List[]: 元素类型不必相同\\ Dictionary{键:值},元素通过键(必是不可变类型)获取\\ Set\{\},也可用set(value...)创建,可进行成员关系测试或去重(交并差,不同时存在^) \end{cases}\\ 不可变\begin{cases} Number\\ String,用str*n重复输出n次,用%格式化输出\\ Tuple(): 元素类型不必相同,可包含可变对象 \end{cases} \end{cases} List[]:Dictionary:,()Set{},set(value...),(,){NumberString,strnn,Tuple():,

数字

  • int: 长整型
  • bool
  • float
  • complex: 复数

数据类型的判断

type()不认为子类与父类是同一种数据类型,而isinstance()反之

  • isinstance()
>>> a = 111
>>> isinstance(a, int)
True
  • type()
>>> class A:
···     xxx
···     
>>> class B(A):
···     xxx
··· 
>>> isinstance(A(), A)
True
>>> isinstance(B(), A)
True
>>> type(A()) == A
True
>>> type(B()) == A
False

数据类型转换

函数描述
int(x, 进制数)x转int
float(x)x转浮点数
complex(实部, 虚部)创建一复数
str(x)x转string
repr(x)x转为表达式(供解释器读取的形式,其实就是变成string了)
chr(x)整数x变字符
ord(x)字符变整数
hex(x)整数转16进制
oct(x)整数转8进制
dict()创建一字典
frozenset(s)转为不可变集合

转义 ‘\’

使用r让反斜杠不转义,r指’raw’

>>> tmp = "thie is a example\n"
>>> print (tmp)
this is an example


Process finished with exit code 0
----------------
>>> tmp = r"this is an example\n"
>>> print (tmp)
this is an example\n

Process finished with exit code 0

索引

从左往右以0开始, 从右往左以-1开始

函数,类之间的分隔

空行
空行不是语法,不写不会报错

等待输入(类似于system(“pause”))

input("\n按下enter退出") #引号内可输其他,退出只能空行

运算符

取地址

id()

大于/小于等于

>=或者<=

幂赋值

x ** = y等价于x = x ** y

取整除赋值

//==

海象运算符

:=,在表达式内部为变量赋值,把表达式的一部分赋值给变量.据说是py3.8的新东西
官网这么介绍的:

There is new syntax := that assigns values to variables as part of a larger expression. It is affectionately known as “the walrus operator” due to its resemblance to the eyes and tusks of a walrus.

看起来类似于循环或判断中的局部变量赋值,省去赋值中间变量的步骤
举个例子:

# 1
if (n := len(a)) > 10:
    print(f"List is too long ({n} elements, expected <= 10)")
# 2, 不用海象算符
if len(a) > 10:
    print(f"List is to long({len(a)} elements, expected <= 10)")
# 3 或者
n = len(a)
if n > 10:
    print(f"List is to long({n} elements, expected <= 10)")

逻辑运算

and, or, not

成员运算符

in, not in

身份运算

is, is not
is判断两个引用对象是否是同一个, ==判断引用变量的值是否相等

随机数

choice(seq)

从序列中随机选

randrange(start,stop,step)或randrange(num)

从指定范围(包括start开始,以step递增到stop结束的数字中)随机选,step默认1

random()

随机实数,[0, 1)

uniform(x, y)

随机实数,[x, y]

shuffle(lst)

将序列lst的所有元素随机排序

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值