LOOPS IN PYTHON
WHILE AND FOR LOOP
What is Loops?
Loops are statements in computer programming that
executes an statement repeatedly until the given
condition reach.
Some loops are responsible in getting the
items/elements in a list, tuples and dictionaries in
python.
The WHILE Loop
The while statement in Python is one of most general
ways to perform iteration. A while statement will
repeatedly execute a single statement or group of
statements as long as the condition is true.
The reason it is called a 'loop' is because the code
statements are looped through over and over again
until the condition is no longer met.
Syntax of WHILE Loop
initialization
TS N S
while test/condition:
U TIO
CO EN
N
code statement
D
IN
ULCV
TS N S
U TIO
else:
CO EN
N
D
final code statement
IN
Sample Program
break, continue & pass statements inside Loop
break: Breaks out of the current closest enclosing
loop.
continue: Goes to the top of the closest enclosing
loop.
pass: Does nothing at all.
Thinking about break and continue statements, the general
format of the while loop looks like this:
For Loops
A for loop acts as an iterator in Python; it goes
through items that are in a sequence or any other
iterable item.
Objects that we've learned about that we can iterate
over include strings, lists, tuples, and even built-in
iterables for dictionaries, such as keys or values.
Syntax of For Loop
list
for item in object:
statement to do stuff
Example Code of For Loop
Example Code of For Loop
Range Function
allows you to quickly generate a list of integers, this
comes in handy a lot, so take note of how to use it!
There are 3 parameters you can pass, a start, a stop,
and a step size.
range(start,stop,step_size)