0

I have another Python beginners question:

options =['stein', 'schere', 'papier']

class Spieler(object):
    def __init__(self, nummer):
        self.nummer = nummer

    def abfrage(self):
        print("Spieler Nr.", self.nummer)
        eingabe = input("- Stein/Schere/Papier? >>>")
        if eingabe.lower() in options:
            print("Danke!")
            # when eingabe printed out from here, always correct!
            return eingabe 
        else:
            print("Nope...")
            self.abfrage() # this call is the problem

spieler1 = Spieler(1); spieler2 = Spieler(2)
wahl1 = spieler1.abfrage()
wahl2 = spieler2.abfrage()

So - the code returns a fine result "eingabe" to wahl1/2. But only if it doesn´t go through the error loop, which means the instance method calls itself again.

In these cases, "None" will be returned to wahl1/2 although if printed out from within the method the value for "eingabe" is correct.

Why?

  • 2
    Well… is there a `return` statement in the `else` branch? No, there isn't. – deceze Mar 02 '20 at 10:44
  • 2
    you probably want at least `return self.abfrage()` but you'd be better off with a better way to loop until a valid input – Sayse Mar 02 '20 at 10:44
  • thanks for the anwers.. works with the return recursive call. But I don´t really understand why the missing return in the else part has priority over the ran-again positive if condition that creates the correct value but just does not return it... – derhottevomdorf Mar 02 '20 at 11:44
  • Would you expect `else: foo()` to `return` anything? No, you wouldn't. It doesn't matter that `foo()` in this case is the same function you're calling it from. – deceze Mar 02 '20 at 11:58
  • well :) Maybe I am thinking to linearly here .. I had expected it just runs the method from the start, including if condition (which it does), thereby also returning "eingabe" – derhottevomdorf Mar 02 '20 at 12:23
  • That's one of the things you need to wrap your head around with recursion: you're calling *a* function, it doesn't matter that it's the same function, it behaves the same as any other function call would. – deceze Mar 02 '20 at 12:38

0 Answers0