表达式
- 什么是表达式?
表达式是运算符和操作数所构成的序列。
- 表达式的优先级:
表达式的优先级其实就是运算符的优先级所决定的。
序号 | 运算符 | 描述 |
---|---|---|
1 | ** | 指数(次幂)运算 |
2 | ~ + - | 补码,一元加减(最后两个的方法名称是+@ 和-@ ) |
3 | * / % // | 乘法,除法,模数和地板除 |
4 | + - | - |
5 | >> << | 向右和向左位移 |
6 | & | 按位与 |
7 | ^ | | 按位异或和常规的“OR ” |
8 | <= < > >= | 比较运算符 |
9 | <> == != | 等于运算符 |
10 | = %= /= //= -= += *= **= | 赋值运算符 |
11 | is is not | 身份运算符 |
12 | in not in | 成员运算符 |
13 | not or and | 逻辑运算符 |
不过请注意,上表中同一类运算符没有区分优先级。
>>> 1 or 2 and 3
1
>>> not 1 and 2 and 3
False
>>> not 0 and 2 and 3
3
可以看到,对于逻辑运算符,优先级 not
> and
> or
。
一般建议使用()
来指定运算优先级,保证运算不会出错,且易于阅读。
if条件判断
Python通过if-elif-else
语句来进行条件判断。
if
后面条件的结果是布尔值。当if
条件为真时执行if
下面的语句;当if
为假时执行else
下面的语句;elif
与if
类似,等同于else if
。
- 格式:
if condition1:
pass
elif condition2:
pass
elif condition3:
pass
else:
pass
pass
是Python中的空语句/占位语句。
- 示例:
ACCOUNT = 'qiyue'
PASSWORD = '123456'
print('please input your account')
user_account = input()
print('please input your password')
user_password = input()
if ACCOUNT == user_account and PASSWORD == user_password:
print('successed')
else:
print('failed')
Python中没有专门定义常量的方式,通常使用大写变量名表示。Python中的常量并不是传统意义上的常量。
在VSCode中,我们可以使用snippet(片段)来帮助我们提高效率。
if可以单独使用,但elif、else必须与if结合使用。每个if都是一个代码块,同一个代码块的代码会依次执行,缩进一致。
while循环
Python通过while-else
语句来进行循环。
while
后面条件的结果也是布尔值。当while
条件为真时执行while
下面的语句;当while
条件为假时执行else
下面的语句。
- 格式:
while expression:
pass
else:
pass
- 示例:
i,sum = 1,0
while i <= 100:
sum += i
i += 1
else:
print(sum)
while很容易造成死循环,因此while的条件必须是有限的,不能是常量。
while循环通常使用在递归中。
for循环
Python还通过for-else
语句来进行循环。
for
后面条件的结果也是布尔值。当for
条件为真时执行for
下面的语句;当for
条件为假时执行else
下面的语句。
- 格式:
for target_list in expression_list:
pass
else:
pass
- 示例:
fruit = [['apple', 'orange', 'banana', 'grape'],('watermelon', 'strawberry', 'cherry')]
for x in fruit:
for y in x:
print(y, end=' ')
else:
print('\nThis is all fruit.')
可以看到,当for遍历完所有元素之后,执行else下面的语句。或者说当for循环是正常结束的时候,都会执行else下面的语句。对于print,print(y)
默认等于print(y, end='\n')
,如果想要print的结果在一行显示,可以使用print(y, end=' ')
。
for循环通常用来遍历序列、集合或字典。
退出循环
Python使用continue
和break
来退出循环。
continue会跳过本次循环,但后面的循环仍会进行。continue是让循环正常结束。
break会终止本次循环,并且后面的循环都不会再执行。break是让循环非正常结束。
range()
函数
Python中使用range()
函数来表示重复次数的循环。range()
函数的结果是列表,遵循“左包右不包”的原则。
如range(0,10)
就相当于其他语言中的for(i=0; i<10; i++)
。
for x in range(0,10):
print(x, end=' ')
0 1 2 3 4 5 6 7 8 9 #结果
range()
函数的步长(间隔)默认是1,也可以额外指定步长。
for x in range(0,100,5):
print(x, end=' ')
0 5 10 15 20 25 30 35 40 45 50 55 60 65 70 75 80 85 90 95 #结果
步长也可以是负数,这样就相当于是等差的递减数列。
for x in range(100,0,-10):
print(x, end=' ')
100 90 80 70 60 50 40 30 20 10 #结果
此外,对于序列的切片也可以指定步长,用法与range()
相似。