Lecture 7: Python Basic Syntax : Loops
Repetition in Python start
While statement
instruction1_inside_the_while
while (condition) : While this is true
instruction1_inside_the_while
instruction2_inside_the_while Do this instruction2_inside_the_while
instruction_outside_the_while
True
condition
False
instruction_outside_the_while
end
Start_Smart_ Punishment
Counted Loop in Python
counter=0
Need to have a variable that
counts the number of times
that the loop is executed. Output "I will not cheat
in my assessments"
The condition depends on the
counter.
counter= counter+1
Recall this flowchart example:
True counter
<10 ?
False
End_Smart_Punishment
Counted loop in Python
One time:
print("I will not cheat in my assessment")
Modify the above program to print the statement 10 times.
Building blocks of counted loops:
1- Initializing the counter
Counted loop in Python 2-Condition to test if the counter reaches the
Loop to repeat the process: end value (e.g., 10).
3- Incrementing the counter.
Starting loop from zero
• Starting loop from one
counter = 0
counter = 1
while (counter < 10):
while (counter <= 10):
counter = counter + 1
print("I will not cheat in my
print("I will not cheat in my assessment")
assessment")
counter = counter + 1
• Forgetting the increment the counter • Incorrect decrement results in an infinite
results in an infinite loop… loop…
counter = 1 counter = 1
while (counter <= 10): while (counter <= 10):
print("I will not cheat in my assessment") print("I will not cheat in my assessment")
counter = counter - 1
counter is never incremented in this program, counter <= 10 will counter is decremented in this program, counter <= 10 will always be
always be true. Possible values of counter are: 1 1 1 1 etc… true. Possible values of counter are: 1 0 -1 -2 -3 etc…
Counted loop in Python: Computing Sum and
Average
The counter variable can be used as an index in the loop
The counter can be useful to compute sums and averages
Use a running sum to add up all user entries in one variable
Example: write program that computes the average grade of five students and runs as follows:
Enter the grade of student 1 90
Enter the grade of student 2 60
Enter the grade of student 3 70
Enter the grade of student 4 55
Enter the grade of student 5 80
The average grade of students is 71.0
1.Start_averageGrade
Counted loop in Python: Computing
Sum and Average [Link] =0
Need to have a variable that counts the 3.total_grades = 0
number of times that the loop is 4. Input "Enter the grade of
executed. student" (counter + 1)
Need to have a variable to that 5. total_grades = total_grades + grade
calculate the total for all grades.
The avg is computed outside the loop, 6. counter=counter + 1
after the sum of all numbers has been True
[Link]<5?
done.
False
8. average= total_grades /count
9. "The average grade of
students is" avg
10.End_averageGrade
Counted loop in Python: Computing Sum and
Average
counter = 0 1) Initialize counter
total_grades = 0
while (counter < 5):2) Check condition
grade = int(input("Enter the grade of student"+
3) Execute
str(counter + 1))) body
total_grades = total_grades + grade
counter = counter + 1 4) Increment counter
avg = total_grades / counter 5) Calculate and print average
print("The average grade of students is", avg) outside the loop
Counted loop in Python: Computing Sum and
Average
We can use the same program to read the grades of 20 students by changing
the number of student in the condition to be 20 instead of 5.
counter = 0
total_grades = 0
while (counter < 20):
grade = int(input("Enter the grade of student"+
str(counter + 1) ))
total_grades = total_grades + grade
counter = counter + 1
avg = total_grades / counter
print("The average grade of students is", avg)
Counted loop in Python: Computing Sum and
Average
Change the program to read two grades and find the output if the user enters 10 and 20.
counter = 0
total_grades = 0
while (counter < 2):
grade = int(input("Enter the grade of student"+ str(counter + 1) ))
total_grades = total_grades + grade
counter = counter + 1
avg = total_grades / counter
print("The average grade of students is", avg)
Memory Output
counter total_grades grade avg
0 0 10 15.0 The average grade of students is 15.0
1 10 20
2 30
Counted loop in Python: Computing Sum and
Average
Rewrite the same program by starting the counter from one instead of zero.
Notice changes!
counter = 1
total_grades = 0
while (counter <= 2):
grade = int(input("Enter the grade of student"+
str(counter) ))
total_grades = total_grades + grade
counter = counter + 1
avg = total_grades / (counter – 1)
print("The average grade of students is", avg)
Counted loop in Python: Computing Sum and
Average
The number of students could be a parameter defined by the user (for example to compute
the average of different sections and sections have different number of students in them)
counter = 0
total_grades = 0
num_students = int(input("Enter the number of students
in the section"))
while (counter < num_students):
grade = int(input("Enter the grade of student"+
str(counter + 1) ))
total_grades = total_grades + grade
counter = counter + 1
avg = total_grades / counter
print("The average grade of students is", avg)
Sentinel loop in Python
Sometimes, we don’t • General form:
know how many times
we want to repeat the input first value into variable
loop.
While (variable != sentinelValue)
Therefore, the program is .
designed to repeat the loop .
until a special value is met. .
This special value is called process the value in the variable
.
sentinel value.
.
.
input another value into variable
The program reads a value before the loop, then in
the loop, process the value and read another value.
Start_Daily_Sales
Sentinel loop in Python
total_sales = 0
The condition is on the value entered by the
user. What is the current
sale amount?
Recall for instance the example given in
flowcharts. total_sales = total_sales + current_sale
True
current_sale!=0?
False
Output: The daily
sale is total_sales
End_Daily_Sales
Sentinel loop in Python
One time:
Current_sale=int(input("What is the current sale
amount?"))
print("The daily sale is ", current_sale)
Modify the above program to keep asking the user for current sales until the user
enters zero! The program should display the total sales.
Sentinel loop in Python
Loop to repeat the process:
total_sale=0
current_sale = int(input("What is the current sale
amount?"))
while (current_sale != 0): 10
0 != 0?
20 !=
total_sale = total_sale + 0?
current_sale
current_sale= int(input("What is the c1urrent sale
amount?"))
print("The daily sale is ", total_sale)
Memory Output
total_sale current_sale
0 10 The daily sale is 30
Trace the above
10
program if the user enters
20
10, 20, 0
30 0
Sentinel loop in Python
Trace the program again if the user enters 10, 20,-10, 0:
Total_sale=0 Memory
total_sal current_sa
current_sale = int(input("What is the current sale
e 0 e 10
amount?")) 10 20
0 != 0?
while (current_sale != 0): 20
10 !=
-10 != 30 -10
0?
0?
20 0
total_sale = total_sale + current_sale
current_sale= int(input("What is the current sale
Output
amount?"))
print("The daily sale is ", total_sale) The daily sale is 20
Total sales is incorrect ! Why?
See the fixed code in the next slide!
Sentinel loop in Python (fixed code)
Trace the program again after we fixed it if the user enters 10, 20,-10, 0:
Memory
total_sale=0 current_sa
total_sale
current_sale = int(input("What is the current sale0 10
amount?")) 10 20
20 >> 0?
-10
10 0?
while (current_sale > 0): 30 -10
total_sale = total_sale + current_sale
current_sale= int(input("What is the c1urrent sale
amount?")) Output
print("The daily sale is ", total_sale)
The daily sale is 30
Nested Loops Outer Loop
It is possible to have a loop inside a
loop, which is called a nested loop
The loops should use different
counters
The indentation level makes the
difference between the inner and outer
loop
Example nested loop structure:
Outer loop (runs i times) Inner Loop
Inner loop (runs j times)
Body of inner loop (runs i x j times)
i j
Nested Loops 1 1
Example: write a program that shows table of multiplications i*j
where i is between 1 and 2 and j is between 1 and 3 2
i = 1 Outer Loop
3
while (i <= 2):
Output
j = 1 4
1 * 1 = 1
while (j <= 3): i j 1 * 2 = 2
2 1 1 * 3 = 3
print(i, "*", j, "=", i*j)
2 * 1 = 2
j = j + 1 2 2 * 2 = 4
2 * 3 = 6
i = i + 1 3 end
print("end")
4
Inner Loop v
i
3
Practice Comparisons
2<6 True Less than
2 != 6 True Not equal to
2 == 6 False Equal to (Notice double ==)
2 >= 6 False Greater than or equal to
1<2<6 True Multiple comparisons.
2 is greater than 1 and 2 is less than 6
Single ‘=‘ is assignment
Double ‘==‘ is comparison
Practice counted loops
i=0 i=0 i=1
i=1
while i < 5: while i <= 5: while i < 10:
while i < 10:
print (i) print (i) if i > 4:
print (i)
i=i+1 i=i+1 print (i)
i +=3
i += 3
0 0 1
1 1 4 7
2 2 7
3 3
4 4
5
a=5 a=5 while True: while False: while True:
while a>0: while a>0: print (1) print (1) print (1)
print(a ,end=" ") print(a) break
Infinite loop Nothing is printed
a=a - 1 print("Bye")
1
print("Bye") Infinite loop
5 4 3 2 1 Bye
Visualizing your Python code with "Python Tutor
Sentinel loop #What is the output if the user
#What is the output if the user #What is the output if the user
enters 5,10,-10,0 enters 5,10,-10,0
enters 5,10,-10,0 x= int(input("Enter a number:"))
x= int(input("Enter a number:")) x= int(input("Enter a number:"))
s=0 s=0
s=0 while x!=0:
while x!=0: while x!=0:
s=s+x s=s+x
s=s+1 x= int(input("Enter a number:"))
x= int(input("Enter a number:")) print("s=",s)
print("s=",s)
print("s=",s)
Infinite loop
s= 5
s= 3 #What is the output if the user enters
#What is the output if the user #What is the output if the user enters 5,10,-10,20,0
enters 5,10,-10,0 5,10,-10,0
x= int(input("Enter a number:")) s=0
s=0 s=0 x= int(input("Enter a number:"))
while x!=0: while x!=0:
x= int(input("Enter a number:")) x= int(input("Enter a number:")) while x>0:
s=s+x s=s+x s=s+x
print("s=",s) print("s=",s) x= int(input("Enter a number:"))
print("s=",s)
s= 0
NameError: name 'x' is not defined s= 15
Practice more
num = 0 num = 1 num = 1
while num<=4: while num<=10: while num<=10:
if num==0: if num==1 or num==2: if num==1 or num==2:
print("zero") print(num,"A") print(num,"A")
elif num==2: elif num==4 and num==8: if num==4 and num==8:
print("two") print(num,"B") print(num,"B")
elif num==3: elif num==10: if num==10:
print("three") print(num,"C") print(num,"C")
else: else: else:
print(num) print(num,'D') print(num,'D')
num +=1
num = num * 2 num = num * 2
zero 1A
1 2A 1A
two 4D 1D
three 8D 2A
4 2D
4D
8D