☰ خطة العام · تكنولوجيا المعلومات والاتصالات (بالإنجليزية)

Formulas, comparisons and loops

الأسبوع 3 · الدرس ١ «التفكير الحاسوبي وحل المشكلات» (٣): مساحة المستطيل وأكبر رقم وحلقة الجمع والنشاط والتدريبات · 3 دروس
3

Adding 1 to 5 with a for loop

ICT Prep 3 Term 1, Unit 1, Lesson 1: pp. 10–17
GoalAdd the numbers 1 to 5 with a for loop and trace it with a table.
New words
loop · code that repeats the same step several timesrange(1, 6) · the numbers 1, 2, 3, 4, 5; it stops before 6total += i · adds i to total; the same as total = total + itrace table · a table that shows the values after each repetition
Explanation

To add 1, 2, 3, 4 and 5 we repeat the same step five times: add the next number. Whenever a step repeats, we use a loop. First we start the total at 0, so that the sum begins from nothing. Then for i in range(1, 6) visits the numbers 1, 2, 3, 4 and 5. Note that range(1, 6) stops before 6, so 6 is not visited. Inside the loop, total += i adds the current number to the total. When the loop ends, the program shows 15. A trace table helps to see the loop: write the value of i and the total after each turn. Python is case sensitive, so the name must be written the same each time: i and I would be two different names.

AB
1itotal after adding
211
323
436
5410
6515
Worked examples
Starttotal = 0i = 1i <= 5yestotal = total + ii = i + 1noshow totalEnd
The flowchart shows the same loop: the diamond asks whether i is still 5 or less. If yes, add i and move to the next i; if no, leave the loop and show the total.
Python
1total = 0
2for i in range(1, 4):
3    total += i
4print(total)
Output
6
With range(1, 4) the loop visits only 1, 2 and 3, because it stops before 4. The total is 1 + 2 + 3 = 6.
Class activity

Mona has three marks: 45, 60 and 52. The rule, decided by a person, is: pass if the average is at least 50. Write the four skills, then the idea of the code (three inputs, the average with brackets, if and else). What does the program show for her marks?

Practice
1
Which numbers does for i in range(1, 6) visit?
2
Why do we write total = 0 before the loop?
3
What is the total for range(2, 6)?
4
What does total += i mean in other words?