Learn Python – Iteration (for loop, while loop)

In my previous post variables and conditional statement covered.

Now let’s see Iteration (for loop, while loop)

So many ways I can use for loop

I can iterate through string like this

for character in “Nikhil”:

      print character

Output:
N

i

k

h

i

l

Also, I can iterate through an array

numbers = [1,2,3,4,5,6,7,8,9,0]
for number in numbers:

     print number

Output:
1

2

3

4

5

6

7

8

9

0

Now suppose I want to iterate between range from 4 to 11, then in python its very easy

for number in range(4,11):

print number

Output:

4

5

6

7

8

9

10

11

Hmm.. this is really cool. Lets look at while

number = 4

while number <=11:

        print number

number += 1

Output:

4

5

6

7

8

9

10

11

I am trying while with boolean. Yes its simple and expected

student_passed = true

while student_passed:

     print(“Congratulations!!!”)

Also published on Medium.

Leave a Reply

Your email address will not be published. Required fields are marked *