lfalanga
12/17/2019 - 2:00 AM

For / Else loop in Python

# Example 1: Simple For / Else loop
fruits = ['banana', 'apple', 'orange', 'tomato', 'pear', 'grape']

print 'You have...'
for f in fruits:
  if f == 'tomato':
    print 'A tomato is not a fruit!' # (It actually is.)
    break
  print 'A', f
else:
  print 'A fine selection of fruits!'

# Example 2: Removing unexpected values in list
fruits = ['banana', 'apple', 'orange', 'tomato', 'pear', 'grape']

print 'You have...'
for f in fruits:
  if f == 'tomato':
    print 'A tomato is not a fruit!' # (It actually is.)
    fruits.remove(f)
  print 'A', f
else:
  print 'A fine selection of fruits!'

# Example 3: Printing out even numbers
numbers = [2, 4, 6, 8, 10, 11, 12]
 
print 'Even numbers in list...'
for n in numbers:
  if n % 2 != 0:
    print '%s is not an even number!' % n
    break
  print n
else:
  print 'A fine selection even numbers!'