Loops are an essential concept in programming, and they allow you to repeat a block of code multiple times. In Python, there are two main types of loops: for loops and while loops. A for loop is used to iterate over a sequence of elements. The sequence can be a list, tuple, set, or any other iterable object.
# The 'For' Loop
primes = [2, 3, 5, 7]
for prime in primes:
print(prime)
# Range and XRange (Python 3)
for x in range(5):
print(x)
for x in range(3, 6):
print(x)
for x in range(3, 8, 2):
print(x)
A while loop is used to repeat a block of code while a certain condition is true. This while loop will continue to run as long as the count variable is less than or equal to 5.
Loops are also often used with conditional statements, such as if statements
# While Loops
count = 0
while count < 5:
print(count)
count += 1 # This is the same as count = count + 1
## Break and Continue Examples
count = 0
while True:
print(count)
count += 1
if count >= 5:
break
# Prints out only odd numbers - 1,3,5,7,9
for x in range(10):
# Check if x is even
if x % 2 == 0:
continue
print(x)
Each time the loop runs, it will print the value of the count variable and then increase the count by 1.
# "Else" clause and Loops
count=0
while(count<5):
print(count)
count +=1
else:
print("count value reached %d" %(count))
# Prints out 1,2,3,4
for i in range(1, 10):
if(i%5==0):
break
print(i)
else:
print("this is not printed because for loop is terminated because of break but not due to fail in condition")
This for loop will iterate over the list of numbers and check if each number is even. If a number is even, it will be printed to the console.
Basic String Operations Exercise Solution
#Code Completed
numbers = [
951, 402, 984, 651, 360, 69, 408, 319, 601, 485, 980, 507, 725, 547, 544]
# Print all even numbers up to 237
for number in numbers:
if number == 237:
break
if number % 2 == 1:
continue
print(number)
In conclusion, loops are an essential concept in programming and allow you to repeat a block of code multiple times. Python has two main types of loops: for loops and while loops, which can be used with conditional statements to perform more complex tasks. Understanding how to use loops is crucial to becoming a proficient Python programmer.