参考:
-
《简明python教程》
Note:
- 更多连载请查看【python】
文章目录
1 复合赋值语句
1.1 多变量同时赋值
在Python中,可以使用一次赋值符号,给多个变量同时赋值:
1.2 变量交换
非常方便,不用中间变量
age_1 = 'male'#转换性别
age_2 = 'female'
age_1,age_2 = age_2,age_1#age_1,age_2 = age_2,age_1这种操作是Python独有的,不用第三者temp
print(age_1,age_2)
输出为
female male
1.3 复合赋值
如下,+=,-=,*=,=, **=,%=
age = 25
age += 2
print (age)#27
age -=3
print (age)#24
age *= 2
print (age)#48
age /= 4
print (age)#12
age **= 2
print (age)#144
age %= 5
print (age)#4
输出为
27
24
48
12.0
144.0
4.0
2 顺序
从上到下,顺序执行
import calendar
year = int(input('请输入年份:')) #输出指定某年的日历
tab = calendar.calendar(year)
print(tab)
输入年份(我输入的是2017),结果如下
3 分支
3.1 if 语句
可以通过判断条件是否成立来决定是否执行某个语句;
3.2 if-else 语句
就是在原有的if成立执行操作的基础上,当不成立的时候,也执行另一种操作;
3.2.1补充:丰富的else
else 除了和if搭配实现要么怎样,要么不怎样外,还可以和 while(干完了能怎样,干不完就别想怎样),except 搭配(没有问题,那就干吧)
num = int(input("请输入一个整数"))
while(num):
if num>=5:
print("输入的数大于等于5")
break
num-=1
else:
print("输入的数小于5")
例如输入6,结果为
请输入一个整数6
输入的数大于等于5
try:
1+'1'
except TypeError as reason:
print("error")
else:
print('no error')
try:
1+1
except TypeError as reason:
print("error")
else:
print('no error')
结果为:
error
no error
3.3 if-elif-else 语句
这种语句是处理可能有多种情况的判断。
ans = int(input('请输入你的身高:'))
if ans < 180:
print('一般身高')
elif 180 <= ans < 185:
print('王子身高')
elif 185 <= ans < 190:
print('男神身高')
else:
print('巨人身高')
输入身高后,结果为
请输入你的身高:172
一般身高
3.4 分支语句嵌套
if中还有if
gender = input('请输入你的性别(M或者F):')
age = int(input('请输入你的年龄(1-130):'))
if gender == 'M':
if age >= 22:
print('你已经达到合法结婚年龄,有对象了没?\n没有?男的也行啊!还不去相亲?!!')
else:
print('你还是个可爱的男孩子')
else:
if age >= 20:
print('你已经达到合法结婚年龄,有男票了没?\n没有?还不去相亲?!!')
else:
print('你还是个美腻的女孩子')
按提示输入后,结果为:
请输入你的性别(M或者F):M
请输入你的年龄(1-130):24
你已经达到合法结婚年龄,有对象了没?
没有?男的也行啊!还不去相亲?!!
3.5 条件表达式三元操作符
Note: 在条件语句中(if,while)
None、False、0、‘’、“”、()、{}、[]**都当作False
while None:
print('进入循环')
print('退出循环')
结果为
退出循环
4 循环
4.1 while
count = 1
sum = 0
while count < 11:
sum = sum + count
print('sum = %d,count = %d'%(sum,count))
count += 1
结果为
sum = 1,count = 1
sum = 3,count = 2
sum = 6,count = 3
sum = 10,count = 4
sum = 15,count = 5
sum = 21,count = 6
sum = 28,count = 7
sum = 36,count = 8
sum = 45,count = 9
sum = 55,count = 10
while 可以与 else 搭配
while 条件:
语句
else:
语句
Q:下面的例子中,循环中的 break 语句会跳过 else 语句吗?
while 条件:
语句
break
else:
语句
会,因为如果将 else 语句与循环语句(while 和 for 语句)进行搭配,那么只有在循环正常执行完成后才会执行 else 语句块的内容。
4.2 for
for 循环变量 in 对象:
循环语句
对象可以是字符串,列表,元组,字典等
for i in range(0,10,2):
print(i)
结果为:
0
2
4
6
8
说明下range的使用
打印乘法口诀表
for i in range(1,10):
for j in range(1,i+1):
q = i*j
print('i*j = %d '%q,end='')
print('\n')
结果为:
i*j = 1
i*j = 2 i*j = 4
i*j = 3 i*j = 6 i*j = 9
i*j = 4 i*j = 8 i*j = 12 i*j = 16
i*j = 5 i*j = 10 i*j = 15 i*j = 20 i*j = 25
i*j = 6 i*j = 12 i*j = 18 i*j = 24 i*j = 30 i*j = 36
i*j = 7 i*j = 14 i*j = 21 i*j = 28 i*j = 35 i*j = 42 i*j = 49
i*j = 8 i*j = 16 i*j = 24 i*j = 32 i*j = 40 i*j = 48 i*j = 56 i*j = 64
i*j = 9 i*j = 18 i*j = 27 i*j = 36 i*j = 45 i*j = 54 i*j = 63 i*j = 72 i*j = 81
A = [1,2,3,4,5]
B = ['LJR','WL','MYH','LCL','WD']
for i,j in zip(A,B):
print (i,j)
结果为
1 LJR
2 WL
3 MYH
4 LCL
5 WD
for … else …
来面来看下比较冷门的 for 和 else 搭配
for case in "Bryant":
print(case)
else:
print("All words have been printed!\n")
output
B
r
y
a
n
t
All words have been printed!
可以看到 else 会在 for 执行结束后运行
1)for break else
for case in "Bryant":
print(case)
break
else:
print("All words have been printed!\n")
output
B
for 被中途 break 了, 则程序不会进入 else 分支
2)for continue else
for case in "Bryant":
print(case)
continue
else:
print("All words have been printed!\n")
output
B
r
y
a
n
t
All words have been printed!
可以看出 else 不受 continue 的影响
4.3 循环中断
4.3.1 break
结束本次循环,跳出所在的循环
i = 0
while 1:
print('这是第%d次循环'%i)
i += 1
if i >5:
break
结果为:
这是第0次循环
这是第1次循环
这是第2次循环
这是第3次循环
这是第4次循环
这是第5次循环
4.3.2 continue
结束本次循环,继续进行下一次循环
for i in range(0,5):
num = int(input('请输入你本次抓娃娃需要多少秒(1~60秒):'))
if num > 30:
print('时间到啦,机器自动给你抓了!')
continue
print('你本次用了%d秒抓了一下'%num)
结果为
请输入你本次抓娃娃需要多少秒(1~60秒):1
你本次用了1秒抓了一下
请输入你本次抓娃娃需要多少秒(1~60秒):2
你本次用了2秒抓了一下
请输入你本次抓娃娃需要多少秒(1~60秒):31
时间到啦,机器自动给你抓了!
请输入你本次抓娃娃需要多少秒(1~60秒):32
时间到啦,机器自动给你抓了!
请输入你本次抓娃娃需要多少秒(1~60秒):33
时间到啦,机器自动给你抓了!
4.3.3 assert
assert这个关键字我们称之为“断言”,当这个关键字后边的条件为假的时候,程序自动崩溃并抛出 AssertionError
的异常。
一般来说我们可以用Ta再程序中置入检查点,当需要确保程序中的某个条件一定为真才能让程序正常工作的话,assert关键字就非常有用了。
assert 3>4
结果如下
---------------------------------------------------------------------------
AssertionError Traceback (most recent call last)
<ipython-input-8-020d57da1a31> in <module>()
----> 1 assert 3>4
AssertionError:
再看看如下一个例子,来加深对 break,continue 的印象
1)break
while True:
a = input("please input a number:")
if a == '1':
break
else:
pass
print('still in while')
print("not in while")
先输入 2,再输入1
please input a number:2
still in while
please input a number:1
not in while
符合 break 条件后,会直接结束循环,不执行 else 后面的语句
2)continue
while True:
a = input("please input a number:")
if a == '1':
continue
else:
pass
print('still in while')
print("not in while")
先输入2,再一直输入1
please input a number:2
still in while
please input a number:1
please input a number:1
please input a number:1
……
符合 continue 条件后不会执行 else 后面的代码,而会直接进入下一次循环。
3)True and False
a = True
while a:
b = input("please input a number:")
if b == '1':
a = False
else:
pass
print('still in while')
print("not in while")
会执行 else 后面的代码,然后再退出。
补充
python 的 … 也可以代替 pass,python 无处不对象
附录
if 多个条件同时判断
if 包含多个条件,全部满足
math_points = 51
biology_points = 78
physics_points = 56
history_points = 72
my_conditions = [math_points > 50, biology_points > 50,
physics_points > 50, history_points > 50]
if all(my_conditions):
print("Congratulations! You have passed all of the exams.")
else:
print("I am sorry, but it seems that you have to repeat at least one exam.")
# Congratulations! You have passed all of the exams.
if 包含多个条件,任意一个满足
math_points = 51
biology_points = 49
physics_points = 48
history_points = 47
my_conditions = [math_points > 50, biology_points > 50,
physics_points > 50, history_points > 50]
if any(my_conditions):
print("Congratulations! You have passed all of the exams.")
else:
print("I am sorry, but it seems that you have to repeat at least one exam.")
# Congratulations! You have passed all of the exams.
为什么没有 do-while
最后还有一点,在汇编层面,do-while 比 while 更接近汇编语言的逻辑,可以节省使用指令,在过去的低内存时代,算得上是一种优化写法
python 不需要引入新的关键字和语法,仅使用现有语法就能很好地实现同样的功能:
while True:
<setup code>
if not <condition>:
break
<loop body>
do-while 能够解决的几个问题要么在 Python 中并不存在(宏定义、汇编指令),要么就是已经有更为合适而低成本的实现(跳转控制)。
Note: 更多连载请查看【python】