Learning Python: Loops
#1. loop through an array
fruits = ["apple", "banana", "cherry", "dragon fruit"]
print("Example 1: Printing Fruits")
for x in fruits:
print(x)
Notice there is no begin and end blocks! Indenting implies a block has begun
#2. Loop through a string
a_fruit = "banana"
print("Example 2: Banana in loop")
for x in a_fruit:
print(x)
#3. Break a loop
print("Example 3: Break example")
print("Fruit Array has these values {0}\n\n".format(fruits))
#^^^^ string interpolation
print("If we are going to break at banana we only"\
"should be printing an apple\n")
#^^^^ statements that span across multiple lines have backslash
for x in fruits:
if x == "banana":
break
print(x)
#4 For i = 1 to 10
print("Prining Numbers from 1 to 10")
for x in range(10):
print(x)
print("ooops... :-)")
print("\n let's try again")
for x in range(1, 10):
print(x)
print("oopss... :-(")
print("\n let's try again")
for x in range(1, 11):
print(x)
print("Yay! Can you give my computer science engineering certificate")
print("\n. Print odd numbers")
for x in range(1, 11, 2):
print(x)
print("\n. Print even numbers")
for x in range(0, 11, 2):
print(x)