Python for Loop
What is for loop in Python?
The for loop in Python is used to iterate
over a sequence (list, tuple, string) or other iterable
objects. Iterating over a sequence is called traversal.
Syntax of for Loop
for val in sequence:
Body of for
Here,
val is the variable
that takes the value of the item inside the sequence on each iteration.
Loop continues until we reach the last item
in the sequence. The body of for loop is separated from the rest of the code
using indentation.
Example: Python for Loop
# Program to find the sum of all numbers stored in
a list
# List of numbers
numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]
# variable to store the sum
sum = 0
# iterate over the list
for val in numbers:
sum
= sum+val
# Output: The sum is 48
print("The sum is", sum)
The range() function
We can generate a sequence of numbers
using
range() function. range(10) will generate
numbers from 0 to 9 (10 numbers).
We can also define the start, stop and step
size as
range(start,stop,step size). step size defaults to
1 if not provided.
This function does not store all the values
in memory, it would be inefficient. So it remembers the start, stop, step size
and generates the next number on the go.
To force this function to output all the
items, we can use the function
list().
The following example will clarify this.
# Output: range(0, 10)
print(range(10))
# Output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(list(range(10)))
# Output: [2, 3, 4, 5, 6, 7]
print(list(range(2, 8)))
# Output: [2, 5, 8, 11, 14, 17]
print(list(range(2, 20, 3)))
We can use the range()
function in for loops to iterate through a sequence of numbers. It can be
combined with the
len() function to
iterate though a sequence using indexing. Here is an example.
# Program to iterate through a list using indexing
genre = ['pop', 'rock', 'jazz']
# iterate over the list using index
for i in range(len(genre)):
print("I
like", genre[i])
When you run the
program, the output will be:
I like pop
I like rock
I like jazz
for loop with else
A for loop can have an
optional else block as well. The
else part is executed
if the items in the sequence used in for loop exhausts.
break statement can be
used to stop a for loop. In such case, the else part is ignored.
Hence, a for loop's else
part runs if no break occurs.
Here is an example to
illustrate this.
digits = [0, 1, 5]
for i in digits:
print(i)
else:
print("No items left.")
When you run the
program, the output will be:
0
1
5
No items left
Python
Nested For Loops
Loops defined within another Loop are called Nested Loops. Nested
loops are used to iterate matrix elements or to perform complex computation.
When an outer loop contains an inner loop in its body it is called
Nested Looping.
Python Nested For Loop
Syntax
for <expression>:
for <expression>:
Body
Example
for i in range(1,6):
for j in range (1,i+1):
print i,
print
Output
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
Python while Loop
What is while loop in Python?
The while loop in Python
is used to iterate over a block of code as long as the test expression
(condition) is true.
We generally use this
loop when we don't know beforehand, the number of times to iterate.
Syntax of
while Loop in Python
while test_expression:
Body of while
In while loop, test
expression is checked first. The body of the loop is entered only if the
test_expression evaluates to True. After one iteration,
the test expression is checked again. This process continues until the test_expression evaluates to False.
In Python, the body of
the while loop is determined through indentation.
Body starts with
indentation and the first unindented line marks the end.
Python interprets any
non-zero value as
True. None and 0 are interpreted
as False.
Example: Python
while Loop
# Program to add natural
# numbers upto
# sum = 1+2+3+...+n
# To take input from the user,
# n = int(input("Enter n: "))
n = 10
# initialize sum and counter
sum = 0
i = 1
while i <= n:
sum = sum
+ i
i =
i+1 # update counter
# print the sum
print("The sum is", sum)
When you run the
program, the output will be:
Enter n: 10
The sum is 55
In the above program,
the test expression will be
True as long as our
counter variable iis less than or equal
to n (10 in our program).
We need to increase the
value of counter variable in the body of the loop. This is very important (and
mostly forgotten). Failing to do so will result in an infinite loop (never
ending loop).
Finally the result is
displayed.
while loop with else
The
else part is executed
if the condition in the while loop evaluates to False.
The while loop can be
terminated with a break statement. In such case, the
else part is ignored.
Hence, a while loop's else part runs if no
break occurs and the condition is false.
Here is an example to
illustrate this.
# Example to illustrate
# the use of else statement
# with the while loop
counter = 0
while counter < 3:
print("Inside loop")
counter = counter + 1
else:
print("Inside else")
Output
Inside loop
Inside loop
Inside loop
Inside else
Here, we use a counter
variable to print the string
Inside loop three times.
On the forth iteration,
the condition in while becomes
False. Hence, the else part is executed.
No comments:
Post a Comment