> For the complete documentation index, see [llms.txt](https://notes.tzpro.xyz/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://notes.tzpro.xyz/kif-notes/lab_sheet_9_zh-hans.md).

# lab\_sheet\_9\_zh-hans

{% tabs %}
{% tab title="Chief Author" %}
![](https://avatars.githubusercontent.com/u/60097976?s=400\&u=46206cff80830b3e6e2d04154b9c75a0a156c056\&v=4)

**Binary-Yuki**

> Empowering my own dreams in coding.

&#x20;[![](https://camo.githubusercontent.com/af694da70ebb0f12c9c7dad8899298d2a2c38df8320e46f98610031c3dde2d6c/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f73746172732f6c6f62656875623f636f6c6f723d666663623437266c6162656c436f6c6f723d626c61636b267374796c653d666c61742d737175617265266c6f676f3d676974687562)](https://github.com/lobehub)
{% endtab %}

{% tab title="Author" %}
![](https://avatars.githubusercontent.com/u/146884379?v=4)

**UniDesiranCX**

.
{% endtab %}
{% endtabs %}

## lab9

Python 编程中 while 语句用于循环执行程序 即在某条件下 循环执行某段程序 以处理需要重复处理的相同任务 其基本形式为：

```
while 判断条件(condition)：
    执行语句(statements)……
```

执行语句可以是单个语句或语句块 判断条件可以是任何表达式 任何非零、或非空（null）的值均为true

当判断条件假 false 时 循环结束

**1.Write a while-loop that prints**

**(a) All squares less than `n`. For example, if `n` is `100`, print `0 1 4 9 16 25 36 49 64 81`.** **(b) All positive numbers that are divisible by 10 and less than n. For example, if `n` is `100`, print `10 20 30 40 50 60 70 80 90` (c) All powers of two less than `n`. For example, if `n` is `50`, print `1 2 4 8 16 32 2`**

(a) 打印小于n的所有平方数:

解题思路：

初始化一个变量i为0 （因为0的平方仍为0 所以从0开始） 使用while循环 在循环中 首先判断i\*i是否小于n 如果是 就打印出i的平方 然后i自增1 为下一次循环做准备 如果不是 则结束循环

代码实现：

```python
n = 100
i = 0
while i * i < n:
    print(i * i)
    i += 1
```

(b) 打印所有可以被10整除且小于n的正整数:

解题思路：

* 初始化一个变量i为10 （因为10是最小的能被10整除的正数 所以从10开始）
* 使用while循环
* 在循环中 首先判断i是否小于n
* * 如果是 就打印出i
  * 然后i加10 为下一次循环做准备
  * 如果不是 则结束循环

代码实现：

```python
n = 100
i = 10
while i < n:
    print(i)
    i += 10
```

(c) 打印小于n的所有2的幂:

解题思路：

* 初始化一个变量i为1 （因为2的0次方为1 所以从1开始）
* 使用while循环
* 在循环中 首先判断i是否小于n
* 如果是 就打印出i
* 然后i乘以2 为下一次循环做准备
* 如果不是 则结束循环

代码实现：

```python
n = 50
i = 1
while i < n:
    print(i)
    i *= 2
```

All in one函数化写法

```python
# Write a while-loop that prints
# (a) All squares less than n. For example, if n is 100, print 0 1 4 9 16 25 36 49 64 81.
# (b) All positive numbers that are divisible by 10 and less than n. For example, if n is
# 100, print 10 20 30 40 50 60 70 80 90
# (c) All powers of two less than n. For example, if n is 50, print 1 2 4 8 16 32


# a)
def solution_a(n):
    """
    n --> int
    :param n:
    :return:
    """
    n = 100
    i = 0

    while i ** 2 < n:
        print(i ** 2, end=' ')
        i += 1


solution_a(100)
print("\n")


# b)
def solution_b(n):
    """
    n --> int
    :param n:
    :return:
    """
    n = 100
    i = 10

    while i < n:
        if i % 10 == 0:
            print(i, end=' ')
        i += 10


solution_b(100)

print("\n")


def solution_c(n):
    """
    n --> int
    :param n:
    :return:
    """
    i = 1

    while i < n:
        print(i, end=' ')
        i *= 2


solution_c(50)

```

**2. Write a while-loop that computes**

\*\*(a) The sum of all square numbers between integers a and b (inclusive). For example, `if a = 1 and b = 10`, then the sum is 14. \*\* **(b) The sum of all odd numbers between integers a and b (inclusive). For example, if `a = 1 and b = 10`, then the sum is 25. (c) The sum of all odd digits in integer n. For example, if `n` is `32677`, then the `sum` is `17`**

(a) 计算在整数a和b（含）之间的所有平方数的和

解题思路：

* 初始化一个变量sum为0 （用来储存所有平方数的和）
* 使用while循环 用变量i遍历a到b的所有整数
* 在循环中 首先判断i的平方是否在a和b之间（包括a和b）
* 如果是 sum加上这个平方数
* 然后i自增1 为下一次循环做准备
* 如果不是 跳过该轮循环 继续下一轮
* 循环结束后 打印出sum

代码实现：

```python
a = 1
b = 10
sum = 0
i = a
while i * i <= b:
    if i * i >= a:
        sum += i * i
    i += 1
print(sum)
```

(b) 计算在整数a和b（含）之间的所有奇数之和

解题思路：

* 初始化一个变量sum为0 （用来储存所有奇数之和）
* 使用while循环 用变量i遍历a到b的所有整数
* 在循环中 首先判断i是否是奇数 可以通过i对2的余数是否为1来判断
* 如果是 sum加上这个奇数
* 然后i自增1 为下一次循环做准备
* 循环结束后 打印出sum

代码实现：

```python
a = 1
b = 10
sum = 0
i = a
while i <= b:
    if i % 2 == 1:
        sum += i
    i += 1
print(sum)
```

(c) 计算整数n中所有奇数位数的和

解题思路：

* 初始化一个变量sum为0 （用来储存所有奇数位数之和）
* 使用while循环 直到n减为0
* 在循环中 首先通过n对10取余数得到n的最右侧的一位（这就是n的一位数字）
* 然后判断这一位数字是否是奇数 如果是 就把这一位数字加到sum中
* 然后将n除以10 丢弃最右侧的一位
* 循环结束后 打印出sum

代码实现：

```python
n = 32677
sum = 0
while n != 0: # 当n不等于0的时候
    digit = n % 10
    if digit % 2 == 1:
        sum += digit
    n //= 10
print(sum)
```

All in one函数式写法

```python
# Write a while-loop that computes
# (a) The sum of all square numbers between integers a and b (inclusive). For example,
# if a = 1 and b = 10, then the sum is 14.
# (b) The sum of all odd numbers between integers a and b (inclusive). For example, if
# a = 1 and b = 10, then the sum is 25.
# (c) The sum of all odd digits in integer n. For example, if n is 32677, then the sum is
# 17
from math import sqrt


# a)
def solution_a(a, b):
    """
    a, b --> int
    :param a:
    :param b:
    :return:
    """
    i = a
    total = 0
    while i <= b:
        if int(i ** 0.5) ** 2 == i:
            total += i
        i += 1
    return total


# b)
def solution_b(a, b):
    i = a
    total = 0
    while i <= b:
        if i % 2 != 0:
            total += i
        i += 1
    return total


def solution_c(n):
    """
    n --> int
    :param n:
    :return:
    """
    total = 0
    while n:
        digit = n % 10
        if digit % 2 != 0:
            total += digit
        n = n // 10
    return total


if __name__ == '__main__':
    a = 1
    b = 10
    n = 32677
    print(solution_a(a, b))
    print(solution_b(a, b))
    print(solution_c(n))

```

**3.Write a program that asks the user to enter a string of letters and the program prints the indices of all capital letters.**

**For example,** **Enter text:** **`PROGRAM`**

`>>>` **0 1 2 3 4 5 6** **Enter text:** **`JEffery`** `>>>`**0 1**

解题思路：

程序需要用户输入一个字符串 由于大写和小写字母的ASCII码不同 可以使用该特性来判断一个字母是否为大写\
遍历该字符串 获取其每一个字符及其对应的索引\
检查该字符是否为大写字母 可以通过调用str.isupper()方法实现 传入一个字符串 如果这个字符串全为大写字母 返回True 否则返回 False\
如果是大写字母 打印其索引 否则继续检查下一个字符

代码实现：

while循环：

```python
# 获取用户输入
text = input("Enter text: ")

# 初始化一个变量 i 为 0（这将作为字符串中字符的索引）
i = 0
# 创建一个 while 循环  当 i 小于字符串的长度时执行
while i < len(text):
    # 检查当前字符是否大写  如果是大写就打印其索引
    if text[i].isupper():
        print(i, end=' ')
    i += 1  # 累加 i 为下一次循环做准备
```

解析：

* `while i < len(text)`：这是一个while循环 用于遍历字符 判断条件是i（字符的索引）小于字符串的长度 初始化为0 每次循环i加1 直到遍历完所有字符
* `if text[i].isupper()`：使用字符串的isupper()方法 判断当前字符text\[i]是否为大写字母 如果是 则将条件判断为True 执行下一行代码
* `print(i, end=' ')`：打印出大写字母的索引 并且不换行 而是在其后添加一个空格 这是因为 print函数默认在打印完之后会换行 通过设置end参数为一个空格 把默认的换行符改成了空格 实现了在一行内打印所有数据 - i += 1：最后将索引 i 增加 1 以便于在下次循环中检查下一个字符

For循环版本：

```python
# 获取用户输入
text = input("Enter text: ")

# 遍历文本
for i in range(len(text)):
    if text[i].isupper():  # 如果字符是大写字母
        print(i, end=' ')  # 打印索引
```

代码解析：

* `text = input("Enter text: ")`：获取用户的输入字符串
* `for i in range(len(text))`：这是一个for循环 用于遍历文本 i表示字符的索引 初始化为0 每次循环i加1 直到遍历完所有字符
* `if text[i].isupper()`:：使用字符串的isupper()方法 判断当前字符text\[i]是否为大写字母 如果是 则将条件判断为True 执行下一行代码
* `print(i, end=' ')`：打印出大写字母的索引 并且不换行 而是在其后添加一个空格 这是因为 print函数默认在打印完之后会换行 通过设置end参数为一个空格 把默认的换行符改成了空格 实现了在一行内打印所有数据

4. Write a program that prints a Celsius/Fahrenheit conversion table such as the following:

| Celsius | Fahrenheit |
| ------- | ---------- |
| 0       | 32         |
| 10      | 50         |
| 20      | 68         |
| ...     | ...        |
| 100     | 212        |

The output should be formatted as shown in the example. Lastly, use the equation below to convert Celsius to Fahrenheit:

$F = \frac{9}{5}C + 32$

解题思路:

* 首先初始化摄氏度值为0
* 然后使用一个while循环 只要摄氏度值小于等于100 就进行循环
* 在循环中 计算对应的华氏度值并打印出来
* 然后将摄氏度增加10 为下一次循环做准备

代码实现：

```python
# 打印表头
print('Celsius | Fahrenheit')
print('---------------------')

# 初始化摄氏度值
celsius = 0

# 使用while循环生成转换表
while celsius <= 100:
    # 计算华氏度值
    fahrenheit = celsius * 9 / 5 + 32
    # 打印摄氏度和华氏度值
    print(f'{celsius}      | {fahrenheit}')
    # 更新摄氏度值  增量为10
    celsius += 10
```

All in one函数式写法

```python
def solution_a():
    print("Celsius | Fahrenheit")
    print("--------------------")
    for c in range(0, 101, 10):
        f = (c * 9 / 5) + 32
        print(f"{c:7} | {f}")  # c:7 的意思是占7个字符的位置  不够的用空格补齐


solution_a()
```

**An increasing diabolical number is a number whose digits, from left to right, are never less than the previous digit. A decreasing diabolical number is the opposite, the digits are never greater than the previous digit.**

**For example, 1111, 123456 and 125788999 are increasing diabolical numbers and 1111, 654321 and 999888752 are decreasing diabolical numbers.**  **Write a program that asks the user to enter an integer, n, and prints whether the number is increasing or decreasing. If it’s neither, print neutral. Enter n: 479 increasing diabolical Note: single digit numbers are neutral.**

解题思路是

* 从用户那里获取输入的数值
* 创建两个标志变量（increasing和decreasing） 用来标识当前的数列是否属于上升、下降或者中立
* 遍历输入的每个数字 取出当前数字及其前一个数字进行比较 以确定当前的数列趋势
* 根据当前数字和前一个数字的大小关系 来确定是上升、下降还是中立 并修改对应的标志变量
* 根据这两个标志变量的值 来确定并输出数列的最终趋势

代码实现：

```python
# 获取用户输入
n = input("Enter n: ")

# 初始化递增和递减标记
increasing = True
decreasing = True

# 遍历输入的每个数字
for i in range(1, len(n)):
    # 如果当前数字小于前一个数字  则非递增
    if n[i] < n[i - 1]:
        increasing = False
    # 如果当前数字大于前一个数字  则非递减
    elif n[i] > n[i - 1]:
        decreasing = False

# 根据递增和递减标记判断数列趋势
if increasing:
    print('increasing diabolical')
elif decreasing:
    print('decreasing diabolical')
else:
    print('neutral')
```

代码解析：

* `n = input("Enter n: ")`：这行代码从用户那里获取输入值\
  increasing 和 decreasing：这两个是标志位 用来标识当前的数列是递增还是递减 一开始假设它们都为真
* `for i in range(1, len(n))`：这是一个for循环 用于遍历输入的每个数字 从第二个数字开始（索引为1） 因为需要比较当前数字和前一个数字
* `if n[i] < n[i - 1]`：这个条件判断当前的数字是否小于前一个数字 如果是 则非递增 设置increasing为False
* `elif n[i] > n[i - 1]`：这个条件判断当前的数字是否大于前一个数字 如果是 则非递减 设置decreasing为False
* 最后的if-else语句 基于increasing和decreasing的值来决定是打印出'increasing diabolical' 'decreasing diabolical'还是'neutral'

最后一问要用到for循环 列表以及格式符 仅提供解法

```python
week_days = ["Su", "M", "T", "W", "Th", "F", "Sa"]
start_day = input("Start day: ")
last_date = int(input("Last date: "))

day_index = week_days.index(start_day)

# 打印星期表头并对齐
# print the header of the week days and align them
for day in week_days:
    print("{0:<3}".format(day), end="")
print()

# 对于每一个空白的天数, 打印空格
# print the blank spaces for the first day
for i in range(day_index):
    print("   ", end="")


# 对于每一个日期，按照规定的格式打印，每7天换行
# print the dates and change line every 7 days
day_count = 1
num_day = day_index
while day_count <= last_date:
    # 打印日期，并对齐到第一个字符
    # print the date and align it to the first character
    print("{0:<3}".format(day_count), end="")
    day_count += 1
    num_day += 1
    # 每7天换行
    # change line every 7 days
    if num_day % 7 == 0:
        print()

```
