{{tag>projects cloud club computing virtualization machines VMs AWS Azure GCP}}
[[python_club|About the Club]]\\
==== Python Club Topics - Loops ====
==== Loops ====
- whiile loops
- Execute a set of statements for as long as a condition evaluates to true
- for loops
- Used for iterating over a sequence ( eg. list, tuple, dictionary, set, or a string )
==== while loop examples ====
- This condition always evaluates to True, so will continue forever
i = 0
while True:
i += 1
print("keep going... " + str(i))
- This condition will change to False when i updates to the value of 6
i = 1
while i <= 6:
print(i)
i += 1
- Adding a **break** key word, we can stop the loop
i = 1
while i <= 6:
print(i)
i += 1
if i == 5:
break
- Adding a **continue** key word, we can do something and continue the loop
i = 1
while i <= 6:
print(i)
i += 1
if i == 5:
print("i equals 5")
continue
- Adding an **else** key word, we can do something else
i = 1
while i <= 6:
print(i)
i += 1
else:
print("i is no longer less than 6")
==== for loop examples ====
- Iterates over the list and prints the items, one line at a time
fruits = ["apple", "banana", "orange"]
for x in fruits:
print(x)
- Iterates over the letters in a string and prints them, one line at a time
for x in "banana":
print(x)
- Can use the **break** key word
fruits = ["apple", "banana", "orange"]
for x in fruits:
print(x)
if x == "banana":
break
- Can use the **continue** key word
fruits = ["apple", "banana", "orange"]
for x in fruits:
print(x)
if x == "banana":
print("I love bananas!")
continue
- Can use the **else** key word **only** if the loop exits normally ( without a break )
fruits = ["apple", "banana", "orange"]
for x in fruits:
print(x)
if x == "apple":
break
else:
print("I'm done!")