I'm supposed to write a statement that calls the recursive function backwards_alphabet() with input starting_letter. I've figured out how to do that. The problem is that at the end of my code it prints None. How do I get it to stop doing that?
(Anything above starting_letter = input() cannot be edited or added on to. I've tried and the site I'm using won't let me)
Here is my code
def backwards_alphabet(curr_letter):
if curr_letter == 'a':
print(curr_letter)
else:
print(curr_letter)
prev_letter = chr(ord(curr_letter) - 1)
backwards_alphabet(prev_letter)
starting_letter = input()
print(backwards_alphabet(starting_letter))
The expected output is supposed to be
f e d c b a
My output is
f e d c b a None
All I had to do was get rid of print
Your code is correct, your problem is:
print(backwards_alphabet(starting_letter))
You're trying to print the function, which returns None
as there is no return statement in the function.
Your code can also be simplified:
def backwards_alphabet(curr_letter: str):
if curr_letter != '`':
print(curr_letter)
backwards_alphabet(chr(ord(curr_letter) - 1))
When you have to write a recursive function, always start by thinking what will the base condition be?