2021-04-22

本文介绍了Python中注释的使用,包括单行和多行注释,以及运算符的分类和优先级,涵盖了算术、比较、逻辑、位运算和三元运算。此外,详细讲解了数据类型、转换、条件语句(if, elif, else, assert)和循环(while, for, with)等内容,以及异常处理的基本概念和try-except-finally-else结构。
摘要由CSDN通过智能技术生成

天池学习笔记:

task01

1. 注释

在 Python 中,# 表示注释,作用于整行。

#表示一个注释
print("Hello world")

运行:Hello world

'''
这是多行注释
这是多行注释
'''

运行:''' ''' 或者 """ """ 表示区间注释,在三引号之间的所有内容被注释

【我是测试题1】请在下方代码块中打印(print)出 hello+你的姓名

如:print("叶欢")

print('Hello yehuan')

运行:Hello yehuan

2. 运算符

算术运算符

操作符 名称 示例

'+' 加 1 + 1

'-' 减 2 - 1

'*' 乘 3 * 4

'/' 除 3 / 4

'//' 整除(地板除)

'%' 取余 3 % 4

'*' 幂 2 * 3


print(1+1)#2
print(1-23)#-22
print(2*2)#4
print(2/2)#1
print(4//3)#1
print(3%4)#3
print(2**3)#6

比较运算符

操作符 名称 示例

'>' 大于 2 > 1

'>=' 大于等于 2 >= 4

< 小于 1 < 2

<= 小于等于 5 <= 2

== 等于 3 == 4

!= 不等于 3 != 5

print(2 > 2)  # fales
print(2 >= 1)  # ture
print(1 < 2)  # True
print(5 <= 6)  # ture
print(3 == 3)  # ture
print(3 != 2)  # True

逻辑运算符

操作符 名称 示例

and 与 (3 > 2) and (3 < 5)

or 或 (1 > 3) or (9 < 2)

not 非 not (2 > 1)

print((3>2)and(3<4))#true
print((1>2)or(2>2))#false == 是判断符
print(not(2>2))#true

位运算符

操作符 名称 示例 ~ 按位取反 ~4

& 按位与 4 & 5

'`' 按位或

^ 按位异或 4 ^ 5

<< 左移 4 << 2

'>>' 右移 4 >> 2

print(bin(4))  # 0b100
print(bin(5))  # 0b101
print(bin(~4), ~4)  # -0b101 -5
print(bin(4 & 5), 4 & 5)  # 0b100 4
print(bin(4 | 5), 4 | 5)  # 0b101 5
print(bin(4 ^ 5), 4 ^ 5)  # 0b1 1
print(bin(4 << 2), 4 << 2)  # 0b10000 16
print(bin(4 >> 2), 4 >> 2)  # 0b1 1

三元运算符

x,y=2,4
small=x if x>y else y
print(small)#4

其他运算符

操作符 名称 示例

in 存在 'A' in ['A', 'B', 'C']

not in 不存在 'h' not in ['A', 'B', 'C']

is 是 "hello" is "hello"

not is 不是 "hello" is not "hello"

letter='adc'
if 'a' in letter:
    print('a'+' exists')
if 'h' not in letter:
    print('h'+' not existes')

#a exists
#h not existes

【例子】比较的两个变量均指向不可变类型

a = "hello"
b = "hello"
print(a is b, a == b)  # True True
print(a is not b, a != b)  # False False

【例子】比较的两个变量均指向可变类型。

a = ["hello"]
b = ["hello"]
print(a is b, a == b)  # False True
print(a is not b, a != b)  # True False

注意

is, is not 对比的是两个变量的内存地址

==, != 对比的是两个变量的值

比较的两个变量,指向的都是地址不可变的类型(str等),那么is,is not 和 ==,!= 是完全等价的。

对比的两个变量,指向的是地址可变的类型(list,dict,tuple等),则两者是有区别的

运算符的优先级

运算符 描述

** 指数(最高优先级)

~+- 按位翻转,一元加号和减号

  • / % // 乘,除,取模和取整除)

    • 加法减法

'>> << 右移,左移运算符'

'& 位‘AND’'

'^| 位运算符'

'<=<>>= 比较运算符'

'<>==!= 等于运算符'

'=%=/=//=-=+==*= 赋值运算符'

'is is not 身份运算符'

'in not in 成员运算符'

'not and or 逻辑运算符'

'pop 删除最后一个元素'
set_1=['k',2,3]
print(set_1.pop())

4.数据类型与转换

a=1
type(a)#type查看数据类型
#int
b=dir(int)
print(b)

#['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__init_subclass__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']
#【例子】找到一个整数的二进制表示,再返回其长度。
a=21
print(bin(a))
print(a.bit_length())

#0b10101
#5
#可以使用decimal里的Decimal对象和getcontext()来实现
import decimal
from decimal import Decimal

#getcontext() 显示了 Decimal 对象的默认精度值是 28 位 (prec=28)。

使 1/3 保留 4 位,用 getcontext().prec 来调整精度。

decimal.getcontext().prec=3
c=Decimal(1)/Decimal(3)
print(c)

#0.333

布尔型

除了直接给变量赋值 True 和 False,还可以用 bool(X) 来创建变量,其中 X 可以是

基本类型:整型、浮点型、布尔型 容器类型:字符串、元组、列表、字典和集合

bool 作用在容器类型变量:X 只要不是空的变量,bool(X) 就是 True,其余就是True

print(type(''),bool(''),bool('python'))
#<class 'str'> False True

确定bool(X) 的值是 True 还是 False,就看 X 是不是空,空的话就是 False,不空的话就是 True。

对于数值变量,0, 0.0 都可认为是空的。 对于容器变量,里面没元素就是空的。

type() 不会认为子类是一种父类类型,不考虑继承关系。 isinstance() 会认为子类是一种父类类型,考虑继承关系。

 

print()函数

#print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

将对象以字符串表示的方式格式化输出到流文件对象file里。其中所有非关键字参数都按str()方式进行转换为字符串输出; 关键字参数sep是实现分隔符,比如多个参数输出时想要输出中间的分隔字符; 关键字参数end是输出结束时的字符,默认是换行符\n; 关键字参数file是定义流输出的文件,可以是标准的系统输出sys.stdout,也可以重定义为别的文件; 关键字参数flush是立即把内容输出到流文件,不作缓存。

位运算

  1. 原码、反码和补码 二进制有三种不同的表示形式:原码、反码和补码,计算机内部使用补码来表示。

原码:就是其二进制表示(注意,有一位符号位)。

00 00 00 11 -> 3 10 00 00 11 -> -3 反码:正数的反码就是原码,负数的反码是符号位不变,其余位取反(对应正数按位取反)。

00 00 00 11 -> 3 11 11 11 00 -> -3 补码:正数的补码就是原码,负数的补码是反码+1。

00 00 00 11 -> 3 11 11 11 01 -> -3 符号位:最高位为符号位,0表示正数,1表示负数。在位运算中符号位也参与运算。

  1. 利用位运算实现快速计算 通过 <<,>> 快速计算2的倍数问题。

n << 1 -> 计算 n2 n >> 1 -> 计算 n/2,负奇数的运算不可用 n << m -> 计算 n(2^m),即乘以 2 的 m 次方 n >> m -> 计算 n/(2^m),即除以 2 的 m 次方 1 << n -> 2^n 通过 ^ 快速交换两个整数。 通过 ^ 快速交换两个整数。

a ^= b b ^= a a ^= b 通过 a & (-a) 快速获取a的最后为 1 位置的整数。

00 00 01 01 -> 5 & 11 11 10 11 -> -5


00 00 00 01 -> 1

00 00 11 10 -> 14 & 11 11 00 10 -> -14


00 00 00 10 -> 2

Python中bin一个负数(十进制表示),输出的是它的原

码的二进制表示加上个负号,巨坑。 Python中的整型是补码形式存储的。 Python中整型是不限制长度的不会超范围溢出。 所以为了获得负数(十进制表示)的补码,需要手动将其和十六进制数0xffffffff进行按位与操作,再交给bin()进行输出,得到的才是负数的补码表示。

条件语句

if 条件语句

if 语句的 expr_true_suite 代码块只有当条件表达式 expression 结果为真时才执行,否则将继续执行紧跟在该代码块后面的语句。 单个 if 语句中的 expression 条件表达式可以通过布尔操作符 and,or和not 实现多重条件判断。 if ture: run else: run


if 2>1 and not 2>4:
    print('run')

#run

 if -elif-elif-else

Python 提供与 if 搭配使用的 else,如果 if 语句的条件表达式结果布尔值为假,那么程序将执行 else 语句后的代码。


temp=input('say a No.')
guess=int(temp)
if guess==3:
    print('good')
else:
    print('worng')
print('game over')

#say a No. 3
#good
#game over
#if 语句还支持在一个if 语句中嵌套另外一个语句
hi = 6
if hi > 2:
    if hi > 7:
        print('好棒!好棒!')
else:
    print('切~')

# 无输出
temp = input("猜一猜小姐姐想的是哪个数字?")
guess = int(temp)
if guess > 8:
    print("大了,大了")
else:
    if guess == 8:
        print("你太了解小姐姐的心思了!")
        print("哼,猜对也没有奖励!")
    else:
        print("小了,小了")
print("游戏结束,不玩儿啦!")


#猜一猜小姐姐想的是哪个数字? 56
#大了,大了
#游戏结束,不玩儿啦!

if - elif - else 语句

if expression1: expr1_true_suite elif expression2: expr2_true_suite . . elif expressionN: exprN_true_suite else: expr_false_suite

 

assert关键词

assert这个关键词我们称之为“断言”,当这个关键词后边的条件为 False 时,程序自动崩溃并抛出AssertionError的异常

#sample
assert 3>4
---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
<ipython-input-39-62ee76fd2130> in <module>
      1 #sample
----> 2 assert 3>4

AssertionError: 

循环语句

while 循环

while 布尔表达式: 代码块 while循环的代码块会一直循环执行,直到布尔表达式的值为布尔假

count = 0
while count < 3:
    temp = input("猜一猜小姐姐想的是哪个数字?")
    guess = int(temp)
    if guess > 8:
        print("大了,大了")
    else:
        if guess == 8:
            print("你太了解小姐姐的心思了!")
            print("哼,猜对也没有奖励!")
            count = 3
        else:
            print("小了,小了")
    count = count + 1
print("游戏结束,不玩儿啦!")



猜一猜小姐姐想的是哪个数字? 2
小了,小了
猜一猜小姐姐想的是哪个数字? 3
小了,小了
猜一猜小姐姐想的是哪个数字? 8
你太了解小姐姐的心思了!
哼,猜对也没有奖励!
游戏结束,不玩儿啦!

while -else 循环

while 布尔表达式: 代码 else: code

当while循环正常执行完的情况下,执行else输出,如果while循环中执行了跳出循环的语句,比如 break,将不执行else代码块的内容。

count = 0
while count < 5:
    print("%d is  less than 5" % count)
    count = count + 1
else:
    print("%d is not less than 5" % count)


0 is  less than 5
1 is  less than 5
2 is  less than 5
3 is  less than 5
4 is  less than 5
5 is not less than 5
count = 0
while count < 5:
    print("%d is  less than 5" % count)
    count = 6
    break
else:
    print("%d is not less than 5" % count)

# 0 is  less than 5


count = 0
while count < 5:
    print("%d is  less than 5" % count)
    count = 6
    continue
else:
    print("%d is not less than 5" % count)



0 is  less than 5
6 is not less than 5

for 循环

for循环是迭代循环,在Python中相当于一个通用的序列迭代器,可以遍历任何有序序列,如str、list、tuple等,也可以遍历任何可迭代对象,如dict。

for 迭代变量 in 可迭代对象: 代码块 每次循环,迭代变量被设置为可迭代对象的当前元素,提供给代码块使用。

for i in 'ILoveLSGO':
    print(i, end=' ') 

#I L o v e L S G O 

dic={'a':2,'b':3}
for key,value in dic.items():
    print(key,value,sep=':',end=' ')

#a:2 b:3 

dic = {'a': 1, 'b': 2, 'c': 3, 'd': 4}

for value in dic.values():
    print(value, end=' ')

#1 2 3 4 


for else 循环

for 迭代变量 in 可迭代对象: 代码块 else: 代码块 当for循环正常执行完的情况下,执行else输出,如果for循环中执行了跳出循环的语句,比如 break,将不执行else代码块的内容,与while - else语句一样。

#寻找质数
for num in range(10,20):
    for i in range(2,num):
        if num%i==0:#计算第一各因子
            j=num/i#计算第二个因子
            print('{}等于{}*{}'.format(num,i,j))
            break#跳出当前循环
    else:#循环的else部分
        print(num,'是一个质数')


10等于2*5.0
11 是一个质数
12等于2*6.0
13 是一个质数
14等于2*7.0
15等于3*5.0
16等于2*8.0
17 是一个质数
18等于2*9.0
19 是一个质数

range()函数

range([start,] stop[, step=1]) 这个BIF(Built-in functions)有三个参数,其中用中括号括起来的两个表示这两个参数是可选的。 step=1 表示第三个参数的默认值是1。 range 这个BIF的作用是生成一个从start参数的值开始到stop参数的值结束的数字序列,该序列包含start的值但不包含stop的值。

enumerate()函数

enumerate(sequence, [start=0]) sequence:一个序列、迭代器或其他支持迭代对象。 start:下标起始位置。 返回 enumerate(枚举) 对象

a=[2,4]
list(enumerate(a))
#[(0, 2), (1, 4)]

seasons = ['Spring', 'Summer', 'Fall', 'Winter']
lst = list(enumerate(seasons))
print(lst)
# [(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
lst = list(enumerate(seasons, start=1))  # 下标从 1 开始
print(lst)
# [(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]


[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
for i, a in enumerate(A) i 下标 a value

break 语句

break语句可以跳出当前所在层的循环

continue 语句

continue终止本轮循环并开始下一轮循环

pass 语句

pass 语句的意思是“不做任何事”,如果你在需要有语句的地方不写任何语句,那么解释器会提示出错,而 pass 语句就是用来解决这些问题的。

推导式

[ expr for value in collection [if condition] ]

x = [(i, i ** 2) for i in range(6)]
print(x)

#[(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]

a = [(i, j) for i in range(0, 3) for j in range(0, 3)]
print(a)

#[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]

x = [[i, j] for i in range(0, 3) for j in range(0, 3)]
print(x)
# [[0, 0], [0, 1], [0, 2], [1, 0], [1, 1], [1, 2], [2, 0], [2, 1], [2, 2]]

x[0][0] = 10
print(x)
# [[10, 0], [0, 1], [0, 2], [1, 0], [1, 1], [1, 2], [2, 0], [2, 1], [2, 2]]

元组推到式

( expr for value in collection [if condition] )

字典推导式

{ key_expr: value_expr for value in collection [if condition] }

b = {i: i % 2 == 0 for i in range(10) if i % 3 == 0}
print(b)
# {0: True, 3: False, 6: True, 9: False}

s = sum([i for i in range(101)])
print(s)  # 5050
s = sum((i for i in range(101)))
print(s)  # 5050

1. Python 标准异常总结

BaseException:所有异常的 基类

Exception:常规异常的 基类

StandardError:所有的内建标准异常的基类

ArithmeticError:所有数值计算异常的基类

FloatingPointError:浮点计算异常

OverflowError:数值运算超出最大限制

ZeroDivisionError:除数为零

AssertionError:断言语句(assert)失败

AttributeError:尝试访问未知的对象属性

EOFError:没有内建输入,到达EOF标记

EnvironmentError:操作系统异常的基类

IOError:输入/输出操作失败

OSError:操作系统产生的异常(例如打开一个不存在的文件)

WindowsError:系统调用失败

ImportError:导入模块失败的时候

KeyboardInterrupt:用户中断执行

LookupError:无效数据查询的基类

IndexError:索引超出序列的范围

KeyError:字典中查找一个不存在的关键字

MemoryError:内存溢出(可通过删除对象释放内存)

NameError:尝试访问一个不存在的变量

UnboundLocalError:访问未初始化的本地变量

ReferenceError:弱引用试图访问已经垃圾回收了的对象

RuntimeError:一般的运行时异常

NotImplementedError:尚未实现的方法

SyntaxError:语法错误导致的异常

IndentationError:缩进错误导致的异常

TabError:Tab和空格混用

SystemError:一般的解释器系统异常

TypeError:不同类型间的无效操作

ValueError:传入无效的参数

UnicodeError:Unicode相关的异常

UnicodeDecodeError:Unicode解码时的异常

UnicodeEncodeError:Unicode编码错误导致的异常

UnicodeTranslateError:Unicode转换错误导致的异常

异常体系内部有层次关系,Python异常体系中的部分关系如下所示:

2.Python标准警告总结

Warning:警告的基类

DeprecationWarning:关于被弃用的特征的警告

FutureWarning:关于构造将来语义会有改变的警告

UserWarning:用户代码生成的警告

PendingDeprecationWarning:关于特性将会被废弃的警告

RuntimeWarning:可疑的运行时行为(runtime behavior)的警告

SyntaxWarning:可疑语法的警告

ImportWarning:用于在导入模块过程中触发的警告

UnicodeWarning:与Unicode相关的警告

BytesWarning:与字节或字节码相关的警告

ResourceWarning:与资源使用相关的警告

3. try - except 语句

try:

检测范围

except Exception[as reason]:

出现异常后的处理代码

try 语句按照如下方式工作:

首先,执行try子句(在关键字try和关键字except之间的语句) 如果没有异常发生,忽略except子句,try子句执行后结束。 如果在执行try子句的过程中发生了异常,那么try子句余下的部分将被忽略。如果异常的类型和except之后的名称相符,那么对应的except子句将被执行。最后执行try - except语句之后的代码。 如果一个异常没有与任何的except匹配,那么这个异常将会传递给上层的try中。

try:
    f = open('test.txt')
    print(f.read())
    f.close()
except OSError:
    print('打开文件出错')

# 打开文件出错

try:
    f = open('test.txt')
    print(f.read())
    f.close()
except OSError as error:
    print('打开文件出错\n原因是:' + str(error))

# 打开文件出错
# 原因是:[Errno 2] No such file or directory: 'test.txt'

try:
    int("abc")
    s = 1 + '1'
    f = open('test.txt')
    print(f.read())
    f.close()
except OSError as error:
    print('打开文件出错\n原因是:' + str(error))
except TypeError as error:
    print('类型出错\n原因是:' + str(error))
except ValueError as error:
    print('数值出错\n原因是:' + str(error))

# 数值出错
# 原因是:invalid literal for int() with base 10: 'abc'

dict1 = {'a': 1, 'b': 2, 'v': 22}
try:
    x = dict1['y']
except LookupError:
    print('查询错误')
except KeyError:
    print('键错误')
else:
    print(x)

# 查询错误

try-except-else语句尝试查询不在dict中的键值对,从而引发了异常。这一异常准确地说应属于KeyError,但由于KeyError是LookupError的子类,且将LookupError置于KeyError之前,因此程序优先执行该except代码块。所以,使用多个except代码块时,必须坚持对其规范排序,要从最具针对性的异常到最通用

dict1 = {'a': 1, 'b': 2, 'v': 22}
try:
    x = dict1['y']
except KeyError:
    print('键错误')
except LookupError:
    print('查询错误')
else:
    print(x)

# 键错误

一个 except 子句可以同时处理多个异常,这些异常将被放在一个括号里成为一个元组。

try:
    s = 1 + '1'
    int("abc")
    f = open('test.txt')
    print(f.read())
    f.close()
except (OSError, TypeError, ValueError) as error:
    print('出错了!\n原因是:' + str(error))

# 出错了!
# 原因是:unsupported operand type(s) for +: 'int' and 'str'



4. try - except - finally 语句

try: 检测范围 except Exception[as reason]: 出现异常后的处理代码 finally: 无论如何都会被执行的代码

不管try子句里面有没有发生异常,finally子句都会执行。

【例子】如果一个异常在try子句里被抛出,而又没有任何的except把它截住,那么这个异常会在finally子句执行后被抛出。

【例子】如果一个异常在try子句里被抛出,而又没有任何的except把它截住,那么这个异常会在finally子句执行后被抛出。

5. try - except - else 语句

如果在try子句执行时没有发生异常,Python将执行else语句后的语句。

try: 检测范围 except: 出现异常后的处理代码 else: 如果没有异常执行这块代码

使用except而不带任何异常类型,这不是一个很好的方式,我们不能通过该程序识别出具体的异常信息,因为它捕获所有的异常。

try: 检测范围 except(Exception1[, Exception2[,...ExceptionN]]]): 发生以上多个异常中的一个,执行这块代码 else: 如果没有异常执行这块代码

try:
    fh = open("testfile.txt", "w")
    fh.write("这是一个测试文件,用于测试异常!!")
except IOError:
    print("Error: 没有找到文件或读取文件失败")
else:
    print("内容写入文件成功")
    fh.close()

#内容写入文件成功

注意:else语句的存在必须以except语句的存在为前提,在没有except语句的try语句中使用else语句,会引发语法错误。

6. raise语句

Python 使用raise语句抛出一个指定的异常。

try:
    raise NameError('HiThere')
except NameError:
    print('An exception flew by!')
    
# An exception flew by!

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值