Why code is printing e

I want this code to stop after getting G but it also prints e


## recursion to find the first upper case letter in a string

def find_upper(str_1):

#base case

#Simplest case if first letter has upper case

    if str_1[0].isupper():

        print("the letter is", str_1[0])

        return str_1[0]

#recursive case

    else:

#check the next letter as you slice the string

        str_1 = str_1[1:]

        print("the outer else statement str_1", str_1)

        if str_1[0].isupper():

            print("this is the letter",str_1[0])

        else:

#recurse

            find_upper(str_1[1:])

        return str_1[0]

print(find_upper("geekforGeeks"))

I know this isn’t an answer, but your function could be much shorter.
Finish the second return line to make this work, don’t add any lines.

def find_upper(str_1):

#base case

#Simplest case if first letter has upper case

    if str_1[0].isupper():

        print("the letter is", str_1[0])

        return str_1[0]

    return #your code here
1 Like

same as the previous reply:

you can take out the code between
#check the next letter as you slice the string
and
#recurse

Alternatively, change:

        str_1 = str_1[1:]
        print("the outer else statement str_1", str_1)

to

        print("the outer else statement str_1", str_1[1:])

Without some change, there’s a problem because you’d be doing str_1 = str[1:] and then find_upper(str_1[1:])
in both of those steps, you removed the first character of the string you are examining,
but doing it twice means removing two characters.


it might also be a good idea to have a base case for an empty string (just in case there is no upper case letter) like:

if len(str_1) == 0:
  return str_1;

1 Like

## recursion to find the first upper case letter in a string

def find_upper(str_1):

#base case

    if str_1 == "":

        return str_1

#Simplest case if first letter has upper case

    else:

        if str_1[0].isupper():

            print("the letter is", str_1[0])

            return str_1[0]

        return find_upper(str_1[1:])

2 Likes