006.while循环

山无陵,江水为竭,冬雷震震,夏雨雪, 天地合,乃敢与君绝!

《上邪》是我国汉代一首著名的乐府诗歌,它是一个痴情的女子对爱情的忠贞表白。

复习逻辑条件

这节课需要同学们先复习not和and

问题:not True的值是什么?False and True的值是什么?

回答:请在脑子里运行这两个逻辑表达式,不熟的请看上节课的教程来复习

折行

有这样一个程序

# 程序006.01
cond1 = True
cond2 = True
cond3 = True
cond4 = True
cond5 = True
cond6 = True
if cond1 and cond2 and cond3 and cond4 and cond5:
    print('Bam!')

if有5个条件,如果编辑器显示不下我们会想把条件折行输入,这样写会出错

# 程序006.02
cond1 = True
cond2 = True
cond3 = True
cond4 = True
cond5 = True
cond6 = True
if cond1 and cond2 and cond3 and cond4 
    and cond5:
    print('Bam!')

因为Python的代码块逻辑被打断了

要想折行,只需要在代码行最后加上\,告诉Python下一行续写这一行的代码

# 程序006.03
cond1 = True
cond2 = True
cond3 = True
cond4 = True
cond5 = True
cond6 = True
if cond1 and cond2 and cond3 and cond4 \
    and cond5: # 这样写等价于程序006.01
    print('Bam!')

整数变量

前面我们介绍了字符串变量,现在我们再介绍下整数变量

i = 1 # 我是一个整数变量

顾名思义,整数变量就是存放整数的容器,在这个变量上,我们可以做各种算数操作

# 程序006.04
i = 1
print(i) # 打印1

i = i + 1 # 还有一个简化写法是 i += 1
print(i) # 打印2

i = i - 1 # 还有一个简化写法是 i -= 1
print(i) # 打印1

print(i < 2) # 打印True

让我们把这首情诗改成完整的Python程序

# 程序006.05
mountain_without_peaks = False
river_runs_dry = False
winter_thunder_rolls = False
summer_rain_turns_to_snow = False
heaven_earth_merged = False
life = 18

while not mountain_without_peaks and not river_runs_dry and not winter_thunder_rolls\
    and not summer_rain_turns_to_snow and not heaven_earth_merged and life < 100:
    print(f'{life} years old: I love you!')
    life += 1
print('I love you forever...')

课后作业

问题: 修改for循环为while循环

for i in range(10, 0, -1):
    print(i)

Last updated