How to resolve the algorithm Loops/Break step by step in the Python programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Loops/Break step by step in the Python programming language

Table of Contents

Problem Statement

Show a loop which prints random numbers (each number newly generated each loop) from 0 to 19 (inclusive). If a number is 10, stop the loop after printing it, and do not generate any further numbers.
Otherwise, generate and print a second random number before restarting the loop.
If the number 10 is never generated as the first number in a loop, loop forever.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Loops/Break step by step in the Python programming language

This is a Python program that generates two random numbers between 0 and 19 until the second number is 10. Here is a detailed explanation of the code:

  1. Import the randrange function from the random module. The randrange function generates a random integer between the given start and stop values, but excluding the stop value. For example, randrange(20) will generate a random integer between 0 and 19, but not including 20.
  2. Enter an infinite loop using the while True statement. This means that the code will continue to run until it encounters a break statement.
  3. Inside the loop, generate two random integers between 0 and 19 using the randrange function. Store the first random integer in the variable a and the second random integer in the variable b.
  4. Print the value of a.
  5. Check if the value of a is equal to 10. If it is, break out of the loop using the break statement. This will stop the program from generating any more random numbers.
  6. If the value of a is not equal to 10, print the value of b.
  7. Repeat steps 3-6 until the value of a is equal to 10. When this happens, the program will break out of the loop and stop running.

Here is an example of the output of the program:

17
1
15
14
9
10

Source code in the python programming language

from random import randrange

while True:
    a = randrange(20)
    print(a)
    if a == 10:
        break
    b = randrange(20)
    print(b)


  

You may also check:How to resolve the algorithm Return multiple values step by step in the ooRexx programming language
You may also check:How to resolve the algorithm Sequence of non-squares step by step in the APL programming language
You may also check:How to resolve the algorithm Snake step by step in the C programming language
You may also check:How to resolve the algorithm Fibonacci sequence step by step in the Dc programming language
You may also check:How to resolve the algorithm Gray code step by step in the NOWUT programming language