Quantcast
Channel: Linux Candy » Mr Spark
Viewing all articles
Browse latest Browse all 10

Looping and Iterations in Python

$
0
0

Lets enter into the one of the most important topics in python: Looping. Looping or Iteration means repetition of a certain part of code for a number of times until a condition is met(till condition set of loops has true).

First of these looping constructs is for: iterates through the items in the sequence, and second is while: a general loop to be precise.

The for loop:

Definition: for loop has an ability to iterate through the items present in the sequence, where a sequence can be a list, tuple , etc. and iterates until the condition set in the loop is true.

Syntax:

for iterating_var in sequence:
   block of codes

Each items present in the sequence is assigned to iterating_var and the block of codes present in the loop is executed until all the items in the sequence is used.

Example 1):

>>> for x in 'Its W0rk!ng!?':
	print x

I
t
s

W
0
r
k
!
n
g
!
?

In the above example ‘Its W0rk!ng!?’ is a sequence of characters: String to be exact. Each characters in the string is assigned to x and is printed with a newline characters by default.

2)

>>> scientist=['Einstein','Newton','Franklin','Darwin']
>>> for person in scientist:
 print `person`

'Einstein'
'Newton'
'Franklin'
'Darwin'

Here scientist is the list of names of few scientists, which are being assigned to person and printed until the list is exhausted.

Its time to introduce another function: range()

The range function uses two arguments like this range(start, finish). start is the first number that is produced. finish is one larger than the last number.

>>> range(1,10) [1, 2, 3, 4, 5, 6, 7, 8, 9]

Example:

>>> for x in range(1,10):
	print x
1
2
3
4
5
6
7
8
9

Here, x is assigned all the items present in the list ranging from 1 to 10 but excludes 10 in the execution and prints out the list.


The while loop:

A while statement repeatedly executes a block of code(indented one) till the expression at the top results into true. When the condition set in the expression becomes false, then the control passes to the statement the follows the while block.

Syntax:

while expression:
   block of code

Example:

1)CODE:

count=0
while (count<10):
    count = count +1
    print count

OUTPUT:

1
2
3
4
5
6
7
8
9
10

2)CODE:

string=['c','C++','Python','Scripting']
index=0
while (index < len(string)):
    print 'I work on '+string[index]
    index=index+1

OUTPUT:

I work on c
I work on C++
<pre>I work on Python
I work on Scripting

3)

>>> while True:
	print('Type Ctrl-C to stop me!')

LOOP controls

After working on loops, we might have situation where have to exit a loop completely, skip statement and start with another. Here Python provides break and continue statement to achieve the above said.

In certain cases, where we have to choose which block of statements to execute at that time, we might need the help of else statements.

The break statement:

Using break statement, we can come out of the current loop and execute the next set of statements.

break statement are used mostly in for and while loops.

Example:

CODE:

while True:
    menu=input("\nMENU:\n1.NAME\n2.EXIT\nEnter a number:")
    if menu==1 :
        name=raw_input('Enter your name:')
        pro=raw_input('Enter which Language you work on:')
        print 'Welcome, '+name+' . You work on ' + pro+' !! Nice :) '
    else:
        break
print 'Your are out of loop now!!'

OUTPUT:

MENU:
1.NAME
2.EXIT
Enter a number:1
Enter your name:Mr.Spark
Enter which Language you work on:Python
Welcome, Mr.Spark . You work on Python !! Nice :) 

MENU:
1.NAME
2.EXIT
Enter a number:1
Enter your name:Cemicolon
Enter which Language you work on:Python and C
Welcome, Cemicolon . You work on Python and C !! Nice :) 

MENU:
1.NAME
2.EXIT
Enter a number:2
Your are out of loop now!!

The continue statement:

The continue statement transfers the control to the beginning of the loop and skips all the statements under it, of the current iteration of the loop.

Example:

CODE:

for letter in <strong>'Python'</strong>:     # First Example
   if letter == 'h':
      continue
   print 'Current Letter :', letter

OUTPUT:

Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : o
Current Letter : n

The pass Statement:

The pass statement is null operational statement, which does nothing. We get situation where syntactically some code must be placed, but at that moment you have nothing to put here a pass statement is used to do nothing.

Example:

CODE:

for letter in <strong>'Python'</strong>:
   if letter == 'h':
      <strong>pass</strong>
      print 'This is pass block'
   print 'Current Letter :', letter

OUTPUT:

Current Letter : P
Current Letter : y
Current Letter : t
This is pass block
Current Letter : h
Current Letter : o
Current Letter : n

The else Statement Used with Loops

This else statement functions same while it was used in if clause, but with few changes on how it is executed.

for loop: If the else statement is used with a for loop, the else statement is executed when the loop has exhausted iterating the list.
while loop: If the else statement is used with a while loop, the else statement is executed when the condition becomes false.


Viewing all articles
Browse latest Browse all 10

Latest Images

Trending Articles





Latest Images