Python has primitive two loop commands:
- while loop
- for loop
In some cases one iteration (=execution) of an expression isn’t sufficient to get the result that you need. Thus, Python offers a special statement that will execute the block of code several times. Meet the loop command and one of the universal loop is the while loop.
As the while loop requires the introduction of additional variables, it takes more effort for an iteration. Therefore, the while loop is very moderate and not all that well known. It looks like a conditional operator: utilizing the while loop, we can execute a set of statements as long as the condition is valid(true).
The condition itself (2) is written before the body of the loop (some consider it as conditional code) and is being checked before the body is executed. In the event that the condition is valid (3a), the loop proceed. If the condition is false (3b), the loop execution is terminated and the program control moves further to the next set of statements.
While loop syntax with example:
number = 0 while number < 5: print(number) number += 1 print('Hence, numbers are lesser than or equal to 5')
The variable number assumes here the role of a counter – a variable that changes its value after every iteration. For this situation, the iteration proceed until the number is equivalent to 5. At the point when the value of a counter reaches at 5, the program control moves to the next operation and prints the message. Here you can see the output of this code:
The Break Statement
With the break statement we can stop the loop even if the while condition is true:
num = 1 while num < 10: print(num) if num == 7: break num += 1
The Continue Statement
With the continue statement we can stop the current iteration, and continue with the next:
num = 0 while num < 10: num += 1 if num == 3: continue print(num)
The Infinite Loop
By chance if you erase the part of the conditional code where you increment the value of a counter, you will bump into infinite loop. Since you don’t increase your variable, a condition never turns out to be false and can work forever. Typically, it is a sensible paradox, and you’ll need to stop the loop using special statements or completing the loop manually.
Once in a while the infinite loop can be useful, for example in questioning a customer when the loop works consistently to furnish the steady trade of data with a client. You can actualize it by composing True as a condition after the while header.
while True: ......
Now you know about the while loop and its use. Remember about the job of a counter, else, you’ll need to deal with infinite loop.
Try to solve this simple problem:
Carl asks you to count the sum of the first k natural numbers. Read k from the input, then add up numbers from 1 to k and print your answer.
Sample Input 1:
Sample Output 1:
n = int(input()) result = 0 while n: result += n n -= 1 print(result)
What is an iteration?
PCs are known for their capacity to do things which individuals consider to be exhausting and vitality boring. For instance, repeating identical tasks with no mistakes is one of these things. In Python, the procedure of repeated execution of a similar block of code is called an iteration.
There are two kinds of iteration:
Definite iteration, where the number of repetitions is stated in advance.
Indefinite iteration, where the code block executes as long as the condition stated is valid.
After the main iteration, the program returns to the start of the code’s body and repeats it, making it so-called loop. The most utilized one is the for loop, named after the for operator that gives the code’s execution.
For loop syntax
for variable in iterable: statement
where statement is a block of operations executed for each item in iterable, an object used in iteration (e.g. string or list). Variable takes the value of the next iterable after each iteration.
Now try to guess which output we’ll get if we execute the following piece of code:
continents = ['Asia','Africa','Antartica','South America','North America','Australia','Europe'] for conti in continents: print(conti)
Even strings are iterable, so you can spell the word, for example:
for char in 'INDIA': print(char)
Input data processing
You can likewise utilize the input() function that encourages a user to pass a value to some variable and work with it. Along these lines, you can get a similar output likewise with the past bit of code:
word = input() for char in word: print(char)
Now let’s try with a practical exam
times = int(input('I have repeatedly asked you to complete your "Homework"?')) for i in range(times): print('Homework!')
The range() function is utilized to specify the number of iterations. It returns an arrangement of numbers from 0 (by default) and ends at a predefined number. Be cautious: the last number won’t be in the output.
for i in range(5): print(i)
You can change the starting value if you’re not satisfied with 0, moreover, you can configure the increment (step) value by adding a third parameter:
for i in range(0, 20, 5): print(i)
Let’s try to find factorial of a number once using for loop and once using while loop:
num = int(input("enter a number: ")) fact = 1 for i in range(1, num + 1): fact = fact * i print("factorial of ", num, " is ", fact)
num = int(input("enter a number: ")) fact = 1 i = 1 while i <= num: fact = fact * i i = i + 1 print("factorial of ", num, " is ", fact)
In Python, it is easy to put one loop inside another one – a nested loop. The type of inner and outer loops doesn’t matter, the first to execute is the outer loop, then the inner one executes:
breaking_bad = ['Walter_White', 'Jesse_Pinkman'] surnames = ['Miller'] for name in breaking_bad: for surname in surnames: print(name, surname)
All in all, for loops are an efficient way to automatize some repetitive actions. You can add variables and operations to make a nested loop. Moreover, you can control the number of iterations with the help of the range() function. Be careful with the syntax: an extra indent or lack of colon can cause a mistake!
Let’s try to solve a problem now
Here is your chance to write instructions for a text-to-speech system. Let’s focus on reading phone numbers aloud. The input phone number will consist solely of digits. Print the name of each digit on a new line for the system to read them one by one.
Sample Input 1:
Sample Output 1:
digit_name = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'] phone_number = input() for digit in phone_number: print(digit_name[int(digit)])