Python : Crash Course Part 10 – Loops

Lets first create a sequence and use a FOR loop to print the elements in a sequence, that way it is easy to understand the looping concepts.

In [1]:seq=[1,2,3,4]
In [2]:for item in seq:
           print(item)
1
2
3
4

The temporary variable name ( item ) as shown above can be changed to num / any other variable name of your choice, it wouldn’t matter for python. So make a good choice of your own while choosing the temporary variable names.

In [3]:seq=[1,2,3,4]
In [4]:for item in seq:
           print('hello')
hello
hello
hello
hello

The above code printed hello for every element in our sequence. Lets now discuss the WHILE loop in python.

In [5]:i = 1
       while i < 5:
           print('i is : {}'.format(i))
           i=i+1
i is : 1
i is : 2
i is : 3
i is : 4

The above loops executes printing until the condition happens to be true. You can try some more examples on your own and let me know in the comments.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s