• 1
    إدخال وإخراج البيانات
    • المهام
  • 2
    الشروط
    • المهام
  • 3
    حلقة for
    • المهام
  • 4
    السلاسل النصية
    • المهام
  • 5
    حلقة while
    • المهام
  • 6
    القوائم
    • المهام
  • 7
    مصفوفات ثنائية الأبعاد
    • المهام
  • 8
    القواميس
    • المهام
  • 9
    المجموعات
    • المهام
  • 10
    الدوال والتكرار
    • المهام
  • к

درس 5. While cycle

الصعوبة:

иконка человека красный иконка человека белая иконка человека зеленая Pythonlib

مسألة«حساب الأعداد بين»

💻 Python

في مختبره القديم، وجد الخيميائي أليستر جرعة مذهلة. إذا أسقطتها على رقعة مكتوب عليها رقم، تبدأ الجرعة في الأزيز والتوهج، ثم يظهر رمز سحري في الهواء، يعني عدد الأرقام في هذا الرقم. قرر أليستر، الذي ليس فقط خيميائيًا بل أيضًا متحمسًا لـ"التقنية السحرية" الجديدة (البرمجة)، إعادة إنشاء هذا التأثير باستخدام الكود.

مهمتك — ساعد أليستر واكتب برنامجًا سحريًا. يجب أن تأخذ هذه التعويذة رقمًا واحدًا كمدخل وتحدد عدد الأرقام فيه.

قواعد سحرية مهمة:

  • يجب أن تعمل التعويذة مع الأرقام الموجبة والسالبة.
  • علامة "الناقص" في الأرقام السالبة لا تُعتبر رقمًا. على سبيل المثال، في الرقم -123 يوجد 3 أرقام فقط.
  • الرقم 0 يتكون من رقم واحد.

 

تنسيق الإدخال

واحد هو رقم كامل يقدمه الخيميائي إلى مدخل جهازه (عدد صحيح/عدد صحيح).

تنسيق الإخراج

عدد الأرقام في رقم الإدخال (رقم صحيح / Integer).

مثال

إدخال

-481516

إخراج

6

تلميح

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
حل المطور
# Считываем входные данные от пользователя в виде строки
input_str = input()

# Преобразуем строку в целое число
number = int(input_str)

# Инициализируем счетчик цифр
digit_count = 0

# Проверяем особый случай: если число равно 0
if number == 0:
    # В числе 0 ровно одна цифра
    digit_count = 1
else:
    # Если число отрицательное, делаем его положительным для удобства подсчета
    if number < 0:
        number = -number  # Знак минуса не является цифрой

    # Запускаем цикл, который будет работать, пока в числе есть цифры
    while number > 0:
        # Целочисленно делим число на 10, отбрасывая последнюю цифру
        number = number // 10
        # Увеличиваем счетчик на 1 за каждую отброшенную цифру
        digit_count = digit_count + 1

# Выводим итоговое количество цифр
print(digit_count)

🎉 تهانينا! 🎉

لقد حللت المهمة ببراعة! كان صعبًا لكنك وجدت الحل الصحيح. أنت خطوة أقرب إلى الاحتراف! استمر، كل مرحلة تجعلك أقوى.

AD

إعلان

red-snake blue-snake green-snake

جارٍ تشغيل الكود...

مساعد الذكاء الاصطناعي

مرحباً! أنا مساعدك في البرمجة. اسألني أي شيء عن Python — يمكنني شرح الدوال والطرق ومساعدتك في المهمة الحالية!