Wednesday 18 October 2017

Python Interview Questions-2

1. What is Python?
Python is a high-level, interpreted, interactive and object-oriented scripting language. Python is designed to be highly readable. It uses English keywords frequently where as other languages use punctuation, and it has fewer syntactical constructions than other languages.

2. What is the purpose of PYTHONPATH environment variable?
PYTHONPATH - It has a role similar to PATH. This variable tells the Python interpreter where to locate the module files imported into a program. It should include the Python source library directory and the directories containing Python source code. PYTHONPATH is sometimes preset by the Python installer.

3. What is the purpose of PYTHONSTARTUP environment variable?
PYTHONSTARTUP - It contains the path of an initialization file containing Python source code. It is executed every time you start the interpreter. It is named as .pythonrc.py in Unix and it contains commands that load utilities or modify PYTHONPATH.

4. Is python a case sensitive language?
Yes! Python is a case sensitive programming language.

5. What are the supported data types in Python?

Python has five standard data types −
Numbers
String
List
Tuple
Dictionary

6. What are tuples in Python?
A tuple is another sequence data type that is similar to the list. A tuple consists of a number of values separated by commas. Unlike lists, however, tuples are enclosed within parentheses.

7. What is the difference between tuples and lists in Python?
The main differences between lists and tuples are − Lists are enclosed in brackets ( [ ] ) and their elements and size can be changed, while tuples are enclosed in parentheses ( ( ) ) and cannot be updated. Tuples can be thought of as read-only lists.

8.What are Python's dictionaries?
Python's dictionaries are kind of hash table type. They work like associative arrays or hashes found in Perl and consist of key-value pairs. A dictionary key can be almost any Python type, but are usually numbers or strings. Values, on the other hand, can be any arbitrary Python object.

9.How will you create a dictionary in python?
Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed using square braces ([]).

dict = {}
dict['one'] = "This is one"
dict[2]     = "This is two"
tinydict = {'name': 'john','code':6734, 'dept': 'sales'}

10.How will you get all the keys from the dictionary?
Using dictionary.keys() function, we can get all the keys from the dictionary object.
print dict.keys()   # Prints all the keys

11.How will you get all the values from the dictionary?
Using dictionary.values() function, we can get all the values from the dictionary object.
print dict.values()   # Prints all the values

12. How will you convert a string to an int in python?
int(x [,base]) - Converts x to an integer. base specifies the base if x is a string.

13.How will you convert a string to a long in python?
long(x [,base] ) - Converts x to a long integer. base specifies the base if x is a string.

14.How will you convert a string to a float in python?
float(x) − Converts x to a floating-point number.

15.How will you convert a object to a string in python?
str(x) − Converts object x to a string representation.

16.How will you convert a object to a regular expression in python?
repr(x) − Converts object x to an expression string.

17.How will you convert a String to an object in python?
eval(str) − Evaluates a string and returns an object.

18.How will you convert a string to a tuple in python?
tuple(s) − Converts s to a tuple.

19.How will you convert a string to a list in python?
list(s) − Converts s to a list.

20.How will you convert a string to a set in python?
set(s) − Converts s to a set.

21.How will you create a dictionary using tuples in python?
dict(d) − Creates a dictionary. d must be a sequence of (key,value) tuples.

22. How will you convert an integer to a character in python?
chr(x) − Converts an integer to a character.

23.How will you convert a single character to its integer value in python?
ord(x) − Converts a single character to its integer value.

24.How will you convert an integer to hexadecimal string in python?
hex(x) − Converts an integer to a hexadecimal string.

25.What is the purpose of // operator?
// Floor Division − The division of operands where the result is the quotient in which the digits after the decimal point are removed.

26.What is the purpose of is operator?
is − Evaluates to true if the variables on either side of the operator point to the same object and false otherwise. x is y, here is results in 1 if id(x) equals id(y).

27.What is the purpose break statement in python?
break statement − Terminates the loop statement and transfers execution to the statement immediately following the loop.

28.What is the purpose continue statement in python?
continue statement − Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.

29.What is the purpose pass statement in python?
pass statement − The pass statement in Python is used when a statement is required syntactically but you do not want any command or code to execute.

30.How can you get a random number in python?
random() − returns a random float r, such that 0 is less than or equal to r and r is less than 1.

31.How will you capitalizes first letter of string?
capitalize() − Capitalizes first letter of string.

32.How will you check in a string that all characters are digits?
isdigit() − Returns true if string contains only digits and false otherwise.

33.How will you check in a string that all characters are alphanumeric?
isalnum() − Returns true if string has at least 1 character and all characters are alphanumeric and false otherwise.

34.How will you check in a string that all characters are in lowercase?
islower() − Returns true if string has at least 1 cased character and all cased characters are in lowercase and false otherwise.

35.How will you check in a string that all characters are numerics?
isnumeric() − Returns true if a unicode string contains only numeric characters and false otherwise.

36.How will you check in a string that all characters are whitespaces?
isspace() − Returns true if string contains only whitespace characters and false otherwise.

37.How will you check in a string that it is properly titlecased?
istitle() − Returns true if string is properly "titlecased" and false otherwise.

38.How will you check in a string that all characters are in uppercase?
isupper() − Returns true if string has at least one cased character and all cased characters are in uppercase and false otherwise.

39.How will you merge elements in a sequence?
join(seq) − Merges (concatenates) the string representations of elements in sequence seq into a string, with separator string.

40.How will you get the length of the string?
len(string) − Returns the length of the string.

41.How will you remove all leading whitespace in string?
lstrip() − Removes all leading whitespace in string.

42.How will you replaces all occurrences of old substring in string with new string?
replace(old, new [, max]) − Replaces all occurrences of old in string with new or at most max occurrences if max given.

43.How will you remove all leading and trailing whitespace in string?
strip([chars]) − Performs both lstrip() and rstrip() on string.

44.How will you get titlecased version of string?
title() − Returns "titlecased" version of string, that is, all words begin with uppercase and the rest are lowercase.

45.What is the output of len([1, 2, 3])?
3.

46.What is the output of [1, 2, 3] + [4, 5, 6]?
[1, 2, 3, 4, 5, 6]

47.What is the output of ['Hi!'] * 4?
['Hi!', 'Hi!', 'Hi!', 'Hi!']

48.What is the output of 3 in [1, 2, 3]?
True

49.What is the output of for x in [1, 2, 3]: print x?
1 2 3

50.What is the output of L[2] if L = [1,2,3]?
3, Offsets start at zero.

51.What is the output of L[-2] if L = [1,2,3]?
L[-1] = 3, L[-2]=2, L[-3]=1

52.What is the output of L[1:] if L = [1,2,3]?
2, 3, Slicing fetches sections.

53. How will you compare two lists?
cmp(list1, list2) − Compares elements of both lists.

54. How will you get the length of a list?
len(list) − Gives the total length of the list.

55.How will you get the max valued item of a list?
max(list) − Returns item from the list with max value.

56. How will you get the min valued item of a list?
min(list) − Returns item from the list with min value.

57. How will you get the index of an object in a list?
list.index(obj) − Returns the lowest index in list that obj appears.

58.How will you remove last object from a list?
list.pop(obj=list[-1]) − Removes and returns last object or obj from list.

59. How will you remove last object from a list?
list.pop(obj=list[-1]) − Removes and returns last object or obj from list.

60. How will you remove an object from a list?
list.remove(obj) − Removes object obj from list.

61. How will you reverse a list?
list.reverse() − Reverses objects of list in place.

61. How will you sort a list?
list.sort([func]) − Sorts objects of list, use compare func if given.

62. Multiple assignment
>>> target_color_name = first_color_name = 'FireBrick'
>>> id(target_color_name) == id(first_color_name)
True
>>> print(target_color_name)
FireBrick
>>> print(first_color_name)
FireBrick
>>>

63. Word count
import sys

def count_words(filename):
    results = dict()
    with open(filename, 'r') as f:
        for line in f:
            for word in line.split():
                results[word] = results.setdefault(word, 0) + 1

    for word, count in sorted(results.items(), key=lambda x: x[1]):
        print('{} {}'.format(count, word))

count_words(sys.argv[1])

64. Word list
from urllib.request import urlopen

with urlopen('http://sixty-north.com/c/t.txt') as story:
    story_words = []
    for line in story:
        line_words = line.split()
        for word in line_words:
            story_words.append(word)

print(story_words)

65. """Demonstrate scoping."""

count = 0

def show_count():
    print("count = ", count)

def set_count(c):
    global count
    count = c

66. """Module for demonstrating files."""
import sys
def main(filename):
  f = open(filename, mode='rt', encoding='utf-8')
  for line in f:
      sys.stdout.write(line)
  f.close()

if __name__ == '__main__':
  main(sys.argv[1])

67. Write a function to add two numbers
def add_numbers(*args):
    total = 0
    for a in args:
        total += a
    print (total)

add_numbers(3)
add_numbers(3, 42)

68.  How to un-pack arguments
def health_calculator(age, apples_ate, cigs_smoked):
    answer = (100-age) + (apples_ate * 3.5) - (cigs_smoked * 2)
    print(answer)

data = [27,20,0]
health_calculator(data[0],data[1],data[2])
health_calculator(*data)


  
69. Example of continue
numbersTaken = [2,5,12,33,17]
print ("Here are the numbers that are still available:")
for n in range(1,20):
    if n in numbersTaken:
        continue
    print(n)

70. Example of default arg
def get_gender(sex='Unknown'):
    if sex is "m":
        sex = "Male"
    elif sex is "f":
        sex = "Female"
    print(sex)

get_gender('m')
get_gender('f')
get_gender()

71. Example of for 
foods = ['apple', 'banana', 'grapes', 'mango']
for f in foods:
    print(f)
    print(len(f))

72. function example
def cisco():
    print("Python, fucntions are cool!")
cisco()

def bitcoin_to_usd(btc):
    amount = btc*527
    print(amount)

bitcoin_to_usd(3.85)

73. Example of if else
name = "Lucy"
if name is "Manish":
    print("hey there Manish")
elif name is "Lucy":
    print("What's up Lucy")
elif name is "Sammy":
    print("What's up Sammy")
else:
    print("Please sign up for the Site!")

74. Example of key argument 
def dumb_sentence(name='manish',action='ate',item='tuna'):
    print(name,action,item)

dumb_sentence()
dumb_sentence("Sally", "plays", "gently")
dumb_sentence(item ='awesome', action= 'is')

75. Example of range
for x in range(10):
    print("Hello manish")

for x in range(5, 12):
    print(x)
for x in range(10, 40, 5):
    print(x)

76. Example of return
def allowed_dating_age(my_age):
    girls_age = my_age/2 + 7
    return girls_age

Age_limit = allowed_dating_age(34)
print("You can date girls", Age_limit, "or older")
allowed_dating_age(34)

77. Example of set
groceries = {'cereal','milk','starcrunch','beer','duct tape','lotion','beer'}
print(groceries)

if 'milk' in groceries:
    print("You already have milk hoss!")
else:
    print("Oh yes you need milk!")

78. Example of variable scope
#a = 1514
def test1():
    a = 1514
    print(a)

def test2():
    print(a)

test1()
test2()

79. Example of dictionary
myDict = {'manish': 'bidsar','abc': 'efg'}
print(myDict)
print(myDict['manish'])
print(myDict["manish"])

varstr = "this is manish " \
         "from  Karnataka " \
         "India."
   
   
80. Example for prime number
for num in range(2,20):
    if num%2 == 0:
        print ('num is not prime')
        #break
    else:
        print ('num is prime number')

x = range(2,9)
print(x)

81. Example of key value

names = {'a': 1, 'b': 2, 'c': 3}
print(names)
x = names.keys()
print(x)
print(names['c'])

82. Program for fibonacci
def fib(n):
    a,b = 0,1
    while b < n:
        print(b)
        a,b = b , a+b

fib(3)

83. Program to check vowel 
letter = 'o'
if letter == 'a' or letter == 'e' or letter == 'i' \
or letter == 'o' or letter == 'u':
    print (letter, 'is a vowel')
else:
    print(letter, 'is not a vowel')
   
84. Example of multi-dimensional array
rows = range(1,4)
cols = range(1,3)

cells = [(row,col) for row in rows for col in cols]
for cell in cells:
    print(cell)

85. Decorator example 
def document_it(func):
    def new_function(*args, **kwargs):
        print('Running function:', func.__name__)
        print('Positional arguments:', args)
        print('keyword arguments:', kwargs)
        result = func(*args, **kwargs)
        print('Result:', result)
        return result
    return new_function

def add_ints(a,b):
    return a + b

add_ints(3,5)

cooler_add_ints = document_it(add_ints)
cooler_add_ints(3,5)
#ALITER
@document_it
def add_ints(a,b):
    return a + b

add_ints(3,5)

86. You can have more than one decorator for a function

def square_it(func):
    def new_function(*args, **kwargs):
        result = func(*args, **kwargs)
        return result*result
    return new_function

@document_it
@square_it
def add_ints(a,b):
    return a+b
add_ints(3,5)

87. Inheritance
class Car():
    pass

##sub class
class Yugo(Car):
    pass

##create object for each class
give_me_a_car = Car()
give_me_a_yugo = Yugo()

class Car():
    def exclaim(self):
        print('I m a Car')

class Yugo(Car):
    pass

## make one object from each class and call the exclaim method
give_me_a_car = Car()
give_me_a_yugo = Yugo()
give_me_a_car.exclaim()
give_me_a_yugo.exclaim()

##over-ride a method
class Car():
    def exclaim(self):
        print('I am a Car!')

class Yugo(Car):
    def exclaim(self):
        print("I am a Yugo much like car, but more Yugo-ish")

# now make two object from these class
give_me_a_car = Car()
give_me_a_yugo = Yugo()

give_me_a_car.exclaim()
give_me_a_yugo.exclaim()

#super class
class Person():
    def __init__(self, name):
        self.name = name

class EmailPerson(Person):
    def __init__(self, name, email):
        super().__init__(name)
        self.email = email

manish = EmailPerson('Manish Bidsar','manish123@gmail.com')

print(manish.name)
print(manish.email)

88. Regular expression
import re
result = re.match('You', 'Young Frankenstein')
print(result)
#or
source = 'Young Frankenstein'
m = re.match('You', source)
if m:
    print(m.group())  ### print macthed value

m = re.match('^You', source)
if m:
    print(m.group())

m = re.match('Frank', source)
if m:
    print(m.group())

m = re.search('Frank', source)
if m:
    print(m.group())

m = re.search('.*Frank', source)
if m:
    print(m.group())

m = re.findall('n', source)
print(m)

m = re.findall('n.', source)
print(m)

m = re.findall('n.?', source)
print(m)

m = re.split('n', source)
print(m)

m = re.sub('n', '?', source)
print(m)

89. Greatest of three
n1 = '902'
n2 = '100'
n3 = '666'

if (n1 > n2) and (n1 > n3):
    print("The greatest number is %s " % n1)
elif (n2 > n1) and (n2 > n3):
    print("The greatest number is %s " % n2)
else:
    print("The greatest number is %s " % n3)

90. ''' odd or even number'''

num = input("Enter a number: ")
mod = num % 2
if mod > 0:
    print (num, "is an odd number")
else:
    print (num, "is an even number")

91. Print all elements less than 5
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
num = int(raw_input("Choose a number:"))
new_list = []

for i in a:
    if i < num:
        new_list.append(i)

print(new_list)'''

92. Current date  and time

import datetime
now = datetime.datetime.now()
print ("Current date and time : ")
print (now.strftime("%Y-%m-%d %H:%M:%S"))

93. Check whether file exists
import os.path
open('abc.txt', 'w')
print(os.path.isfile('abc.txt'))

94. Verify python shell is 32 bit or 64 bit
import struct
print(struct.calcsize("P")*8)

95. Path and name of file currently executing
import os
print("Current file name: ", os.path.realpath(__file__))

96. Python program to access environment variables
import os
print('**********************')
print(os.environ)
print(os.environ['HOME'])
print(os.environ['PATH'])

97. get current username
import getpass
print(getpass.getuser())

98. Convert decimal to hexadecimal
x = 30
print(format(x, '02x'))
x = 4
print(format(x, '02x'))

99. Program to check valid ip address
import socket
addr = '127.0.0.2561'
try:
    socket.inet_aton(addr)
    print("Valid IP")
except socket.error:
    print("Invalid IP")

100. Factorial
def fact(x):
    if x == 0:
        return 1
    return x * fact(x - 1)

x = int(input())
print(fact(x))'''

''' 

101. Define a class which has at least two methods:
getString: to get a string from console input
printString: to print the string in upper case.
Also please include simple test function to test the class methods.
'''

class InputOutString(object):
    def __init__(self):
        self.s = ""

    def getString(self):
        self.s = input()

    def printString(self):
        print(self.s.upper())

strObj = InputOutString()
strObj.getString()
strObj.printString()

102. Write a program that accepts a sentence and calculate the number of letters and digits.
s = input()
d = {"DIGITS": 0, "LETTERS": 0}
for c in s:
    if c.isdigit():
        d["DIGITS"]+=1
    elif c.isalpha():
        d["LETTERS"]+=1
    else:
        pass
print("LETTERS", d["LETTERS"])
print("DIGITS", d["DIGITS"])
'''

103. Define a class, which have a class parameter and have a same instance parameter.
class Person:
    # Define the class parameter "name"
    name = "Person"

    def __init__(self, name = None):
        # self.name is the instance parameter
        self.name = name

manish = Person("manish")
print ("%s name is %s" % (Person.name, manish.name))

bidsar = Person()
bidsar.name = "bidsar"
print ("%s name is %s" % (Person.name, bidsar.name))

104.  Sum of two numbers
def Sum(n1, n2):
    return n1+n2
print(Sum(1,2))

105. Define a class named American and its subclass New Yorker.
class American(object):
    pass
class NewYorker(American):
    pass

anAmerican = American()
aNewYorker = NewYorker()
print(anAmerican)
print(aNewYorker)

106. Define a class named Circle which can be constructed by a radius. The Circle class has a method which can compute the area. 
class Circle(object):
    def __init__(self,r):
        self.radius = r

    def area(self):
        return self.radius**2*3.14

aCircle = Circle(2)
print(aCircle.area())

107. Write a Python program to check that a string contains only a certain set of characters (in this case a-z, A-Z and 0-9).
import re
def check_specific_char(string):
    charRe = re.compile(r'[^a-zA-Z0-9]')
    string = charRe.search(string)
    return not bool(string)

print(check_specific_char("ABCDEFabcdef123456780"))
print(check_specific_char("*&%#!}{"))

108. Write a Python program that matches a word containing 'z'.
import re
def text_match(txt):
    pattern = '\w*z. \w*'
    if re.search(pattern, txt):
        return 'match found!'
    else:
        return 'match not found'

print(text_match("the quick brown fox jumps over the lazy dog."))
print(text_match('python exercise'))

'''
109.  Write a Python program to reverse a string word by word.
class str_reverse:
    def reverse_words(self):
        return ''.join(reversed(s.split()))

print(str_reverse().reverse_words('hello.py'))
'''

110. Strings are immutable sequence of unicode codepoints

''' this is
...a
...multiline
...string.'''

m = 'this string\nspans multiple\n lines.'
print(m)

n = 'this is a \" and a \' in a string.'
print(n)


111. Manipulate list
b = []
b.append(1.64)
print(b)
b.append(3)
print(b)

def square(x):
    return x*x
print(square(5))

''' __name__ is a special python attribute used to evaluates to "__main__" or the actual
...mddule name depending on how the enclosing module is being used'''

## number of blank line between function should be 2

## shebang #!/usr/bin/ is used to determine which interpreter is used to run program

112.  Example on variable
varString = "This is a string variable.  It can have " \
            "any combination of letters, numbers, or " \
            "special characters."

varInteger = 32

varLong = 12345

varFloat = 1290.60

varList = [1, 2, 3.5, "Ben", "Alice", "Sam"]

varTuple = (4, 5, 6.5, "Alex", "Barbara", "Amy")

varDictionary = { 'First': 'The first item in the dictionary',
                  'Second' : 'The second item in the dictionary' }

print(varString)
print(varInteger)
print(varLong)
print(varFloat)
print(varList)
print(varTuple)
print(varDictionary)

18 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. Good Post. I like your blog. Thanks for Sharing
    Python Training in Gurgaon

    ReplyDelete

  3. Core Python interview questions and answers for freshers and 1 to 5 years experience candidate.Learn tips and tricks for cracking python interviews.Coding tag will guide you the best e-learning website that cover all technical and learn technical tutorial based on different languages.

    ReplyDelete
  4. Python is such a wonderfully flexible and object-oriented language that has been created as an open source project. It is cross-platform programming language
    python interview questions

    ReplyDelete
  5. This was relay very helpful thank you. I have also prepared top listed Python Interview Questions for beginners which . Please look into it. And share your feedback by replying my comment.

    ReplyDelete
  6. Thanks for your valuable information .We are also providing Python online training in our institute NareshIT. We are having the best and well trained experienced faculty to train you the Python. By joining in this course you will get complete knowledge about Python. we are giving 100% guidance in placement for our students.

    https://nareshit.com/python-online-training/

    ReplyDelete

  7. The blog is absolutely fantastic! Lot of great information which can be helpful about benefits of developing website. Keep updating the blogs.
    home services app development

    ReplyDelete
  8. Thanks for sharing with us the best python interview career related questions.
    hire python developers in US

    ReplyDelete
  9. This comment has been removed by the author.

    ReplyDelete
  10. Start your journey into Python programming by registering for the challenging Python Course in Hyderabad program by AI Patasala.
    Python Training Hyderabad

    ReplyDelete
  11. amazing blog , you are awesome man Manish Bidsar . keep up the good work.

    ReplyDelete
  12. Python course in Gurgaon
    https://www.wikiful.com/@trainingingurgaon/easy-ways-you-can-turn-python-training-into-success
    If you are searching for the best Python training institute in Gurgaon, APTRON is a notable name among understudies. We have fantastic industry master mentors who help understudies in fostering their idea in Python. You can improve your vocation with a great reasonable Python course in Gurgaon.

    ReplyDelete

Note: only a member of this blog may post a comment.