The goal of this tutorial is to help you understand and master the use of For and While loops in Python. Loops are fundamental to programming as they allow us to repeat a block of code multiple times.
By the end of this tutorial, you will learn:
For and While loops.This tutorial assumes that you have a basic understanding of Python programming. Knowledge of Python syntax and data types would be beneficial.
In Python, For loops are used for iterating over a sequence (like a list, tuple, dictionary, set, or string) or other iterable objects. The iterating variable takes on each value in the sequence.
# Simple For loop
for i in range(5):
print(i)
The While loop in Python is used to iterate over a block of code as long as the test expression (condition) is true.
# Simple While loop
i = 0
while i < 5:
print(i)
i += 1
break and continue statements wisely to control your loop execution.# For loop on a list
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
print(fruit)
This code will output:
apple
banana
cherry
# While loop with break statement
i = 0
while i < 5:
print(i)
if i == 3:
break
i += 1
This code will output:
0
1
2
3
In this tutorial, you've learned about For and While loops in Python. You've seen how to use them with examples and you've also learned some best practices when writing loops.
The next step in your learning journey could be to learn about nested loops, where a loop exists inside another loop. You can also explore more about the break and continue statements and their use cases.
Write a Python program to find those numbers which are divisible by 7 and multiple of 5, between 1500 and 2700 (both included).
Write a Python program to count the number of even and odd numbers from a series of numbers.
Solution 1
for number in range(1500, 2701):
if number % 7 == 0 and number % 5 == 0:
print(number)
Solution 2
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9] # This is an example series. You can use any series.
even_count, odd_count = 0, 0
for number in numbers:
if number % 2 == 0:
even_count += 1
else:
odd_count += 1
print("Number of even numbers: ", even_count)
print("Number of odd numbers: ", odd_count)
In these exercises, you've practiced using both For and While loops. Keep practicing with more complex examples to solidify your understanding. Happy coding!