-4

Can anyone please suggest me why this function doesn't return re , if i pass any int it just return an int

def fun (a):
    if a:
        if type(a) == int:
            return "an int"
        else:
            return "not"
    re = {"key":a}
    return re

It this a python condition

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
Ravi Dawade
  • 66
  • 1
  • 5
  • 1
    Why **wouldn’t** it return “an int”? In other words, what about it isn’t working the way you expect? Are you asking about Python truthiness? Are you asking why if `a` is truthy the function returns? (That’s because you told it to.) – Dave Newton May 05 '23 at 12:49
  • Does this answer your question? [What is the purpose of the return statement? How is it different from printing?](https://stackoverflow.com/questions/7129285/what-is-the-purpose-of-the-return-statement-how-is-it-different-from-printing) – CrazyChucky May 05 '23 at 12:50

3 Answers3

2

I'm assuming you're a beginner in programming

the keyword return is literally like an exit door to a function, whenever the function hits with return keyword it'll automatically stop executing the below code in the function.

In your code, you have 3 return statements and the final return is the one you are expecting, so for that you have to make the condition clear and remove other two returns.

def fun (a):
    if a:
        if type(a) == int:
            print("an int")
        else:
            print("not")
    re = {"key":a}
    return re
Hariharan
  • 191
  • 7
1

function does not return re because the return in if else condition is executed first (unless a==0 or False) ,this will return the string "an int" or "not" then the function exits because return is a break point in a function.

if you need to return a dict then directly return {'key':a,'type':'an int'}

Vishnu Balaji
  • 175
  • 1
  • 11
0

I'm not sure that I understood your problem, however, if you want your "re" variable to be returned, the only way is to set up "a" as an empty string :

fun("")

Due to your "if a:" if theres something, your else condition will never be used.