Return False Not Working + If/Else

Hello! I am new to python and learning about functions and how to return a value. I have an assigment that says to “create a function who returns the third character in a string, if the string is shorter than three characters it should return false”.
I am able to make the function return the third sign in a string, but I can´t get it to return False when the string is shorther than characters.
Anyone who can help me figure out why it wont return false? This is the code I´ve written:

def third_character(string):
 x = string[2]
 print(x)
 if len(string) > 2:
   return x
 else:
   return False

third_character()  #In there you enter a string with "" around

Thankful for help

here:

x = string[2]

what if the string is one character in length? You will get an IndexError error, given there is nothing at index 2

you do a check for this:

if len(string) > 2:

but this after the possible IndexError, so that won’t work

It works now, i put the x = string[2] under the if statement instead! Thank you so much, very helpful :grinning:

Do you also understand why this change works? Don’t read it purely as code, but also what is happening (if there aren’t elements in the list, stop the function by return false else return the third character

Yes i think so! Since python reads the code in order (line 1, line 2 line 3…), if i write it as i did first (above if-statement) it will always try to output the third character, even when there isnt one and that will create an error. But if i put it under the if-statement it will only print it if it is actually longer than 2 characters. And if the if-statement is not fulfilled it will instead print what is under “else”!

But i dont understand what the return statement actually does! I feel like it should do the same thing if i would take away the return part and only write print? Don´t understand the difference!

+ is like a function, you give it input and get something back

now imagine it printed the result instead of returning it

try to write a function add that adds two numbers together just like +, but prints the result instead of returning it (so the location where the result is expected to be presented no longer has the result)

Then use it to evaluate this:
1 + 2 + 3
The result of the first use of add is the first input to the second use of add:
add(add(1, 2), 3)

not really, functions and loop are an exception to this rule

It doesn’t output the third character, it attempts to look up third character at index 2/third character of the string

return and print are not the same thing, as explained by @ionatan

Ah okay, I get it now! Thank you a lot :slight_smile:

Okay I see, thank you very much for the help!! :slight_smile: