python for and while loop examples

Python has the for in syntax for for loop.
[code language=”python”]
#! /usr/bin/env python

print "Using for loop to print each letter from a string:"
for letter in "Python":
print letter

print "Using for loop to print the array elements:"
names = ["Amy","Ben","Carl"]
for a in names:
print a

print "Using for loop and using the array index to print array elements:"
fruits = [‘apple’, ‘banana’, ‘cherry’]
for index in range(len(fruits)):
print fruits[index]

print "while loop:"
a = 0
while a < 5:
a = a + 1
print "Loop: ", a
[/code]

Output:
[code language=”text”]
Using for loop to print each letter from a string:
P
y
t
h
o
n
Using for loop to print the array elements:
Amy
Ben
Carl
Using for loop and using the array index to print array elements:
apple
banana
cherry
while loop:
Loop: 1
Loop: 2
Loop: 3
Loop: 4
Loop: 5
[/code]

Search within Codexpedia

Custom Search

Search the entire web

Custom Search