Home > Blockchain >  Using While Loop in __init__ to meet specific condition in Python
Using While Loop in __init__ to meet specific condition in Python

Time:09-14

I am working with a senior developer who pointed out that the below code written is not the best practice.

import random


class RandomNumbers:

    def __init__(self):
        self.BASE_TEXT = ''' {}   {} '''
        while True:
            self.A = random.randint(1, 10)
            self.B = random.randint(1, 5)

            if self.A > self.B:
                break

    def generate(self):
        return self.BASE_TEXT(self.A, self.B)

I want to ensure that random number A is always greater than random number B. To meet this condition I can't think of any other way apart from using while with an if condition.

The comment I got from the senior developer is that

Neither do I understand what he means by that nor do I see any problems with code with an API response.

you cannot have something that runs randomly on the class constructor, especially since we will need an API response for it

Can someone please review the code and validate that there is no issue with the code?

CodePudding user response:

The senior developer is correct that when unlucky, your code can randomly and potentially take a long time to run if self.A > self.B keeps getting evaluated to False.

Instead, you can make A the stop number of random.randrange when generating a random number for B, or 6, whichever is lower. But since A has to be greater than B and B must be at least 1, A should be at least 2:

class RandomNumbers:
    def __init__(self):
        self.BASE_TEXT = ''' {}   {} '''
        self.A = random.randint(2, 10)
        self.B = random.randrange(1, min(self.A, 6))

    def generate(self):
        # don't forget to call the str.format method
        return self.BASE_TEXT.format(self.A, self.B)
  • Related