Milandeep Bassi

Using For Loops and While Loops in Python Programming

21st, January, 2020


While Loops

A while loop is one way of repeating some code. A while keyword is followed by True or False values. The expressions thats value is equal to True or False is called a Boolean. An example of a while loop is below.

Print the numbers 1 to 100:

Without loop:

print ( 1 )
print ( 2 )
print ( 3 )
...

With loop:

x = 0
while x < 100:
x = x + 1
print ( x )

This code segment is a lot more efficient and less work than writing the first 100 out line by line. The expression followed by a while loop must evaluate to a Boolean data type of either True or False. An indent of the code after the : must always occur. The code indented will only execute if the program returns a value of True from the Boolean

while <expression>:
statement
statement

In Python for Boolean's we have some operators that can help. Comparison operators are as follows. == (Equal to), <= (Less than or equal to), < (Less than), >= (Greater than or equal to), > (Greater than), != (Not equal to).


For Loops

Another type of loop in Python is the For loop. The for loop continues going over the elements in a finite list of values. The structure of the loop is outlined below. 

for <element> in <list>:
statement
statement

A for loop must always follow the structure outlined above. The <list> area can be filled with usage of a range(x, x) list. This will instruct the programme to continue until the range of times the loop has been asked to run for has been fulfilled. We can also use a list in place of the area by defining [1,2,3]. Examples of for loops can be seen below.

for number in [1,2,3]
print (number)
1
2
3

for number in range(1, 5):
print (number)
1
2
3
4

As before see how when using the range command it goes up to 5 but not 5.