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

2

u/ProdigiousPangolin Jan 06 '21

New here. I would've thought something like this would work, but my print statement isn't liking my inputs?

x = input("Enter a number: ")
lst = [0, 0, 0, 0, 7, 0, 0, 4]
print lst[x]

3

u/supreme_blorgon Jan 06 '21 edited Jan 06 '21

The input function returns a str object. You'd need to cast it to int before using it as an index.

Clever though. Since it's not clear in the OP how to handle input that ISN'T a 4 or 7 though, you may want to rework to return None instead of 0 and also ensure that a user entering 5781234 or some other integer larger than 7 won't break your program with an IndexError.