.
Previous Next

Interview Questions on Python

31. How to write while loop in python?

Syntax :-
while expression:
   statement(s)
Ex :- 
count = 0
while (count < 9):
   print 'The count is:', count
   count = count + 1

32. How to write for loop in python?

Syntax :-
for iterating_var in sequence:
    statements(s)
Ex:-
for letter in 'Python':     # First Example
   print 'Current Letter :', letter
fruits = ['banana', 'apple',  'mango']
for fruit in fruits:        # Second Example
   print 'Current fruit :', fruit

33. How to pass command line arguments?

Syntax :-
python test.py arg1 arg2 arg3

34. How to get command line arguments legth?

Use len()
Ex :-
#!/usr/bin/python
import sys
print 'Number of arguments:', len(sys.argv), 'arguments.'
print 'Argument List:', str(sys.argv)

35. How to print cmd line arguments?

Use sys.argv
Ex :-
#!/usr/bin/python
import sys
print 'Argument List:', str(sys.argv)
     for arg in str(sys.argv):        # Second Example
         print arg

36. How to open file in write mode?

Syntax :- open('file_name', 'w')
Ex :-  fo = open('file1.txt', 'w')

37. How to open file in read mode ?

Syntax :- open('file_name', 'r')
Ex :- fo = open('file1.txt', 'r')

38. How to create a file?

Open file in write mode. It will create file if it is not exist. But it will truncate the file if it is exist.

39. What happens if we use negative index in string?

A negative index accesses elements from the end of the list counting backwards.
An example to show negative index in python
>>> import array
>>> a= [1, 2, 3]
>>> print a[-3]

40. How to know whether the object is belongs to particular class or not?

Syntax :- isinstance(obj, MyClass)
Ex :- 
if isinstance(obj, MyClass):
     print "obj is my object"

Previous Next