Files
cybr108/practice/loops_examples.py
T

33 lines
1.1 KiB
Python

# # Define a list of items
# fruits = ['apple', 'banana', 'cherry']
# # Loops through defined list and prints each item as var 'fruit'
# for fruit in fruits:
# print(fruit)
# # For loops can iterate through the built-in range function as well, this prints all numbers (0 indexed) in the range
# for i in range(5):
# print(i)
# # While loops iterate while a condition is true
# # Define 'count' var
# count = 5
# # While count is greater than 0, the indented lines will fire
# while count >0:
# # Print the current count
# print(count)
# # This is shorthand for 'count = count - 1'
# count -= 1
# # When 'while' condition is no longer true, it continues to this line (This is the end of the loop)
# print("Blast off!")
# Iterate through a range
for i in range(10):
# If i equals 5 'break' the loop (in this example, only iterates 0, 1, 2, 3, 4)
if i == 5:
# stops the loop with the given condition
break
# if i can be divided by 2 with a remainder of 0 (modulo(this indicates an even number))
if i % 2 == 0:
# skip even numbers in the loop
continue
print(i)