In [ ]:
In [5]:
for letter in 'Python': # First Example
print 'Current Letter :', letter
fruits = ['banana', 'apple', 'mango']
for fruit in fruits: # Second Example
print 'Current fruit :', fruit
print "Good bye!"
Python supports an else statement associated with a loop statement
In [6]:
for num in range(10,20): #to iterate between 10 to 20
for i in range(2,num): #to iterate on the factors of the number
if num%i == 0: #to determine the first factor
j=num/i #to calculate the second factor
print '%d equals %d * %d' % (num,i,j)
break #to move to the next number, the #first FOR
else: # else part of the loop
print num, 'is a prime number'
In [9]:
i = 2
while(i < 100):
j = 2
while(j <= (i/j)):
if not(i%j):
break
j = j + 1
if (j > i/j) :
print i, " is prime"
i = i + 1
print "Good bye!"
In [10]:
count = 0
while (count < 9):
print 'The count is:', count
count = count + 1
print "Good bye!"
In [11]:
count = 0
while count < 5:
print count, " is less than 5"
count = count + 1
else:
print count, " is not less than 5"
In [12]:
for i in range(2):
print(i)
else:
print('completed for-loop')
In [13]:
for i in range(2):
print(i)
break
else:
print('completed for-loop')
In [14]:
i = 0
while i < 2:
print(i)
i += 1
else:
print('in else')
In [15]:
i = 0
while i < 2:
print(i)
i += 1
break
else:
print('completed while-loop')
In [ ]:
# don't run this code
# flag = 10
#while (flag): print 'Given flag is really true!'
#print "Good bye!"
In [22]:
a_list=[0,1,2,3,4,5]
try:
print('first element:', a_list[0])
except IndexError:
print('raised IndexError')
else:
print('no error in try-block')
In [23]:
try:
print('third element:', a_list[2])
except IndexError:
print('raised IndexError')
else:
print('no error in try-block')