Iterations with Python
Iterations with Python
Iterations are a crucial concept in programming. We use them to execute repetitive code blocks. Python has provided us two types of iteration statements; the while loop and the for loop. Today let’s learn how these two can help us to avoid code repetition.
while Loop
We use while loops to repeat a code block multiple times as long as a particular condition is met or to repeat forever while the condition is True. Therefore, while loops may be used to validate user input.
Let’s write a simple program to get user input and check if it is a positive integer. The variable is_positive_integer is initialized to True. This is used to check the while condition. If the user enters a digit and if it is larger than 0, is_positive_integer will be set to False. Therefore, while condition will stop execution. This is done with the help of if condition and isdigit() method.
is_positive_integer = True
while is_positive_integer:
positive_integer = input("Enter a positive integer: ")
if positive_integer.isdigit() and int(positive_integer) > 0:
print(f"{positive_integer} is a positive integer.")
is_positive_integer = False
else:
print("A positive integer is a whole number larger than 0.")
for Loop
We use for loops to iterate over a sequence. A sequence could be a range of numbers, a string or even a data structure. Therefore, for loops can be used to search and sort data through a sequence.
Let’s look at how we can use for loops to iterate over keys and values of a dictionary. Using the dictionary name -square_numbers- in the for loop we can access the keys. In order to access values or key-value pairs, we have to use the values() method or the items() method.
square_numbers = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
# Iterating over keys
for key in square_numbers:
print(key)
# Iterating over values
for value in square_numbers.values():
print(value)
# Iterating over key-value pairs
for key, square in square_numbers.items():
print(f"{key}: {square}")
for loops can also be used to add elements to a data structure. Below code shows how to initialize an empty dictionary and add the first ten square numbers to the dictionary. We have to use the range() function to define the range of numbers from 1 through 10 (range function excludes 11).
square_numbers = dict()
for i in range(1, 11):
square_numbers[i] = i * i
print(square_numbers)
Refer this Python official document to see some more examples on for loops.
Note:
while loops are known as indefinite loops, since we may use them to iterate over an unknown number of iterations.
for loops are known as definite loops, since we may use them to iterate over a known range.
Comments
Post a Comment