-2

I need to use recursion in order for the input to keep calling itself if the sum of the two inputs don't equal to 100, but every time I try, I keep ending up with it asking for the input once, and then once it has been entered, it returns a hexadecimal value.

class Z:
    def __init__(self, probabilityX = 0, probabilityY = 0):
        self.probabilityX = ""
        self.probabilityY = ""
    def getProbability(self):
        print(self.probabilityX, self.probabilityY)
    def input(self):
        self.probabilityX = int(input("Enter probability of x:"))
        self.probabilityY = int(input("Enter probability of y:"))
        if self.probabilityX + self.probabilityY != 100:
            input(self)

def main():
    purs = Z()
    purs.input()
    purs.getProbability()
main()

Any help is greatly appreciated! Edit: Fixed typing errors

mikecal7
  • 95
  • 1
  • 2
  • 7
  • 2
    It should be `self.input()`, not `input(self)`. – zondo Dec 07 '16 at 22:45
  • Possible duplicate of [Asking the user for input until they give a valid response](http://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) – wwii Dec 07 '16 at 23:05

1 Answers1

0

A couple of things:

  1. First off, these aren't class methods, that term has a specific meaning that you shouldn't confuse. You're dealing with plain methods here.
  2. (obsolete) Both input calls are missing closing parentheses:

    self.probabilityX = int(input("Enter probability of x:")
    self.probabilityY = int(input("Enter probability of y:")
    

    should instead be:

    self.probabilityX = int(input("Enter probability of x:"))
    self.probabilityY = int(input("Enter probability of y:"))
    

    I'm guessing they are typos when you posted the question :-)

  3. Calling input(self) doesn't do what you think. input is a built-in function, you're invoking that with self as the prompt. You should be using self.input() again (and maybe renaming it to input_probabilities to evade confusion.

  4. (obsolete) purs.getProbabilityP is mis-spelled, it is purs.getProbability().

  5. Your __init__ doesn't make much sense:

    def __init__(self, probabilityX = 0, probabilityY = 0):
        self.probabilityX = ""
        self.probabilityY = ""
    

    I'm not sure why you provide default arguments for probability(X|Y) and then not assigning those to the corresponding instance attributes. You should do that:

    def __init__(self, probabilityX = 0, probabilityY = 0):
        self.probabilityX = probabilityX
        self.probabilityY = probabilityY
    

As a final point, I'd suggest not using recursion; a while loop does the trick effectively.

Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253