• 1
    数据输入输出
    • 任务
  • 2
    条件语句
    • 任务
  • 3
    for循环
    • 任务
  • 4
    字符串
    • 任务
  • 5
    while循环
    • 任务
  • 6
    列表
    • 任务
  • 7
    二维数组
    • 任务
  • 8
    字典
    • 任务
  • 9
    集合
    • 任务
  • 10
    函数与递归
    • 任务
  • к

课程 5. While cycle

难度:

任务«数字迷宫»

💻 Python

欢迎来到数学电视节目《数字迷宫》!规则很简单:主持人说出一个自然数,参与者需要找出这个数的最大约数,且该约数严格小于这个数本身。例如,对于数字100,这样的约数是50;而对于质数13,这样的约数则是1。

你是一名程序员,被要求为这个节目创建一个“电子专家”。你的程序应当向用户请求一个数字,找出所需的约数,并将结果显示在屏幕上。

输入格式

我们正在寻找其约数(整数)的自然数。

输出格式

一个数的最大约数,即小于该数本身的最大整数约数。

示例

输入

100

输出

数字100的最大约数(小于该数字本身):50

提示

While in python

In the Python programming language, the while loop construction can have an optional else block. This block is executed only when the loop completes in its natural way, that is, when its condition becomes false, and not as a result of a forced interruption using the break operator.

Syntax:

while condition:
    # the body of the loop
    # ...the code that runs on each iteration...
else:
    # else block
    # ...the code that is executed if the loop ended without a break...

You can think of the else block as a "plan B": it is triggered if the main goal within the loop (which is usually completed through a break) has not been achieved.

Usage example: Searching for an element

Consider a classic problem where we search for a number in a list. If a number is found, we immediately break the loop using break. If we have checked all the elements and still haven't found what we are looking for, the else block is executed.

numbers = [1, 2, 3, 4, 5]
target = 8 # Let's try to find a number that is not in the list.

index = 0
while index < len(numbers):
    if numbers[index] == target:
        print(f"Success! {target} found at {index}.")
break # Goal reached, exit the loop
    index += 1
else:
    # This block will be executed because break was not called
    print(f"The search is completed. {target} not found in the list.")

How it works:

  1. The whileloop is executed as long as the index < len(numbers) condition is true.
  2. Inside the loop, we check whether the current element is equal to the desired one (target).
  3. If we find a value, a success message is displayed and the loop is immediately interrupted by the break statement. The else block is ignored in this case.
  4. If the loop reaches the end (checked all the elements), it means that break has never worked. The index < len(numbers) condition becomes false, and then the else block is executed, reporting a failed search.

A useful tip: Using while...else helps to avoid "flagged" variables. Without this block, the code would look like this:

# Alternative version with "flag"
numbers = [1, 2, 3, 4, 5]
target = 8
found = False # Flag variable

index = 0
while index < len(numbers):
    if numbers[index] == target:
        found = True
        break
    index += 1

if found:
    print(f"Success! {target} found.")
else:
print(f"Search completed. {target} not found in the list.")

As you can see, the while...else construction makes the code cleaner, more concise, and more "Pythonic", eliminating the need to manually control the flag.

If break is missing

If there is no break operator in the body of the while loop, then the else block will always be executed after the loop ends.

count = 0
while count < 3:
print(f"Iteration number {count}")
count += 1
else:
print("The loop ended naturally, so the else block is executed.")

Here, the while loop runs until count is less than 3. As soon as count becomes 3, the loop condition becomes false, and control is transferred to the else block.

Important nuances

  • What about continue? The continue operator does not interrupt the loop, but only ends the current iteration ahead of schedule. It does not affect the execution of the else block in any way.
  • If the loop was never executed? If the while condition is initially false, the loop body will not be executed even once. However, the else block will still run, since the loop ended "normally" (it was not interrupted via break).
value = 10
while value < 5: # The condition is immediately false
    print("This text will never be printed")
else:
print("The cycle didn't even start, but it ended normally, so else worked.")
  • This also works for for loops! The same logic applies to for...else loops. The else block after for is executed if the cycle has passed through all the elements and has not been interrupted using break.

Output

The while...else construction is a powerful and elegant Python tool. It is ideal for situations where you need to perform an action only if the loop has completed its work completely without being interrupted. This is especially useful in search algorithms, condition checking, or when working with data streams, where break signals a special event, and else indicates a regular termination without any.

main.py
测试 1
测试 2
测试 3
测试 4
测试 5
测试 6
测试 7
测试 8
测试 9
测试 10
开发者解答
# Получаем число от пользователя и преобразуем его в целый тип данных
n = int(input())

# Начинаем поиск с самого большого возможного делителя,
# который может быть у числа n — это n - 1.
# Мы будем уменьшать это значение, пока не найдем подходящее.
divisor = n - 1

# Запускаем цикл while. Он будет продолжаться до тех пор,
# пока мы не найдем делитель. Условие divisor > 0 страхует нас
# от бесконечного цикла и гарантирует, что для простых чисел
# мы в итоге дойдем до 1.
while divisor > 0:
    # Проверяем, делится ли число n на текущее значение divisor без остатка.
    if n % divisor == 0:
        # Если остатка нет, значит, мы нашли делитель.
        # Так как мы идем от большего числа к меньшему,
        # первый найденный делитель и будет самым большим.
        # Выводим его на экран.
        print(f"Наибольший делитель числа {n} (меньше самого числа): {divisor}")
        # Прерываем цикл, так как задача выполнена.
        break
    
    # Если текущее значение не является делителем,
    # уменьшаем его на 1 и переходим к следующей итерации цикла.
    divisor = divisor - 1

🎉 恭喜! 🎉

你出色地完成了任务!这是一个不小的挑战,但你找到了正确答案。你离编程大师又近了一步!继续保持,每一步都让你更强大。

AD

广告

red-snake blue-snake green-snake

正在运行代码...

AI助手

你好!我是你的编程助手。随时向我提问关于 Python 的问题——我可以解释函数、方法,并帮助你完成当前任务!