Logo F2FInterview

Python Interview Questions

Q   |   QA

{'one':2,'two':2,'three':2}

If a list of words is empty, then let the user know it's empty, otherwise let the user know it's not empty.

a=[]
if len(a):
print"The list is empty"
else:
print"The list is not empty"

The will not work but me being a c++ programmer, I would not code it this way, I would have coded the following way

a=[]
if len(a) == 0:
print"The list is empty"
else:
print"The list is not empty"

This works but the above implementation does not. Can somebody tell me what is wrong with the above code. Because the interviewer told me that a python programmer would code it that way rather than my way. That was a good lesson. When you code in python, you tend to demonstrate your background with such mistakes. :D

a=[1,2,3,4]
try:
print a[0]
except Exception, e # This was important. Just do not say except: and print out something. It is
print e # Important to know what is the error

This could also have been better. If somebody knows a better way than the above code, I would really appreciate it.

f1=open("filename.txt","r")
leng=f1.readline()
print len(leng) -1, "is the length of the string"

Since the last character is a whitespace we deduct 1 out of the length returned by the len() function.

print sum(range(1,100))

This is way too easy but just who know python. Since I am a C++ Programmer, I started writing a for loop to add up which was way too dumb. Hope you don't make this mistake.
Python is known for it short syntax and easy to use functions.

In order to link this F2FInterview's page as Reference on your website or Blog, click on below text area and pres (CTRL-C) to copy the code in clipboard or right click then copy the following lines after that paste into your website or Blog.

Get Reference Link To This Page: (copy below code by (CTRL-C) and paste into your website or Blog)
HTML Rendering of above code: