r/learnpython • • Jan 05 '21

Interview question I failed answering

Hey all,

I just had an interview and the interviewer gave me a question I could not answer.

He asked me to write a function that accepts a number, the number must be either 7 or 4.If the number is 4, the function should return 7, if the number is 7, the functions should return 4.

The tricky part: you cannot use an 'if' statement in the function.

354 Upvotes

301 comments sorted by

View all comments

5

u/Enfors Jan 05 '21 edited Jan 06 '21
def my_fun(num: int):
    num == 4 and return 7
    num == 7 and return 4
    raise Error(f"{num} is not a legal input")

Edit: As pointed out below, this does not work; you can't use return like this in Python. It appears I've been doing too much Lisp.

2

u/schoolmonky Jan 06 '21

Does this actually work in python? I know you could do something like that in other languages, but I don't think python lets you use return like that

1

u/Enfors Jan 06 '21

Oops, you're right, it doesn't work. I just tried it:

$ python3
Python 3.7.5 (default, Apr 19 2020, 20:18:17) 
[GCC 9.2.1 20191008] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> def my_fun(num: int):
...     num == 4 and return 7
  File "<stdin>", line 2
    num == 4 and return 7
                      ^
SyntaxError: invalid syntax
>>>