Controlled iteration

Report a typo

We have created the functions num, double_num, and square_num. Each of these functions can take a range of numbers and print out a number, a doubled number, and a squared number, respectively. The problem is that they print them in blocks, five lines for each function, as shown below:

The number is:  1
The number is:  2
The number is:  3
The number is:  4
The number is:  5
The double of the number is:  2
The double of the number is:  4
...
# and so on

But we want each function to print out one iteration at a time. Like this:

The number is:  1
The double of the number is:  2
The square of the number is:  1
The number is:  2
The double of the number is:  4
The square of the number is:  4
...
# and so on

This can be accomplished with the help of the threading module. Replace the dots in the program below by instantiating threads and starting them to achieve the desired output.

Write a program in Python 3
from threading import Thread
import time

def num():
for i in range(1, 6):
print("The number is: ", i)
time.sleep(1)

def double_num():
for i in range(1, 6):
print("The double of the number is: ", i * 2)
time.sleep(1)

def square_num():
for i in range(1, 6):
print("The square of the number is: ", i ** 2)
time.sleep(1)

thread_1 = ...
thread_2 = ...
thread_3 = ...

thread_1...
time.sleep(0.2)
...start()
time.sleep(0.2)
...

Create a free account to access the full topic