Warum funktioniert mein rekursive python-Funktion zurückzukehren Keiner?

Habe ich diese Funktion, die nennt sich:

def get_input():
    my_var = input('Enter "a" or "b": ')

    if my_var != "a" and my_var != "b":
        print('You didn\'t type "a" or "b". Try again.')
        get_input()
    else:
        return my_var

print('got input:', get_input())

Nun, wenn ich geben Sie nur "a" oder "b" funktioniert alles wunderbar:

Type "a" or "b": a
got input: a

Aber, wenn ich etwas anderes eingibst und dann "a" oder "b", bekomme ich diese:

Type "a" or "b": purple
You didn't type "a" or "b". Try again.
Type "a" or "b": a
got input: None

Ich weiß nicht, warum get_input() zurück None, da sollte es nur zurück my_var. Wo ist dieser None herkommt, und wie behebe ich meine Funktion?

  • Sie tun müssen return Dat_Function() beim Aufruf rekursiv.
  • Nur ein Tipp: Die idiomatische Weise, dass my_var != "a" and my_var != "b" Zustand wäre my_var not in ('a', 'b')
InformationsquelleAutor Cate | 2013-07-22
Schreibe einen Kommentar