> For the complete documentation index, see [llms.txt](https://twinsant.gitbook.io/untitled-1/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://twinsant.gitbook.io/untitled-1/006.while-xun-huan.md).

# 006.while循环

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

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

<figure><img src="https://287028989-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FzFaa4KHjTxY4RdS4enJb%2Fuploads%2FxwnTaX1PIEXOcrPqFVEQ%2Fimage.png?alt=media&amp;token=f90cb80c-be3d-46e2-b237-d35e46d371b0" alt=""><figcaption></figcaption></figure>

## 复习逻辑条件

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

{% hint style="info" %}
问题：not True的值是什么？False and True的值是什么？

回答：请在脑子里运行这两个逻辑表达式，不熟的请看上节课的教程来复习
{% endhint %}

## 折行

有这样一个程序

```python
# 程序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个条件，如果编辑器显示不下我们会想把条件折行输入，这样写会出错

```python
# 程序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的代码块逻辑被打断了

<figure><img src="https://287028989-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FzFaa4KHjTxY4RdS4enJb%2Fuploads%2FRBTSu7viX0BdVx6TeOcK%2Fimage.png?alt=media&amp;token=0618daa0-d587-441e-a575-c2f635a338ff" alt=""><figcaption></figcaption></figure>

要想折行，只需要在代码行最后加上\，告诉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!')
```

## 整数变量

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

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

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

```python
# 程序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程序

```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...')
```

课后作业

{% hint style="info" %}
问题： 修改for循环为while循环

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

{% endhint %}
