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

درس 3. FOR cycle

الصعوبة:

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

مسألة«ماكينة الصراف الآلي»

💻 Python

تخيل أنك تقوم بإعداد برنامج لصراف آلي. لأسباب أمنية، عند إدخال الحساب الشخصي، يطلب الصراف الآلي من المستخدم تكرار عبارة محددة عددًا محددًا من المرات. ومع ذلك، لكي لا يمل العميل، وضع نظام الأمان حدًا: لا يمكنك طلب تكرار العبارة أكثر من 10 مرات.

rn

مهمتك — كتابة برنامج يقوم بـ:

rn
    rn
  1. قراءة العبارة التي يجب تكرارها.
  2. rn
  3. قراءة عدد التكرارات المطلوبة.
  4. rn
  5. التحقق مما إذا كان عدد التكرارات يتجاوز 10 مرات.
  6. rn
  7. إذا كان عدد التكرارات 10 أو أقل، يعرض البرنامج العبارة المحددة بالعدد المحدد من المرات. يجب عرض كل تكرار في سطر جديد.
  8. rn
  9. إذا كان عدد التكرارات أكثر من 10، يجب على البرنامج عرض رسالة خطأ واحدة: "خطأ: لا يمكن أن يتجاوز عدد التكرارات 10".
  10. rn

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

السطر الأول: العبارة التي يحددها جهاز الصراف الآلي (النوع: نص).
السطر الثاني: عدد المرات التي تحتاج فيها إلى تكرار العبارة (النوع: رقم).

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

إذا كان عدد التكرارات لا يتجاوز 10: يتم عرض العبارة المحددة، مكررة العدد الصحيح من المرات. كل عبارة في سطر جديد (النوع: سطر).
إذا كان عدد التكرارات يتجاوز 10: رسالة خطأ (النوع: سطر).

مثال

إدخال

أؤكد
3

إخراج

أؤكد
أؤكد
أؤكد

تلميح

Diving into cycles: for and range()

The for loop is one of the most powerful and frequently used tools in Python. It allows you to repeat (or, as programmers say, iterate) a certain block of code a set number of times. His main idea is to sequentially iterate over elements from a collection (for example, a list of numbers, characters in a string, etc.) and perform the same action for each element.

The basic syntax looks like this:

for element in sequence:
    # a block of code that will be repeated

Here, the sequence can be not only numbers, but also, for example, a list of strings or just a string.

# Example of iterating through a list
for fruit in ["apple", "banana", "cherry"]:
print(fruit)

# Example of line iteration
for letter in "Python":
print(letter)

Generating sequences with range()

We often need to execute the code a certain number of times. The range() function is ideal for this, which creates a sequence of numbers. For example, range(5) creates a sequence from 0 to 4 (i.e. 0, 1, 2, 3, 4).

Combining for and range(), we get a classic construction for repetitions.:

for i in range(number):
    # code block

Let's analyze this construction:

  • for is the keyword that tells Python that we are starting a cycle.
  • i is a counter variable. At each step of the cycle, it will take the next value from the sequence. A useful tip: the variable name can be anything (i, j, k - these are generally accepted conventions for simple counters), but if you are going over something specific, it is better to give a meaningful name. for example for student in students:.
  • in is the keyword that binds the counter variable and the sequence.
  • range(number) calling a function that creates a sequence of integers from 0 to number - 1. It is important to remember that the upper bound is not included.
  • The code block (indented) is the commands that you want to execute for each number in the sequence.

Practical examples

Output of numbers from 0 to 4

for i in range(5):
    print(i)
# output: 0
# output: 1
# output: 2
# output: 3
# output: 4
  • range(5) creates an invisible sequence for us: 0, 1, 2, 3, 4.
  • The for loop assigns each of these values to the i variable in turn.
  • print(i) prints the current value of i at each step.

Re-executing the code 5 times

for i in range(5):
print("Hello world!")
# output: Hello world!
# conclusion: Hello, world!
# conclusion: Hello, world!
# conclusion: Hello, world!
# conclusion: Hello, world!
  • range(5) creates the sequence again 0, 1, 2, 3, 4.
  • The for loop goes through each of these numbers, but in this case we don't use the value of the i variable inside the loop. We just use the loop as a counter to run print("Hello, world!") exactly 5 times.

Summation of numbers from 0 to 4

amount = 0 # 1. Creating a "piggy bank" for the amount
for i in range(5):
    #2. At each step, we add the current number to the piggy bank
    sum += i
print(sum) # 3. We show what has accumulated in the end
# output: 10
  • amount = 0 initialize the variable amount. This is a critical step.
  • range(5) creates a sequence 0, 1, 2, 3, 4.
  • The for loop runs through each number. In the first step, the sum becomes 0 + 0 = 0. On the second one, 0 + 1 = 1. On the third one, 1 + 2 = 3. On the fourth floor, 3 + 3 = 6. On the fifth - 6 + 4 = 10.
  • sum +=i is a shortened and more "pythonic" notation for sum = sum + i. It increases the value of sum by the current value of i.
  • print(amount) outputs the total amount after the cycle is completely completed.

Flexibility range(): parameters start, stop, step

The range() function can take up to three parameters: start (start), stop (end) and step (step).

  • range(stop): creates a sequence from 0 to stop - 1.
  • range(start, stop): creates a sequence from start to stop - 1.
  • range(start, stop, step): creates a sequence from start to stop - 1 in step increments.

A useful tip: The step may be negative. This allows you to generate sequences in reverse order. In this case, the start value should be greater than stop.

  • range(5) -> 0, 1, 2, 3, 4
  • range(2, 6) -> 2, 3, 4, 5
  • range(1, 10, 2) -> 1, 3, 5, 7, 9
  • range(5, 0, -1) -> 5, 4, 3, 2, 1

What are increment and decrement?

An increment is simply an increase in the value of a variable, usually by 1. A decrement is a decrease in the value of a variable, usually by 1.

Some programming languages have special operators ++ and --, but Python does not have them. Instead, more explicit and flexible assignment operators with the operation are used.

Increment in Python: operator +=

We can easily increase the value of a variable using +=.

number = 5
# Increasing the value of the variable by 1
number += 1
print(number) # will output 6
  • the number = 5 sets the initial value.
  • number += 1 is an elegant shorthand for number = number + 1. She says, "take the current value of the number, add 1 to it, and write the result back to the number."

Decrement in Python: operator -=

Similar to increment, the -= operator is used for decrement.

number = 5
# Reducing the value of a variable by 1
number -= 1
print(number) # will output 4
  • the number = 5 sets the initial value.
  • number -= 1 is an abbreviation for number = number - 1.

Other useful operators

This principle works with all basic mathematical operations in Python. Instead of the number on the right, there may be another variable (a +=b).

a = 10
a += 5 # Equivalent to a = a + 5 (a will become 15)
a -= 3 # Equivalent to a = a - 3 (a will become 12)
a *= 2 # Equivalent to a = a * 2 (a will become 24)
a /= 4 # Is equivalent to a = a / 4 (a will become 6.0)
a %= 5 # Is equivalent to a = a %5 (a will become 1.0, the remainder of dividing 6 by 5)
a //= 3 # Is equivalent to a = a // 3 (a will become 0.0, integer division of 1 by 3)

Key ideas and useful tips

  • The for loop is designed to iterate through elements in any sequence (lists, strings, range, etc.).
  • The range() function is your main tool for creating sequences of numbers for loops. Remember that it does not include an upper bound!
  • Increment (+=) and decrement (-=) are the standard and preferred way to change numeric variables in Python.
  • Meaningful names. Give the loop variables understandable names (for book in books:), it makes the code much more readable.
  • Practice is the key to success! Try writing loops to solve different problems: find the sum of even numbers, print the multiplication table, and print a ladder of symbols.
main.py
اختبار 1
اختبار 2
اختبار 3
اختبار 4
اختبار 5
اختبار 6
اختبار 7
اختبار 8
اختبار 9
حل المطور
# Запрашиваем у пользователя фразу, которую нужно будет повторить.
# Функция input() считывает одну строку текста.
secret_phrase = input()

# Запрашиваем количество повторений.
# Функция input() считывает строку, а int() превращает её в целое число.
repeat_count = int(input())

# Это условие. Проверяем, больше ли введенное число, чем 10.
if repeat_count > 10:
    # Если условие истинно (число больше 10), выводим сообщение об ошибке.
    print("Ошибка: количество повторений не может превышать 10")
else:
    # Если условие ложно (число 10 или меньше), выполняется эта часть кода.
    # Запускаем цикл for. Он будет работать столько раз, сколько указано в repeat_count.
    # range(repeat_count) создает последовательность чисел от 0 до repeat_count-1.
    for i in range(repeat_count):
        # На каждом шаге цикла (итерации) выводим секретную фразу.
        print(secret_phrase)

🎉 تهانينا! 🎉

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

AD

إعلان

red-snake blue-snake green-snake

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

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

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