Python学习笔记:条件语句和循环语句

1 条件语句

1.1 布尔值

在Python中,标准值False和None、各种类型(包括浮点数、复数等)的数值0、空序列(如空格字符串""、空元祖()和数组[])以及空映射(如空字典{})都被视为假,而其他值都被视为真。

1.1 if语句

if True:
    print('It is true')

执行后:

It is true

这就是if语句,能够有条件的执行代码。这意味着如果条件(if和冒号中的表达式)为真,就执行后续代码块,如果条件为假,就不执行。

1.2 else语句

if 0:
    print('It is true')
else:
	print('It is false')

执行后:

It is false

在这个示例中,如果条件为假,就执行第二个代码块

1.3 elif语句

要检查多个条件,可使用elif。elif是else if的缩写,由一个if子句和一个else子句组合而成,也就是包含条件的else子句。

num = 0
if num > 0:
    print('the number is positive')
elif num < 0:
	print('the number is negative')
else:
	print('the nubmer is zero')

1.4 代码块嵌套

也可将if语句放在其他if语句中

num = 886
if num > 0:
	if num == 886:
		print('wa, 886')
	else:
		print('the number is positive')
elif num < 0:
	print('the number is negative')
else:
	print('the nubmer is zero')

执行后:

wa, 886

1.5 更复杂的条件

1.5.1 比较运算符

表达式 描述
x == y x等于y
x < y x小于y
x > y x大于y
x >= y x大于或等于y
x <= y x小于或等于y
x != y x不等于y
x is y x和y是同一个对象
x is not y x和y是不同的对象
x in y x是容器(如序列)y的成员
x not in y x不是容器(如序列)y的成员

1.5.2 逻辑运算符

表达式 描述
and 且:接收两值,并且两值均为真时,才返回真
or 或:接收两值,如果任意值为真时,就返回真
not 非:反向取值
num = 886
if num > 0 and num < 1000:
	print('wa, 886')

执行后:

wa, 886

1.6 断言

如果知道必须满足特定条件,程序才能正确地运行,可在程序中添加assert语句充当检查点

>>> age = -1
>>> assert age < 0
>>> assert 0 < age < 100
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AssertionError

2 循环

2.1 while循环

while语句非常灵活,可用于在条件为真时,反复执行代码块。
示例:打印1~10的整数:

x = 1
while x <= 10:
	print(x)
	x += 1

2.2 for循环

如果想根据需要进行定制,比如序列中每个元素执行代码块,可以使用for语句来实现。
示例:打印0~9的整数:

for number in range(0, 10):
	print(number)

Python提供了一个创建范围的内置函数 range(x, y),范围类似切片,包含起始位置x,但不包含结束位置y

2.3 迭代字典

要遍历字典的所有关键字,可像遍历序列一样使用普通的for语句。

d = {'x' : 1, 'y' : 2, 'z' : 3}
for key in d:
	print(key, ' : ' ,d[key])

也可以使用keys等字典方法来获取所有的键。如果只想获取值,可使用d.values。

d = {'x' : 1, 'y' : 2, 'z' : 3}
for key, value in d.items():
	print(key, ' : ' , value)

2.3 跳出循环

2.3.1 break

要结束/跳出循环,可使用break。
示例:假设要找出小于10的最大平方值,可从10开始向下迭代,找到一个平方值后,无须再迭代,直接跳出循环:

from math import sqrt
for n in range(9, 0, -1):
	root = sqrt(n)
	print(n)
	if root == int(root):
		print("num is " + str(n))
		break	

执行后:

>>>9
   num is 9

2.3.2 continue

语句continue没有break用的多。它结束当前迭代,并跳到下一次迭代开头,意味着跳过循环体余下的语句,但不结束循环。
拿2.3.1的示例举例:

from math import sqrt
for n in range(9, 0, -1):
	root = sqrt(n)
	print(n)
	if root == int(root):
		print("num is " + str(n))
		continue	

执行后:

>>>9
>>>num is 9
发布了102 篇原创文章 · 获赞 6 · 访问量 9万+

猜你喜欢

转载自blog.csdn.net/tt75281920/article/details/105164804