Introduction
to
IT 163
Computer
Programming 2
[Link]
Loop
❑ A loop refers to the process of executing a
block of code repeatedly until a specified
condition is met.
3 types of Control Flow Statement
1. While Loop
2. For Loop
3. Nested For Loop
[Link]
While Loop
1. Understanding While Loop
2. ELSE in While Loop
3. Using WHILE Loop in Collections
4. Using BREAK Keyword in While Loop
5. CONDITIONS in While Loop
[Link]
While Loop
❑ The condition is evaluated. If the condition is
❑ A while loop is a control flow statement that allows you true, the code block inside the loop is
to repeatedly execute a block of code as long as a executed.
specified condition is true.
❑ After executing the code block, the condition is
❑ The while loop evaluates the condition before executing evaluated again.
the block of code, and it continues to execute the
block as long as the condition remains true.
❑ If the condition is still true, the code block is
executed again.
SYNTAX
❑ This process continues until the condition
becomes false. Once the condition is false, the
[Link]
while loop terminates, and the program
continues with the code following the loop.
Here's an example to illustrate the usage of
while loop:
❑ Initialization: The variable age is initialized with the
value 12.
❑ Loop Condition: The while loop continues to execute
as long as the condition age < 18 is true, indicating that
the person is younger than 18 years old.
❑ Loop Body: Inside the loop, the program prints the
message "Still Young:" along with the current value of
age. It then increments the value of age by 1.
❑ Loop Termination: Once the value of age becomes
[Link]
equal to or greater than 18, the condition age < 18
becomes false, and the loop terminates.
ELSE in While Loop
❑ Else statement can be used in conjunction with a while
loop to execute a block of code when the loop
condition becomes false. The else block is executed
after the loop completes all its iterations, assuming it SYNTAX
hasn't been terminated early by a break statement.
❑ The else block is optional and is executed after the
loop completes all its iterations. It won't be executed if
the loop is terminated by a break statement.
❑ The else block in a while loop is commonly used for
tasks such as finalizing operations, executing cleanup
[Link]
code, or performing additional actions after the loop
has finished its iterations.
Here's an example to illustrate the usage of while loop
in collection using conditional statements:
❑ Condition: The while loop continues to run as
long as index is less than the length of the
numbers list (which is 10).
❑ len(numbers) gives the length of the list, which is
10, so the loop will continue as long as index is
less than 10.
❑ In the first iteration, index = 0, so the condition
0 < 10 is True, and the loop will run.
❑ In the first iteration, index = 0, so
numbers[index] refers to the first element of the
❑ numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]: This defines a list named numbers
list, which is numbers[0] = [Link] condition
that contains the integers from 1 to [Link] are the values we will be
checks if numbers[0] (which is 1) is divisible by 2
working with inside the while loop index = 0: The index variable is
(numbers[0] % 2 == 0). Since 1 is not divisible by
initialized to 0. This variable is used to keep track of the current position
[Link]
2, the condition evaluates to False.
(or index) in the numbers list during the iteration.
Here's an example to illustrate the usage of else
in a while loop:
❑ Initialization: We start by initializing a
variable x with the value 5: x = 5.
❑ Condition Evaluation: The while loop begins
by evaluating the condition x > 0. Since x is
initially 5, which is indeed greater than 0, the
condition is true, and the loop's body is
executed.
❑ Loop Body Execution: Inside the loop's
body, the current value of x (which is 5 in
the first iteration) is printed to the console
[Link]
using the print() function. So, 5 is printed.
Here's an example to illustrate the usage of else
in a while loop:
❑ Loop Continuation: After executing the loop body,
the control returns to the top of the loop, and the
condition x > 0 is evaluated again. Since x is still
greater than 0 (i.e., 4), the loop continues to execute.
❑ Repeating the Process: Steps 3 to 5 are repeated in
each iteration of the loop: printing the current value
of x, decrementing x by 1, and evaluating the
condition.
❑ Termination: This process continues until the
condition x > 0 becomes false. After the value of x
reaches 0, the condition x > 0 evaluates to false. At
[Link]
this point, the loop terminates, and the control moves
to the next statement after the loop.
Here's an example to illustrate the usage of else
in a while loop:
❑ In this example, the while loop decrements
the value of x from 5 to 1 and prints each
value. After the loop completes its
iterations and the condition becomes false
(x <= 0), the else block is executed,
printing "Loop terminated normally".
❑ If the loop were terminated prematurely by
a break statement, the else block would
not be executed.
[Link]
Break Statement and Conditional Statements in
While Loop
❑ The while keyword is used to start the while
❑ The break statement is used to exit or terminate a loop loop, followed by the loop condition.
prematurely, before its normal termination condition is ❑ Within the loop, you have a code block that
met. When encountered within a loop (such as a for gets executed as long as the loop condition
loop or a while loop) evaluates to True.
❑ Inside the loop, there's an optional
❑ The break statement causes the program to conditional statement (often an if statement)
immediately exit the loop and continue executing the
that checks for a specific condition.
next statement after the loop.
❑ If the condition specified in the if statement
SYNTAX evaluates to True, the break statement is
executed.
❑ The break statement causes an immediate
[Link]
exit from the loop, skipping any remaining
iterations, and the program continues
executing the code after the loop.
Here's an example to illustrate the usage of
break statement in while loop:
❑ Initialization: x is initialized with the value 1.
This variable will be used as a counter to
track the current iteration of the loop.
❑ While Loop: The while loop continues as long
as the condition x <= 10 is True.
❑ Inside the loop: The current value of x is
printed using the print() function.
❑ An if statement checks if x is equal to 5.
❑ If x is equal to 5, the break statement is
executed, causing an immediate exit from the
loop.
❑ If x is not equal to 5, x is incremented by 1
[Link]
using the statement x += 1.
Here's an example to illustrate the usage of
break statement in while loop:
❑ Loop Ending: Once the loop terminates
(either by encountering a break statement or
when the condition x <= 10 becomes False),
the program continues executing the next
statement after the loop.
❑ In this case, the statement print("Loop
ended") is executed, which prints "Loop
ended" to the console.
[Link]
Here's an example to illustrate the usage of
break statement in while loop:
❑ Output: The output of the code is the
sequence of numbers from 1 to 5, followed by
the message "Loop ended".
❑ The loop terminates prematurely when x is
equal to 5 because the break statement is
executed at that point, causing the loop to
exit immediately.
[Link]
For Loop
❑ A for loop is a control flow statement that iterates
over a sequence of elements. It allows you to
execute a block of code multiple times, once for
each item in the sequence.
❑ The sequence can be a list, tuple, string, dictionary,
or any other iterable object.
SYNTAX
[Link]
For Loop in Collections
❑ For Loop can be used to access every item in a
COLLECTION (Lists & Tuples) in a very easy way.
❑ This loop iterates over the elements of the
list my_list and prints each number on a
separate line. The loop will execute 5
times, once for each element in the list.
[Link]
For Loop in Collections using Conditional Statement
and Break Statement
❑ Firstly, we create a list called fruits containing
three items: "banana", "apple", and "orange".
❑ Then, it uses a for loop to iterate over each item
in the list.
❑ For each iteration, it prints the current fruit from
the list. If it encounters the fruit "apple", the loop
will stop (using the break statement).
❑ The name of the variable used in the for loop (like
fruit_basket in the example) can be anything. It
is just a placeholder that represents each item in
the list as the loop iterates through it.
❑ You can change the name of this variable to
[Link]
anything you like, and the code will still work the
same.
For Loop in Collections using Conditional Statement
and Break Statement
❑ This code prints all even numbers starting
from the adjusted start value up to stop. If
stop is also even and greater than start, it
prints stop at the end. The logic ensures
the loop starts with an even number and
prints even numbers only.
[Link]
Range in For Loop
❑ range() function is often used in conjunction with for
loops to generate a sequence of numbers. It's a built-in ❑ start (optional): The starting value of the
function that creates an immutable sequence of sequence (inclusive). If omitted, it defaults
numbers starting from 0 (by default) up to but not to 0.
including a specified endpoint. ❑ stop: The ending value of the sequence
(exclusive). This is the value at which the
SYNTAX sequence stops generating numbers.
❑ step (optional): The step or increment by
which the sequence advances. If omitted,
it defaults to 1.
[Link]
Here's an example of using range()
with a for loop:
❑ start (optional): The starting value of the
sequence (inclusive). If omitted, it defaults
to 0.
❑ stop: The ending value of the sequence
(exclusive). This is the value at which the
sequence stops generating numbers.
❑ step (optional): The step or increment by
which the sequence advances. If omitted,
it defaults to 1.
[Link]
Here's an example of using range()
with a for loop:
❑ start (optional): The starting value of the
sequence (inclusive). If omitted, it defaults
to 0.
❑ stop: The ending value of the sequence
(exclusive). This is the value at which the
sequence stops generating numbers.
❑ step (optional): The step or increment by
which the sequence advances. If omitted,
it defaults to 1.
[Link]
Nested for Loop
Outer for loop: for x in range(3):
❑ A nested for loop in Python is a loop inside another loop. The
inner loop is executed completely every time the outer loop is
This line sets up the outer loop. It will go
executed once.
through each number from 0 to 2 one by one."
❑ This structure is useful for iterating over multi-dimensional data
range(3): This part creates a list of numbers:
structures such as lists of lists or matrices.
[0, 1, 2]. It means we'll use these three
numbers in our loop.
Iteration: The variable x will take each number
from the list, one at a time. First, x will be 0,
then x will be 1, and finally, x will be 2. The loop
[Link]
runs three times in total, once for each number.
Nested for Loop
Inner for loop: for y in range(3):
Purpose: This line sets up the inner loop, which is
inside the outer loop. Every time the outer loop runs
once, the inner loop will run through all its steps
completely.
range(3): Just like in the outer loop, this part
creates a list of numbers: [0, 1, 2]. It means the
inner loop will use these three numbers.
Iteration: The variable y will take each number from
the list, one at a time. For every single number that x
(from the outer loop) takes, y will go through 0, 1,
[Link]
and 2. So, for each value of x, the inner loop runs
three times.
Nested for Loop
The outer loop starts with x = 0.
Finally, the outer loop runs with x = 2.
For x = 0, the inner loop runs with y = 0, y = 1, and y = 2. During these iterations,
For x = 2, the inner loop runs with y = 0, y = 1, and y =
the output will be:
2. The output will be:
The outer loop then proceeds with x = 1.
For x = 1, the inner loop again runs with y = 0, y = 1, and y = 2. The output will be:
[Link]
Using Range in Nested for Loop
❑ Basic Usage of range
Range with One Argument:
❑ The range function in Python is used to generate a
sequence of numbers, which can be used in a for loop Generates numbers from 0 up to (but not
to iterate over a specific range of values. including) the given number.
❑ Here’s how to use the range function in different
scenarios:
[Link]
Using Range in Nested for Loop
❑ Range with Two Arguments: ❑ Range with Three Arguments:
Generates numbers from the first argument up to (but Generates numbers starting from the
not including) the second argument. first argument, up to (but not including)
the second argument, incrementing by
the third argument.
[Link]
Using Range in Nested for Loop
❑ Range with Negative Step: ❑ Iterating Over a List Using range:
Generates numbers in reverse order when the step is When you need to access the index of
negative. elements in a list.
[Link]
End Parameter
❑ end parameter is used in the print() function to
❑ value: The value(s) to be
specify what should be printed at the end of the
printed.
output.
❑ sep: The separator between
multiple values (default is a
❑ By default, the print() function ends with a
space).
newline character (\n), which means that each
❑ end: The string appended after
call to print() will start on a new line.
the last value (default is a
newline).
❑ However, you can change this behavior by
specifying a different value for the end parameter.
[Link]
End Parameter
❑ end parameter is used in the print() function to
❑ value: The value(s) to be
specify what should be printed at the end of the
printed.
output.
❑ sep: The separator between
multiple values (default is a
❑ By default, the print() function ends with a
space).
newline character (\n), which means that each
❑ end: The string appended after
call to print() will start on a new line.
the last value (default is a
newline).
❑ However, you can change this behavior by
specifying a different value for the end parameter.
[Link]
One-dimensional Collections
❑ A one-dimensional collection is a list, array, or tuple that
holds a sequence of values along a single dimension.
❑ When we say one-dimensional collections, we have a simple ❑ The loop (for number in numbers) iterates
list of integers or strings. We can access any element in over each element in the list numbers.
the list using a single index. ❑ The print(number) statement prints each
element in the list.
[Link]
Two-dimensional Collections using
Nested For Loop
❑ A two-dimensional collection is like a table or a spreadsheet
that has rows and columns to store information. It's a special ❑ The outer loop (for row in matrix) iterates
kind of collection that has only two dimensions. over each sublist in matrix.
❑ The inner loop (for element in row) iterates
Example: Reading a Two-Dimensional List (List of Lists) over each element in the current sublist
(row).
❑ The print(element, end=' ') statement
prints each element in the current row on
the same line, separated by a space.
❑ The print() statement outside the inner
loop but inside the outer loop prints a
newline character after each row to format
the output correctly.
[Link]
Reading Multi-dimensional Collection using
Nested For Loop
❑ For a more complex structure, such as a multidimensional
❑ The outermost loop (for matrix in tensor)
list, the same principle applies, but you add another nested
iterates over each 2D list within the 3D list.
loop:
❑ The middle loop (for row in matrix) iterates over
Example: Reading a Multi-Dimensional List (List of Lists) each sublist within the current 2D list.
❑ The innermost loop (for element in row) iterates
over each element within the current sublist.
❑ The print(element, end=' ') statement prints
each element in the current row on the same
line.
❑ The print() statement after the innermost loop
prints a newline character after each row.
❑ The print() statement after the middle loop
prints an extra newline character to separate
[Link]
different 2D lists (matrices).
Thank you!
[Link]