运算符号
算数运算符:【+】加、【-】减、【*】乘、【/】除、【//】向下取整、【%】取余、【**】指数前缀、
PS:1、运算符的优先级可通过小括号“( )”提高(无中括号,大括号),运算次序基本与数学一致;
2、优先级从高到低:( ) > ** > * / % // > + - ;
3、(2+3)**5 = (3+2)5,2**8 = 28。a ** b,相当于 b 个 a 连乘;
4、在字符串、列列表、元组对象中,【 + 】表示拼接合并,【 * 】表示复制。
赋值运算符:【=】、【+=】、【-=】、【*=】、【/=】、【//=】、【%=】、【**=】
PS:1、与Java类似,除“=”外,其它复合赋值符号的运算,先将符号前的数与符号后的数做等号前边的算术运算,再将结果赋值给符号前边的数,且符号前的必须为变量,不能是数字,否则无法接收返回值。如:c *= a 等价于 c = c * a,c ** = a 等价于 c = c ** a。
2、与Java不同的是,Python中没有自加自减运算符。
比较运算符(结果为bool型):【==】等于、【!=】不等于、【>=】大于等于、【=<】小于等于、【>】大于、【<】小于;
逻辑运算符(结果为bool型):【 and 】逻辑与、【 or 】逻辑或、【 not 】逻辑非;
1、做 and 运算时,只要有⼀个值为0,则结果为0,否则返回最后⼀个非0数字作为结果;
2、做 or 运算时,只有所有值为0结果才为0,否则结果为第⼀个⾮0数字。
print(56-7*(2+3)**2//3) # -2
demo_int = 3
demo_int *= 5
print(demo_int) # 15,, 不能直接将 demo_int*=5 放入括号内
print(0 or 0 or 3 or 5) # 3, or 运算将输入挨个判断是否非零,一旦非零就返回结果
print(0 and 0 and 3 and 5) # 0
print(6 and 2 and 3 and 5) # 6, and运算将输入挨个判断是否是0,是则返回,否则返回与之比较的值
条件分支
概述:Python 中条件分支语句只有一种,即 if 语句,无 switch 语句。具体而言,if 语句分五种:if 单句、if-else语句、if-elif-...-else(多重 if,彼此处于同一级别,缩进一致,功能相当于 switch)、if 嵌套、if三目表达式。
if 三目表达式格式: 结果1 if 条件 else 结果2,即条件在中间,结果在两边。
import random
# 随机数生成,闭区间,前后都包
num = random.randint(0, 5)
""" if 单句 """
if num == 0:
print("这个数是0")
""" if-else 语句 """
if num > 4:
# if-elif-...else 语句开始
if num >= 9:
print("优秀")
elif num >= 8:
print("良好")
elif num >= 7:
print("中等")
elif num >= 6:
print("及格")
else:
print("不及格")
# if-elif-...else 语句结束,作为代码块整体嵌套入if-else语句的if部分
else:
print("这个数小于等于4")
""" if 三目表达式"""
print("这个数大于5") if num > 5 else print("这个数不大于5")
条件循环
概述:Python中循环控制语句有 while 、for 两种,支持嵌套。此外,如Java一般Python中也有全局循环终止语句 break 和当前次循环终止语句 continue,终止的对象都是最外层的循环体。
PS:1、while 接逻辑判断语句,一般用于在未知边界条件的情况下进行迭代;
2、for 通常后接 in,不能跟普通的逻辑判断,一般用于有界变量的遍历,句型为“for e in Es”,类似于 Java 中“for( e : Es)”(或for e not in Es结构),常用于遍历列表、元组、字符串、字典等。
3、尽管 while 和 for 可以转化,但 while 更适用于条件循环,for 更适用于元素遍历。
# while实现99表
j = 1
while j <= 9:
i = 1
while i <= j:
print(f'{i}*{j}={j*i}', end='\t')
i += 1
j += 1
print()
# for实现99表
my_tuple = 1, 2, 3, 4, 5, 6, 7, 8, 9
print(type(my_tuple))
for e in my_tuple:
for t in my_tuple:
if e >= t :
print(f'{t}*{e}={t*e}', end='\t')
t += 1
else:
continue
print()
# break使用
str1 = 'itheima'
flag = True # 标志变量
for i in str1:
if i != 'e':
print(i)
else:
print('遇到e不打印')
flag = False # 循环被中断,修改标志变量的值
break # e和e之后的不再打印
if flag:
print('循环正常结束之后执行的代码')
# continue 使用
my_int = 1
while my_int < 10:
if my_int % 3 == 0:
print("3的倍数不打印")
my_int += 1
continue # 中断本次,继续下一次
else:
print(my_int)
my_int += 1