while loop, for loop, Range function
Loops in Python help us run the same block of code multiple times. We
use them to repeat tasks without rewriting code, making the program
shorter, faster, and easier to manage.
while loop
A while loop repeats as long as a certain condition is True. It is best used when you don't know
exactly how many times the loop will run. Its syntax is:
Initialization
while(condition):
Statement1
Statement2
.....
StatementN
Increasing or Decreasing of Variable used to check the condition
e.g.
count = 1
while (count <= 5):
print(count)
count += 1
# Crucial: If you forget to increment, the loop runs forever forming a deadlock!
NOTE: here all set of instructions of ‘while’ loop have equal indentation (i.e. whitespaces)
for loop
A ‘for’ loop is used for iterating over a sequence (like a list, a
tuple, a dictionary, a set, or a string) OR iterating with in the
range of values according to the ‘range()’ function. It is best used
when you know about the values you want to access or you know how many
times you want to repeat the code.
i) Iterating over a sequence (by using string)
Syntax is:
for VariableName in RangeOfValues:
Statement1
Statement2
....
StatementN
e.g.
str1 = "I am doing my BCA from GEHU Dehradun"
for v1 in str1:
print(v1)
In ouput it will print each and every character (considering it as
value) present in the str1 variable.
Once you are capable of accessing the value, now you may use them for
any processing (counting, comparing, printing, and more) according to
questions asked to you.
Question: Ask user to enter any string. Now make a python program to
count total number of words present in it.
Questions: Ask user to enter any string. Now write a python script to
count the total number of vowels and consonants present in it.
ii) iterating within range of values (range() function)
To loop through a set of code a specific number of times, we use
range(). It has following syntax:
range(StartValue, EndValue, StepValue)
NOTE the following rules:
a) if StartValue < EndValue
Then range() will provide values from StartValue to EndValue – 1
b) if StartValue > EndValue
Then range() will provide values from StartValue to EndValue + 1
Apart from it, values are selected from the range of values based on
the StepValue, which may have positive as well as negative value.
e.g.
for v1 in range(1, 10, 1):
print(v1, end=" ")
print("")
for v1 in range(10, 1, -1):
print(v1, end=" ")
Output:
1 2 3 4 5 6 7 8 9
10 9 8 7 6 5 4 3 2
NOTE:
range(5) represent it is EndValue, here by default StartValue will be
0 and StepValue will 1, so range will be from 0 to 4.
range(2, 6) generates numbers from 2 to 5, considering by default
value of StepValue as 1.
range(2, 30, 3) generates numbers from 2 to 29, incrementing by 3. So
StepValue will be any value, 1 is a default value if nothing is given
as StepValue.
Loop Control Statements
Statement What it does
Stops the loop entirely when the condition is True. However, the
break
statements written before it will execute for that iteration
When the condition is True, it Skips the current iteration (skip only
continue those statements which are written after ‘continue’ keyword) and
moves to the next iteration.
pass A placeholder (does nothing)
e.g.
for num in range(1, 100):
if num == 50:
break # Loop stops at 5
if num % 2 == 0:
continue # Skip even numbers
print(num, end=" ")
Output:
1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49
Similar to nested if – elif – else statment, we can use nested loops
also i.e. using a loop inside another loop. For example,
a python program to find all prime numbers between first 100 natural
number
print("Prime numbers between 1 and 100 are:")
for num in range(1, 101):
# Prime numbers must be greater than 1
if num > 1:
for i in range(2, num):
if (num % i) == 0:
# If a divisor is found, it's not prime
break
else:
# If the loop finished without hitting 'break', it's prime
print(num, end=" ")
Output:
Prime numbers between 1 and 100 are:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
Loop with else
This is a unique concept in Python, you can use an else block after a loop. The else block runs
only if the loop finished naturally (i.e., it didn't execute a ‘break’ statement).
e.g.
for i in range(3):
if i == 5:
break # STOP THE LOOP
print(i)
else:
print("Loop finished!") # THIS WILL NOT RUN
Output:
0
1
2
Loop finished!
e.g.
for i in range(3):
if i == 2:
break # here ‘break’ statement will STOP THE LOOP
print(i)
else:
print("Loop finished!") # so this statement will not run
Output:
0
1
NOTE: The loop-else block is perfect for Search Operations. Suppose
you are checking a list for a specific item. You want to print a
message only if the item was not found. We may use it with ‘while’
loop also.
e.g.
i = 1
target = 6
while i <= 5:
if i == target:
print("Found the target value! Breaking the loop.")
break
print("Checking", i, "...")
i += 1
else:
print("Target not found.")
# This will NOT run because we get the value and ‘break’ is executed
Output:
Checking 1 ...
Checking 2 ...
Checking 3 ...
Checking 4 ...
Checking 5 ...
Target not found.
Questions: Consider that the username “abc” has password “12345”. Now write a
python program to ask user to enter their login details and check if they entered
the correct values or not. If not then print message that their account is locked
due to 3 failed login attempts.