语法: 输出a if 表达式b else 输出c
解释:如果表达式b条件为真,就执行输出1,否者执行输出c
实例:
>>> print("1") if 1 < 2 else print("2")
1
>>> print("1等于2") if 1==2 else print("1不等于2")
1不等于2
断言函数
断言函数用来什么某个条件是真的,其作用是测试一个条件是否成立,如果不成立,则抛出异常
先来看看断言函数assert的语法:
语法:
assert condition (expression)
如果condition为false,就抛出一个AssertionError异常
expression为可选参数,可以自定以打印的内容
实例:
>>> a = 1
>>> b = 2
>>> assert a > b
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError
>>> assert a > b,'{} is less than {}'.format(a,b)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError: 1 is less than 2
循环语句
在实际编程中,需要重复的去执行某些代码的时候不必要去书写多次,而是使用循环语句,重复的执行代码块
for 循环语句
在讲之前,先来看下for循环语句的语法
语法:
for 迭代值 in 序列:
代码块
先看下实例,再来理解
items = [2,3,5,6,8,10]
for item in items:
print(item)
运行结果:
-------------------------
2
3
5
6
8
10
i = 1
while i < 10:
i += 1
if i%2 > 0: # 非双数时跳过输出
continue
print(i) # 输出双数2、4、6、8、10
i = 1
while 1: # 循环条件为1必定成立
print(i) # 输出1~10
i += 1
if i > 10: # 当i大于10时跳出循环
break
else语句
在 python 中,while … else 在循环条件为 false 时执行 else 语句块
>>> k = 1
>>> while k < 9:
... print(k)
... k+=1
... else:
... print("循环结束了")
简写语句
类似 if 语句的语法,如果 while 循环体中只有一条语句,可以将该语句与while写在同一行中
>>> while 1<2 : print("1小于2")
可以使用Ctrl+C来中断循环
嵌套循环
用一个九九乘法表的小例子来讲解下什么是嵌套循环?
for i in range(1,10):
for j in range(1,i+1):
# print("{}*{}={} ".format(j,i,i*j),end="")
print("%d*%-2d=%-4d" % (j,i,i*j),end=" ")
print()