ლექცია 04 · IV კვირაLecture 04 · Week IV

ციკლებიLoops

for · while · range() · break და continue · ჩადგმული ციკლები for · while · range() · break and continue · nested loops

ეს კურსის ერთ-ერთი გადამწყვეტი ლექციაა. ვინც ციკლებს ვერ აითვისებს, შემდეგ ყველგან გაუჭირდება. მეტი დრო დაუთმე ცოცხალ ტრასირებას. One of the pivotal lectures. Anyone who does not get loops will struggle everywhere afterwards. Spend extra time tracing them live.

მოტივაციაMotivation

რატომ გვჭირდება ციკლიWhy we need loops

ციკლის გარეშეWithout a loop

print("გამარჯობა")
print("გამარჯობა")
print("გამარჯობა")
print("გამარჯობა")
print("გამარჯობა")

და თუ 1000-ჯერ დაგვჭირდა? ან რაოდენობა მომხმარებლისგან მოდის? And if we needed it 1000 times? Or the count comes from the user?

ციკლითWith a loop

for i in range(5):
    print("გამარჯობა")

რიცხვის შეცვლა — ერთი სიმბოლოა. Changing the count is a single character.

ორი სახეობა for — როცა ვიცით, რამდენჯერ (ან რაზე ვიარებთ) while — როცა პირობა წყვეტს, გავაგრძელოთ თუ არა Two kinds for — when we know how many times (or what to walk over) while — when a condition decides whether to continue

კონსტრუქციაConstruct

for — გავლა თანმიმდევრობაზეfor — walking a sequence

for variable in sequence:
    body
for i in range(5):
    print(i)

0 1 2 3 4

for letter in "პითონი":
    print(letter, end=" ")

პ ი თ ო ნ ი

ცვლადის სახელიხშირად i (index), მაგრამ აზრიანი სახელი სჯობს: for student in group: The variable nameOften i (for index), but a meaningful name is better: for student in group:

ინსტრუმენტიTool

range() — სამი ფორმაrange() — three forms

ჩანაწერიWritten as რას ნიშნავსWhat it means მნიშვნელობებიValues
range(5)0-დან 5-მდეFrom 0 up to 50 1 2 3 4
range(2, 6)2-დან 6-მდეFrom 2 up to 62 3 4 5
range(0, 10, 2)ბიჯით 2In steps of 20 2 4 6 8
range(10, 0, -1)უკუსვლითCounting down10 9 8 … 1
ბოლო რიცხვი არ შედისrange(1, 5) იძლევა 1, 2, 3, 4-ს. 5-ის ჩასათვლელად საჭიროა range(1, 6).
ეს დამწყებთა #1 შეცდომაა („off-by-one“).
The last number is not includedrange(1, 5) gives 1, 2, 3, 4. To include 5 you need range(1, 6).
This is the #1 beginner mistake — the “off-by-one”.
for i in range(1, 11):
    print(i, end=" ")        # 1 2 3 4 5 6 7 8 9 10

print(list(range(5)))        # [0, 1, 2, 3, 4]

კონსტრუქციაConstruct

while — სანამ პირობა სრულდებაwhile — as long as the condition holds

while condition:
    body
count = 0

while count < 5:
    print(count)
    count += 1        # ⚠ mandatory!

print("დასრულდა")

სამი აუცილებელი ნაწილიThree essential parts

  1. ინიციალიზაციაcount = 0 ციკლამდე
  2. პირობაcount < 5
  3. ცვლილებაcount += 1 სხეულში
  1. Initialisationcount = 0 before the loop
  2. Conditioncount < 5
  3. Changecount += 1 in the body
თუ მესამე დაგავიწყდამიიღებ უსასრულო ციკლს — პროგრამა არასდროს დამთავრდება.
გაჩერება: Ctrl+C ტერმინალში.
Forget the third andyou get an infinite loop — the program never ends.
Stop it with Ctrl+C in the terminal.

მაგალითიExample

while-ის ნამდვილი ადგილიWhere while really belongs

for ჯობია, როცა რაოდენობა ცნობილია. while — როცა არა.

Use for when the count is known, while when it is not.

მომხმარებლის შემოწმებაChecking user input

password = ""

while password != "python":
    password = input("პაროლი: ")

print("წვდომა დაშვებულია")

დაგროვება ზღვრამდეGrowing to a threshold

balance = 1000
year = 0

while balance < 2000:
    balance *= 1.10   # 10% per year
    year += 1

print(f"{year} წელი, ბალანსი {balance:.2f}")

8 წელი, ბალანსი 2143.59

იკითხე: „რამდენი წელი დასჭირდება?“ — სტუდენტები ვერ იტყვიან წინასწარ. სწორედ ესაა while-ის არსი. Ask: “how many years will it take?” — nobody can say in advance. That is exactly the point of while.

მართვაControl

break დაand continue

breakგამოდის ციკლიდანexits the loop

for i in range(1, 11):
    if i == 5:
        break
    print(i, end=" ")

1 2 3 4

ციკლი მთლიანად წყდება.The loop stops entirely.

continueგამოტოვებს ერთ ბიჯსskips one iteration

for i in range(1, 11):
    if i % 2 == 0:
        continue
    print(i, end=" ")

1 3 5 7 9

ციკლი გრძელდება, ეს ბიჯი გამოტოვდა.The loop continues; this step was skipped.

ჩადგმულ ციკლშიbreak მხოლოდ უახლოეს ციკლს წყვეტს, არა ყველას. Inside nested loopsbreak exits only the innermost loop, not all of them.

ნაკლებად ცნობილიLesser known

else ციკლთან ერთადelse attached to a loop

სრულდება მაშინ, როცა ციკლი break-ის გარეშე დამთავრდა.

It runs when the loop finished without hitting break.

n = int(input("რიცხვი: "))

for d in range(2, n):
    if n % d == 0:
        print(f"{n} იყოფა {d}-ზე — მარტივი არაა")
        break
else:
    print(f"{n} მარტივი რიცხვია")
წაიკითხე ასე„გაიარე ციკლი; თუ break-ს ვერ მიაღწიე — შეასრულე else“. გამოგადგება „ვეძებდი და ვერ ვიპოვე“ ტიპის ამოცანებში. Read it as“run the loop; if you never reached break, run the else.” Useful for “I searched and found nothing” problems.
ეს კონსტრუქცია Python-ის სპეციფიკურია და შუალედურის ღია კითხვად კარგად გამოდგება. This construct is Python-specific and makes a good midterm open question.

შაბლონიPattern

დაგროვება (accumulator)The accumulator

ყველაზე ხშირი შაბლონი ციკლებში: ცვლადი ციკლამდე, ცვლილება ციკლში. The most common loop pattern: declare the variable before the loop, change it inside.

ჯამიSum

total = 0
for i in range(1, 101):
    total += i
print(total)        # 5050

დათვლაCounting

count = 0
for c in "programming":
    if c in "aeiou":
        count += 1
print(count)        # 3

მაქსიმუმის ძებნაFinding the maximum

biggest = 0
for i in range(5):
    n = int(input("რიცხვი: "))
    if n > biggest:
        biggest = n
print("უდიდესი:", biggest)
ფრთხილადbiggest = 0 ვერ იმუშავებს, თუ ყველა რიცხვი უარყოფითია. სწორი გზა — პირველი მნიშვნელობით ინიციალიზაცია. Carefulbiggest = 0 fails if every number is negative. The correct approach is to initialise with the first value.

კონსტრუქციაConstruct

ჩადგმული ციკლებიNested loops

for i in range(1, 6):
    for j in range(1, 6):
        print(f"{i * j:4}", end="")
    print()          # line break, in the outer loop

1 2 3 4 5 2 4 6 8 10 3 6 9 12 15 4 8 12 16 20 5 10 15 20 25

როგორ იმუშავაგარე ციკლის ერთ ბიჯზე შიდა ციკლი მთლიანად გაირბენს. 5 × 5 = 25 შესრულება. How it worksFor each step of the outer loop, the inner loop runs completely. 5 × 5 = 25 executions.
for i in range(1, 6):
    print("*" * i)

* ** *** **** *****

შაბლონიPattern

უსასრულო ციკლი + break (მენიუ)Infinite loop + break (a menu)

while True:
    print("\n1 — შეკრება")
    print("2 — გამრავლება")
    print("0 — გასვლა")

    choice = input("არჩევანი: ")

    if choice == "0":
        print("ნახვამდის!")
        break
    elif choice == "1":
        a = float(input("a: "))
        b = float(input("b: "))
        print("შედეგი:", a + b)
    elif choice == "2":
        a = float(input("a: "))
        b = float(input("b: "))
        print("შედეგი:", a * b)
    else:
        print("არასწორი არჩევანი")
ეს შაბლონიინტერაქტიული პროგრამების საფუძველია. while True + break — სრულიად ნორმალური და გავრცელებული ხერხია. This patternis the backbone of interactive programs. while True + break is perfectly normal and widely used.

პრაქტიკაPractice

რიცხვის ციფრებთან მუშაობაWorking with the digits of a number

n = int(input("მთელი რიცხვი: "))
n = abs(n)

total = 0
count = 0
reversed_num = 0

while n > 0:
    digit = n % 10          # the last digit
    total += digit
    count += 1
    reversed_num = reversed_num * 10 + digit
    n = n // 10             # drop the last digit

print("ციფრების ჯამი:", total)
print("ციფრების რაოდენობა:", count)
print("შებრუნებული:", reversed_num)

მთელი რიცხვი: 1234 ციფრების ჯამი: 10 ციფრების რაოდენობა: 4 შებრუნებული: 4321

ეს კლასიკური ამოცანაა და გამოცდაზე ხშირად ხვდება. ტრასირება დაფაზე: n=1234 → digit=4, n=123 → … A classic exercise that shows up in exams often. Trace it on the board: n=1234 → digit=4, n=123 → …

დიაგნოსტიკაTroubleshooting

ხშირი შეცდომებიCommon mistakes

შეცდომაMistake რა ხდებაWhat happens
მთვლელის გაზრდა დაგავიწყდა while-შიForgot to increment the counter in while უსასრულო ციკლი. Ctrl+CInfinite loop. Ctrl+C
range(1, 5) და 5-ს ელოდებიrange(1, 5) while expecting 5 ბოლო რიცხვი არ შედის → range(1, 6)The last value is excluded → range(1, 6)
დამგროვებელი ცვლადი ციკლის შიგნით ინიციალიზდებაThe accumulator is initialised inside the loop ყოველ ბიჯზე ნულდება — შედეგი არასწორიაIt resets every iteration — the result is wrong
print() არასწორ დონეზეა ჩადგმულ ციკლშიprint() at the wrong level in a nested loop გამოტანა არეულია — გადახედე წანაცვლებასThe output is scrambled — check the indentation
for i in range(len(s)) როცა პირდაპირ for c in s გამოდგებაfor i in range(len(s)) where for c in s would do მუშაობს, მაგრამ არა-Python-ური სტილიაIt works, but it is not Pythonic
დიაგნოსტიკის ხერხიჩადეთ print(i, total) ციკლის სხეულში — მაშინვე დაინახავთ, სად გაფუჭდა. ან გამოიყენეთ დებაგერი (F5). A debugging trickDrop print(i, total) into the loop body — you will see immediately where it went wrong. Or use the debugger (F5).

შემაჯამებელიWrap-up

რა უნდა დაგამახსოვრდესWhat to remember

სახლში1) 1–100 რიცხვების ჯამი და საშუალო. 2) ფაქტორიალი. 3) მამრავლების ცხრილი (1–9). 4) გამოიცანი რიცხვი (random-ის გარეშე, ფიქსირებული რიცხვით). 5) დახატე „ნაძვის ხე“ ვარსკვლავებით. At home1) Sum and average of 1–100. 2) Factorial. 3) A multiplication table (1–9). 4) Guess-the-number (without random, using a fixed number). 5) Draw a “fir tree” out of asterisks.
შემდეგი — ლექცია 05ჩაშენებული ფუნქციები, მოდული math და შემთხვევითი რიცხვები. Next — lecture 05Built-in functions, the math module and random numbers.