Python入门1(上)

变量、运算符、数据类型

1. 注释

  • 单行注释 #
    【例子】
    #这是打印
    print("hello")
    
    hello
  • 多行注释 ‘’’ ‘’’ 或"“” “”"
    【例子】
    '''
    多行注释1,三个单引号
    多行注释1,三个单引号
    '''
    print("hello,三个单引号")
    """
    多行注释2,三个双引号
    多行注释2,三个双引号
    """
    print("hello,三个双引号")
    
    hello,三个单引号
    hello,三个双引号

2.运算符

算数运算符

操作符名称示例
+1+1
-2-1
*2*2
/2/1
%3%2
//整除3//2
**2**3

【例子】

print(1+1)
print(2-1)
print(2*2)
print(2/1)
print(3%2)
print(3//2)
print(3**2)

2
1
4
2.0
1
1
9

比较运算符

操作符名称示例
>大于3>2
>=大于等于3>=2
<小于3<2
<=小于等于3<=2
==等于3==2
!=不等3!=2

【例子】

print(3 > 2)
print(3 >= 2)
print(3 < 2)
print(3 <= 2)
print(3 == 2)
print(3 != 2)

True
True
False
False
False
True

逻辑运算符

操作符名称示例
and(3>2) and (3<2)
or(3>2) and (3<2)
notnot (3<2)

【例子】

print((3 > 2) and (3 > 2))
print((3 > 2) or (3 > 2))
print(not (3 > 2))

True
True
False

位运算符

操作符名称示例
~按位取反~4
&按位与5&4
|按位或5|4
^按位异或5^4
<<左移5<<2
>>右移5>>2

【例子】

print(bin(5))
print(bin(4))
print(bin(~4))
print(bin(5 & 4))
print(bin(5 | 4))
print(bin(5 ^ 4))
print(bin(5 << 2))
print(bin(5 >> 2))

0b101
0b100
-0b101
0b100
0b101
0b1
0b10100
0b1

三元运算符

【例子】

x, y = 4, 5
if x < y:
    small = x
else:
    small = y
print(small)  

4
可以写成以下一条语句

small = x if x < y else y
print(small)  

4

其它运算符

操作符名称示例
in存在5 in [2,3,5]
not in不存在5 not in [2,3,5]
is是否同一个对象
is not不是不是同一个对象

【例子】

print(5 in [2, 3, 5])
print(5 not in [2, 3, 5])
a = "hello"
b = "hello"
print(a is b)
print(a is not b)

True
False
True
False
注意== 和is

==是比较变量的值,is 变量是否同一个内存地址。

运算符优先级

运算符描述
**
~+-按位翻转,一元加号和减号
* / % //乘 除 余 整除
+ -加 减
>> <<右移 左移
&位与
^ |位异或 位或
> >= < <=比较运算符
== !=<>
= += -= *= /= %= //=赋值运算符
is is not身份运算符
in not in成员运算符
not and or逻辑运算符

3.变量和赋值

  • 使用变量之前,需要对其进行赋值
  • 变量名可以数字、字符、下划线,不能以数字开头
  • 变量名大小写敏感

【例子】

a = 1
a_1 = 2
A = 3
print(a)
print(a_1)
print(A)
print(a is A)

1
2
3
False

4.数据类型与转换

python所有的都是对象,整形,浮点型,布尔型也不例外。

类型名称示例
int<class ‘int’>4, 5
float<class ‘float’>2.1 ,3.2
bool<class ‘bool’>True,False

type 获取类型信息,dir 返回当前范围内的变量、方法和定义的类型列表

整形

【例子】

a = 4
print(a, type(a))
print(dir(int))

4 <class ‘int’>
[‘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’, ‘as_integer_ratio’, ‘bit_length’, ‘conjugate’, ‘denominator’, ‘from_bytes’, ‘imag’, ‘numerator’, ‘real’, ‘to_bytes’]

浮点型

【例子】

a = 2.1
print(a, type(a))
print(dir(int))

2.1 <class ‘float’>
[‘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’, ‘as_integer_ratio’, ‘bit_length’, ‘conjugate’, ‘denominator’, ‘from_bytes’, ‘imag’, ‘numerator’, ‘real’, ‘to_bytes’]

布尔型

【例子】

a = False
print(a, type(a))
print(dir(int))

False <class ‘bool’>
[‘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’, ‘as_integer_ratio’, ‘bit_length’, ‘conjugate’, ‘denominator’, ‘from_bytes’, ‘imag’, ‘numerator’, ‘real’, ‘to_bytes’]

类型转换

浮点型转整形,丢掉小数位。
【例子】

a = 2.7
print(a, type(a))
b = int(a)
print(b, type(b))
d = float(b)
print(d, type(d))

2.7 <class ‘float’>
2 <class ‘int’>
2.0 <class ‘float’>
对象转换字符串

a = 2.7
print(a, type(a))
c = str(a)
print(c, type(c))
b = '4.5'
b_float = float(b)
print(b_float, type(b_float))

2.7 <class ‘float’>
2.7 <class ‘str’>
4.5 <class ‘float’>

5.print函数

print(self, *args, sep=’ ‘, end=’\n’, file=None)

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

【例子】

print('a',2,'c',4.5)
print('a',2,'c',4.5,sep='')
print("v1",end=',')
print("v2",end=',')

a 2 c 4.5
a2c4.5
v1,v2,

位运算

1. 原码、反码、补码

原码就是值的二进制表示,带符号位
反码就是值的二进制取反,符号位不变
补码,正数补码就是本身,负数的补码是其反码+1
符号位,最高位就是符号位,0是正 1是负

2.按位运算

与(&)、或(|)、非(~)、异或(^)、左移(<<),右移(>>)
【例子】

print(bin(5))
print(bin(4))
print(bin(~4))
print(bin(5 & 4))
print(bin(5 | 4))
print(bin(5 ^ 4))
print(bin(5 << 2))
print(bin(5 >> 2))

0b101
0b100
-0b101
0b100
0b101
0b1
0b10100
0b1

3.位运算实现快速计算

2的倍数
【例子】

n = 6
m = 3
print(n << 1)  # n*2
print(n >> 1)  # n/2
print(n << m)  # n*2^m
print(n >> m)  # n/2^m
print(1 << n)  # 2^n

12
3
48
0
64

快速交换2个整数
【例子】

n = 6
m = 3
n ^= m
m ^= n
n ^= m
print(n)
print(m)

3
6

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

a = 5
print(a & (-a))

1

条件语句

1.if语句

if expression:
    expr_true_suite

expression表达式为真,才会执行
【例子】

if 4 > 3:
    print("4>3")

4>3

2.if-else语句

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

嵌套语句支持
【例子】

if 4 < 3:
    print("4>3")
else:
    if 3 > 2:
        print("3>2")
    print("4<3")

3>2
4<3

3.if -elif-else语句

if expression1:
    expr1_true_suite
elif expression2:
    expr2_true_suite
    .
    .
elif expressionN:
    exprN_true_suite
else:
    expr_false_suite
  • elif 语句即为 else if,用来检查多个表达式是否为真,并在为真时执行特定代码块中的代码。
    【例子】
a = 8
if a < 4:
    print("a<4")
elif a < 7:
    print("a<7")
else:
    print("a>7")

a>7

4.assert关键词

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

【例子】

assert 4>5

AssertionError

循环语句

1. while循环

while语句最基本的形式包括一个位于顶部的布尔表达式,一个或多个属于while代码块的缩进语句。

while 布尔表达式:
    代码块

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

【例子】

a = 10
while a > 0:
    a -= 1
print("result:", a)

result: 0

2.while-else语句

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

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

a = 10
while a > 0:
    a -= 1
else:
    print("result a:", a)
print("complete a")

b = 10
while b > 0:
    b -= 1
    if b == 5:
        break
else:
    print("result b:", a)
print("complete b")

result a: 0
complete a
complete b

3.for循环

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

for 迭代变量 in 可迭代对象:
    代码块

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

【例子】

for item in ['a', 'b', 'c']:
    print(item, end=",")
print()
for item in range(4):
    print(item, end=',')
print()
obj = {a: 'av', b: 'bv'}
for item in obj.items():
    print(item, end=',')
print()
dict_1 = {'name': 'lili', "book": "world"}
for item in dict_1:
    print(item, end=',')

a,b,c,
0,1,2,3,
(0, ‘av’),(5, ‘bv’),
name,book,

4.for-else 循环

for 迭代变量 in 可迭代对象:
    代码块
else:
    代码块

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

range函数

range([start,] stop[, step=1])

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

【例子】

for i in range(2, 5):  # 不包含5
    print(i)

3
4

6.enumerate()函数

enumerate(sequence, [start=0])

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

【例子】

seasons = ['Spring', 'Summer', 'Fall', 'Winter']
lst = list(enumerate(seasons))
print(lst)

[(0, ‘Spring’), (1, ‘Summer’), (2, ‘Fall’), (3, ‘Winter’)]

7.break语句

跳出本层循环

8.continue语句

终止本轮循环,继续下一个循环

9.pass语句

nothing to do啥也不做,占用语句位置,符合语法

10 推导式

[ expr for value in collection [if condition] ]
【例子】

lst=[2,3,6,8,5]
result=[value+1 for value in lst]
print(result)
result=[value+1 for value in lst if value>3]
print(result)

[3, 4, 7, 9, 6]
[7, 9, 6]

异常处理

异常就是运行期检测到的错误。计算机语言针对可能出现的错误定义了异常类型,某种错误引发对应的异常时,异常处理程序将被启动,从而恢复程序的正常运行。

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转换错误导致的异常

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:
    a=2/0
except ZeroDivisionError as e:
    print(e)

division by zero

4.try-except-finally

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

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

try:
    a=2/0
except ZeroDivisionError as e:
    print(e)
finally:
    print("complete")

division by zero
complete

5.try-except-else

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

使用except而不带任何异常类型,这不是一个很好的方式,我们不能通过该程序识别出具体的异常信息,因为它捕获所有的异常。
try: 检测范围 except(Exception1[, Exception2[,…ExceptionN]]]): 发生以上多个异常中的一个,执行这块代码 else: 如果没有异常执行这块代码
【例子】

try:
    a = 2 / 1
except ZeroDivisionError as e:
    print(e)
else:
    print("no error")
finally:
    print("complete")

no error
complete

6.raise语句

主动抛异常
【例子】

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

An exception flew by!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值