一、三元表达式
语法:为真时的结果 if 判断条件 else 为假时的结果(注意,没有冒号)
or 前面的判断不成立,则值取决于后面
a = 5
b = a > 7 or 4
print(b) # 运行结果为4
a = 5
b = a > 3 or 4
print(b) # 运行结果为True
or前面进行了判断是否大于3, 判断就是bool类型
b = 10
a = 7 if b > 10 else 8
print(a) # 运行结果为 8
二、while-else
1.else可以和while连用
i = 1
while i < 5:
print(i, '<5')
if i == 3:
break # break管控范围包含else,break跳出后不运行else语句
i += 1
else:
print(i, '不成立')
运行截图:
三、for 循环嵌套
嵌套循环输出2~100之间的素数
import math
for i in range(2, 100):
a = int(math.sqrt(i))
for j in range(2, a + 1):
if i % j == 0:
break
else:
print(i)
从键盘输入一个整数,判断是否为素数
sushu = int(input('请输入一个数:'))
i = 2
while i < sushu:
if sushu % i == 0:
break
i += 1
if i == sushu:
print('是素数')
else:
print('不是')
转换为while-else结构
sushu = int(input('请输入一个数:'))
i = 2
while i < sushu:
if sushu % i == 0:
print(sushu, '不是')
break
i += 1
else:
print(sushu, '是')
转换为for-else结构
import math
sushu = int(input('输入'))
a = int(math.sqrt(sushu))
for i in range(2, a + 1):
if sushu % a == 0:
print('不是质数')
break
else:
print('是质数')
把2到100的素数存到列表里
import math
b = []
for i in range(2, 100):
a = int(math.sqrt(i))
for j in range(2, a + 1):
if i % j == 0:
break
else:
b.append(i)
print(b)
用while循环嵌套的方式
a = []
i = 2
while i < 100:
j = 2
while j < i:
if i % j == 0:
break
j += 1
else:
a.append(i)
i += 1
print(a)
打印5*5的 *号矩形
j = 1
while j <= 5:
i = 1
while i <= 5:
print('*', end='')
i += 1
print()
j += 1
用for循环嵌套的方式
n range(5):
for j in range(5):
print('*', end='')
print()
i = 0
while i < 5:
j = 0
while j <= i:
print('*', end='')
j += 1
print()
i += 1
for i in range(5):
for j in range(5 - i):
print('*', end='')
print()
for i in range(5):
for j in range(i):
print(' ', end='')
for j in range(5 - i):
print('*', end='')
print()
i = 1
while i <= 5:
j = 1
while j <= i:
print(' ', end='')
j += 1
j = 1
while j <= 6 - i:
print("*", end='')
j += 1
print()
i += 1
for i in range(1, 10):
j = 1
while j <= i:
print(j, '*', i, '=', j * i, end=' ')
j += 1
print()
i += 1
i = 1
while i < 10:
for j in range(1, i + 1):
print(j, '*', i, '=', i * j, end=' ')
print()
i += 1
i = 1
while i <= 5:
j = 1
while j <= 5:
if i == 1 or i == 5 or j == 1 or j == 5:
print('*', end='')
else:
print(' ', end='')
j += 1
print()
i += 1
或者如下:
for i in range(1, 6):
for j in range(1, 6):
if i == 1 or i == 5 or j == 1 or j == 5:
print('*', end='')
else:
print(' ', end='')
print()
```