Download as pdf or txt
Download as pdf or txt
You are on page 1of 21

11/14/21, 10:58 AM Networking And Scripting : Python Interview Questions-2

‫إنشاء مدونة إلكترونية


تسجيل الدخول‬
‫د‬

Networking And Scripting

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
TOTAL PAGEVIEWS
locate the module files imported into a program. It should
include the Python source library directory
4 3 3 8 3
and the directories containing
Python source code. PYTHONPATH is sometimes preset by the Python
installer.
SEARCH THIS BLOG

3. What is the purpose of PYTHONSTARTUP environment variable?

MY POSTS
PYTHONSTARTUP - It contains the path of an initialization file containing
Python source code. It is
"DHCP SNOOPING" " DA
executed every time you start the interpreter. It is
named as .pythonrc.py in Unix and it contains
ARP “Working Example &
commands that load utilities or
modify PYTHONPATH.
BGP "IMP" NOTES
BGP Attributes

4. Is python a case sensitive language?


BGP Basics
BGP In Nutshell "With"Int
Yes! Python is a case sensitive programming language.

BGP MCQ
BGP Overview
5. What are the supported data types in Python?
BGP Q&A
Python has five standard data types −
BGP Scenarios Based Q&
CCNA 200-125 Tips 1: Po
Numbers

CCNA 200-125 Tips 2: Po


String

CCNA 200-125: CHEAT S


List
CCNP Route-300-101: No
Tuple CISSP:Notes

Dictionary
Cisco VPN and ASA Note
DHCP Interview Question
DHCP OPTION 82
6. What are tuples in Python?
DNS: Why and How It Wo
A tuple is another sequence data type that is similar to the list. A tuple
consists of a number of values Dynamic Host Configurat
separated by commas. Unlike lists, however,
tuples are enclosed within parentheses.
EAP: Extensible Authenti
Enabling MD5-Challenge
Ethernet interview questio
7. What is the difference between tuples and lists in Python?

Exam CRAM CCNA-200-


The main differences between lists and tuples are − Lists are enclosed in
brackets ( [ ] ) and their Firewall Q&A
elements and size can be changed, while tuples are
enclosed in parentheses ( ( ) ) and cannot be Frequent used command

updated. Tuples can be thought of


as read-only lists.
Gratuitous ARP "Explana
HTTP Tutorial and Status
Hand notes-CCNA Secur
8.What are Python's dictionaries?
Hand notes-CCNA Secur
Python's dictionaries are kind of hash table type. They work like associative
arrays or hashes found in How to find out TCP Payl
Perl and consist of key-value pairs. A dictionary key
can be almost any Python type, but are usually Hubs vs. Switches vs. Ro

numbers or strings. Values, on


the other hand, can be any arbitrary Python object.
ICMP
ICMP Redirect
IEEE 802.1X (dot1x) Port

https://bidsarmanish.blogspot.com/2017/10/python-interview-questions-2.html 1/21
11/14/21, 10:58 AM Networking And Scripting : Python Interview Questions-2

9.How will you create a dictionary in python?


IP Fragmentation "Explan
IP Fragmentation Q&A
Dictionaries are enclosed by curly braces ({ }) and values can be assigned and
accessed using square
IPv4 & IPv6 “Link-Local A
braces ([]).
IPv4 & IPv6 “Loopback A
IPv6 [Internet Protocol Ve
dict = {}
Interview Q/A Routing &S

dict['one'] = "This is one"


Linux Commands-Cheat S
Linux: Command Line Us
dict[2]     = "This is two"

Native Vs Default Vlan


tinydict = {'name': 'john','code':6734, 'dept': 'sales'}
Network Address Transla
Networking Interview Q&A
10.How will you get all the keys from the dictionary?
PROXY ARP
Packet Flow through Cisc
Using dictionary.keys() function, we can get all the keys from the dictionary
object.

Packet Formats to Reme


print dict.keys()   # Prints all the keys
Packet Transmission: Ro
Protocol Stack Layers
Ping And Traceroute
11.How will you get all the values from the dictionary?

Puzzles and Riddles


Using dictionary.values() function, we can get all the values from the
dictionary object.

Python 2.7 Vs 3.4


print dict.values()   # Prints all the values
Python Basic Programs-1
Python Basic Programs-2

12. How will you convert a string to an int in python?


Python Basic Programs-3
Python Basics -1
int(x [,base]) - Converts x to an integer. base specifies the base if x is a
string.

Python Basics:Cheat She


Python Dictionaries & Dic
13.How will you convert a string to a long in python?
Python Functions
long(x [,base] ) - Converts x to a long integer. base specifies the base if x
is a string.
Python IN Nutshell
Python Important Notes
Python Interview Questio
14.How will you convert a string to a float in python?

Python Interview Questio


float(x) − Converts x to a floating-point number.
Python Interview Questio
Python Lists & Lists Prog

15.How will you convert a object to a string in python?


Python OOPS Basic Exam
Python OOPS Basic Tips
str(x) − Converts object x to a string representation.

Python Quick Reference


Python Script:Generate R
16.How will you convert a object to a regular expression in python?
Python Sets & Sets Progr
repr(x) − Converts object x to an expression string.
Python String & String Pr
Python Tuple & Tuple Pro
Python: (_ & __) in variab
17.How will you convert a String to an object in python?

Python: Difference betwe


eval(str) − Evaluates a string and returns an object.
Python: Interview Questio
Python: Removing Duplic

18.How will you convert a string to a tuple in python?


Python: Script to open a U
Python: Subinterfaces on
tuple(s) − Converts s to a tuple.

Python: if __name__ == '_


Python:Assertion
19.How will you convert a string to a list in python?
Python:Basic Notes
list(s) − Converts s to a list.
Python:Basic Script Expla
Python:Decorators
Python:Fibonacci Sequen
20.How will you convert a string to a set in python?

Python:IMP Programs to
set(s) − Converts s to a set.
Python:Lambda Expressi
Python:Module & Packag

21.How will you create a dictionary using tuples in python?


Python:Reverse a String
RADIUS [Remote Authen
dict(d) − Creates a dictionary. d must be a sequence of (key,value) tuples.

RIB Vs FIB
Rapid Spanning Tree Pro
22. How will you convert an integer to a character in python?
Routing Basics
chr(x) − Converts an integer to a character.
STP NOTES
STP Vs RSTP
STP-BPDU GAURD AND

https://bidsarmanish.blogspot.com/2017/10/python-interview-questions-2.html 2/21
11/14/21, 10:58 AM Networking And Scripting : Python Interview Questions-2

23.How will you convert a single character to its integer value in


python?
STP-BPDU TYPES
STP-PortFast
ord(x) − Converts a single character to its integer value.

STP-ROOT GUARD
Scenarios Based Q&A
24.How will you convert an integer to hexadecimal string in python?
Spanning Tree Interview
hex(x) − Converts an integer to a hexadecimal string.
Spanning Tree Protocol
Spanning Tree Protocol:P
Spirent [STC] points to re
25.What is the purpose of // operator?

Static Route Explanation


// Floor Division − The division of operands where the result is the quotient
in which the digits after TCL EXPECT TUTORIAL
the decimal point are removed.
TCL File Handling with Ex
TCL IMP THINGS TO RE
TCL INTERVIEW QUEST
26.What is the purpose of is operator?

TCL Interview Question -


is − Evaluates to true if the variables on either side of the operator point to
the same object and false TCL List & Basic List Prog
otherwise. x is y, here is results in 1 if id(x)
equals id(y).
TCL NAMESPACE
TCL Overview
TCL PACKAGES
27.What is the purpose break statement in python?

TCL PROC
break statement − Terminates the loop statement and transfers execution to the
statement immediately
TCL String
following the loop.
TCL-Arrays with Example
TCL-Regular Expression

28.What is the purpose continue statement in python?


TCL-Regular Expression
TCP Interview Questions
continue statement − Causes the loop to skip the remainder of its body and
immediately retest its
TCl Basic Programs
condition prior to reiterating.
TestCases for Elevator
Traceroute “Working & Ex
29.What is the purpose pass statement in python?
VLAN & VLAN Types
VPN:Detailed Notes
pass statement − The pass statement in Python is used when a statement is
required syntactically but
VRRP virtual MAC addres
you do not want any command or code to execute.

VRRP-Explanation with E
Virtual Private Network:V
30.How can you get a random number in python?
What happens when you

random() − returns a random float r, such that 0 is less than or equal to r and
r is less than 1.
Writing Test Cases:Basic

31.How will you capitalizes first letter of string?


BLOG ARCHIVE
► 
2016
(35)
capitalize() − Capitalizes first letter of string.

▼ 
2017
(70)
► 
January
(14)
32.How will you check in a string that all characters are digits?
► 
February
(13)
isdigit() − Returns true if string contains only digits and false otherwise.
► 
March
(3)
► 
August
(13)

33.How will you check in a string that all characters are


alphanumeric?
► 
September
(6)

isalnum() − Returns true if string has at least 1 character and all characters
are alphanumeric and false ▼ 
October
(12)
BGP Attributes
otherwise.

Python Dictionaries
& Dictionaries
Programs
34.How will you check in a string that all characters are in
lowercase?

Python
islower() − Returns true if string has at least 1 cased character and all cased
characters are in Script:Generate
Running Config
lowercase and false otherwise.

Python Lists & Lists


Programs
35.How will you check in a string that all characters are numerics?
How to find out
TCP Payloads
isnumeric() − Returns true if a unicode string contains only numeric characters
and false otherwise.
Are Identical
Python: Removing
Duplicate IP’s
36.How will you check in a string that all characters are
whitespaces?

Python Interview
isspace() − Returns true if string contains only whitespace characters and
false otherwise.
Questions-1
Python Interview
Questions-2
37.How will you check in a string that it is properly titlecased?

https://bidsarmanish.blogspot.com/2017/10/python-interview-questions-2.html 3/21
11/14/21, 10:58 AM Networking And Scripting : Python Interview Questions-2

istitle() − Returns true if string is properly "titlecased"


and false otherwise.
Python:Fibonacci
Sequence and
Memoization

38.How will you check in a string that all characters are in


uppercase?
Python Functions
Python Interview
isupper() − Returns true if string has at least one cased character and all
cased characters are in Questions-3
uppercase and false otherwise.
IP Fragmentation
"Explanation &
Examples"
39.How will you merge elements in a sequence?

► 
November
(9)
join(seq) − Merges (concatenates) the string representations of elements in
sequence seq into a string,
► 
2018
(24)
with separator string.

► 
2019
(1)

40.How will you get the length of the string?


TECHNICAL LINKS
len(string) − Returns the length of the string.
BGP NOTES
CCIE Blog
CCIE-Security-Notes
41.How will you remove all leading whitespace in string?

CCNA Tutorial
lstrip() − Removes all leading whitespace in string.
Cisco Certification Books
Cisco Dreamer
42.How will you replaces all occurrences of old substring in string
with new string?
Cisco Easy
CISCO-FMC-FTD
replace(old, new [, max]) − Replaces all occurrences of old in string with new
or at most max
Coding Online
occurrences if max given.

Dumps
FAQ:IP Routing
43.How will you remove all leading and trailing whitespace in
string?
Firewall.CX

strip([chars]) − Performs both lstrip() and rstrip() on string.


GNS3Vault
IT Blogs
Kevin Wallace-Youtube
44.How will you get titlecased version of string?
Online SubnetCalculator
title() − Returns "titlecased" version of string, that is, all words
begin with uppercase and the rest are PluralSight
lowercase.
Python Cheat Sheets
Python Problems
Python Tutorial
45.What is the output of len([1, 2, 3])?

Python Tutorial-Python-
3.
Site
Python-Coding Standard
Python-Download
46.What is the output of [1, 2, 3] + [4, 5, 6]?

Python-Regex-Practise
[1, 2, 3, 4, 5, 6]
Regexp
SNMP-Wiki

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


Strongswan
Subnetting Practice
['Hi!', 'Hi!', 'Hi!', 'Hi!']

TCL Tutorial
Tutorialspoint
48.What is the output of 3 in [1, 2, 3]?

True
NON-TECHNICAL LINKS
ACT
Bangalore One
49.What is the output of for x in [1, 2, 3]: print x?

EPF
1 2 3
IELTS
ITR
50.What is the output of L[2] if L = [1,2,3]?
Lecture-PPT
PF-Passbook
3, Offsets start at zero.

SkillSet
Sphere Social
51.What is the output of L[-2] if L = [1,2,3]?
TAX-Information
L[-1] = 3, L[-2]=2, L[-3]=1
TDS
UAN-PF

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

2, 3, Slicing fetches sections.

https://bidsarmanish.blogspot.com/2017/10/python-interview-questions-2.html 4/21
11/14/21, 10:58 AM Networking And Scripting : Python Interview Questions-2

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

https://bidsarmanish.blogspot.com/2017/10/python-interview-questions-2.html 5/21
11/14/21, 10:58 AM Networking And Scripting : Python Interview Questions-2

    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)

https://bidsarmanish.blogspot.com/2017/10/python-interview-questions-2.html 6/21
11/14/21, 10:58 AM Networking And Scripting : Python Interview Questions-2

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"

https://bidsarmanish.blogspot.com/2017/10/python-interview-questions-2.html 7/21
11/14/21, 10:58 AM Networking And Scripting : Python Interview Questions-2

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)

https://bidsarmanish.blogspot.com/2017/10/python-interview-questions-2.html 8/21
11/14/21, 10:58 AM Networking And Scripting : Python Interview Questions-2

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:

https://bidsarmanish.blogspot.com/2017/10/python-interview-questions-2.html 9/21
11/14/21, 10:58 AM Networking And Scripting : Python Interview Questions-2

    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

https://bidsarmanish.blogspot.com/2017/10/python-interview-questions-2.html 10/21
11/14/21, 10:58 AM Networking And Scripting : Python Interview Questions-2

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

https://bidsarmanish.blogspot.com/2017/10/python-interview-questions-2.html 11/21
11/14/21, 10:58 AM Networking And Scripting : Python Interview Questions-2

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'

https://bidsarmanish.blogspot.com/2017/10/python-interview-questions-2.html 12/21
11/14/21, 10:58 AM Networking And Scripting : Python Interview Questions-2

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)

https://bidsarmanish.blogspot.com/2017/10/python-interview-questions-2.html 13/21
11/14/21, 10:58 AM Networking And Scripting : Python Interview Questions-2

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()

https://bidsarmanish.blogspot.com/2017/10/python-interview-questions-2.html 14/21
11/14/21, 10:58 AM Networking And Scripting : Python Interview Questions-2

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. 

https://bidsarmanish.blogspot.com/2017/10/python-interview-questions-2.html 15/21
11/14/21, 10:58 AM Networking And Scripting : Python Interview Questions-2

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.'

https://bidsarmanish.blogspot.com/2017/10/python-interview-questions-2.html 16/21
11/14/21, 10:58 AM Networking And Scripting : Python Interview Questions-2

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)
Posted by
Manish Bidsar
at
00:40

https://bidsarmanish.blogspot.com/2017/10/python-interview-questions-2.html 17/21
11/14/21, 10:58 AM Networking And Scripting : Python Interview Questions-2
Labels:
Python Interview Questions-2

26 comments:

latesttechnologyblogs 1 November 2018 at 23:03


I like your blog, I read this blog please update more content on python, further check it once at python online training
Reply

Replies

Vijayalakshmi 13 August 2021 at 04:46


Python Course in Bangalore

React Course in Bangalore

Automation Anywhere Course in Bangalore

Blue Prism Course in Bangalore

RPA Course in Bangalore

UI Path Course in Bangalore

Clinical SAS Course in Bangalore

Oracle DBA Course in Bangalore

iOS Course in Bangalore

SolidWorks Course in Bangalore

Reply

amar 24 December 2018 at 20:44


Good Job Thanks for Sharing...

Python Training in Bangalore

Artificial Intelligence (AI) Training in Bangalore

Machine learning Training in Bangalore


Reply

ay 10 March 2019 at 09:46


This comment has been removed by the author.
Reply

Shailendra 20 March 2019 at 02:48


Good Post. I like your blog. Thanks for Sharing

Python Training in Gurgaon


Reply

krystaljoodi@gmail.com 15 April 2019 at 04:46

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.
Reply

krystaljoodi@gmail.com 20 April 2019 at 04:42


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

Reply

ontimedeepakshi 1 October 2019 at 04:44


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.
Reply

Gadwin Co Inger 5 December 2019 at 21:08


The development of artificial intelligence (AI) has propelled more programming architects, information scientists, and different experts to
investigate the plausibility of a vocation in machine learning. Notwithstanding, a few newcomers will in general spotlight a lot on hypothesis
and insufficient on commonsense application. Machine Learning Final Year Projects In case you will succeed, you have to begin building

https://bidsarmanish.blogspot.com/2017/10/python-interview-questions-2.html 18/21
11/14/21, 10:58 AM Networking And Scripting : Python Interview Questions-2
machine learning projects in the near future.

Projects assist you with improving your applied ML skills rapidly while allowing you to investigate an intriguing point. Furthermore, you can
include projects into your portfolio, making it simpler to get a vocation, discover cool profession openings, and Final Year Project Centers in
Chennai even arrange a more significant compensation.

Data analytics is the study of dissecting crude data so as to make decisions about that data. Data analytics advances and procedures are
generally utilized in business ventures to empower associations to settle on progressively Python Training in Chennai educated business
choices. In the present worldwide commercial center, it isn't sufficient to assemble data and do the math; you should realize how to apply
that data to genuine situations such that will affect conduct. In the program you will initially gain proficiency with the specialized skills,
including R and Python dialects most usually utilized in data analytics programming and usage; Python Training in Chennai at that point
center around the commonsense application, in view of genuine business issues in a scope of industry segments, for example, wellbeing,
promoting and account.

Reply

Dhananjay 15 January 2020 at 21:30


Great collection of Python concepts and you can answers many python interview questions after reading this article.
Reply

Unknown 23 May 2020 at 00:19


Good Collectio Of Python question..

Python course in pune

Python classes in pune

python certification in pune

python course fees in pune

software testing institute in pune

software testing course in pune

software testing classes in pune

best software testing institute in pune

Reply

MY NEWS ISSUE 9 June 2020 at 20:10


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/
Reply

Priyanka 15 June 2020 at 19:53


Attend The Machine Learning Course Bangalore From ExcelR. Practical Machine Learning course Bangalore Sessions With Assured
Placement Support From Experienced Faculty. ExcelR Offers The Machine Learning course Bangalore.

Machine Learning Course Bangalore

Reply

latesttechnologyblogs 17 June 2020 at 03:22

Usually I never comment on blogs but your article is so convincing that I never stop myself to say something about it. You’re doing a great
job Man learn Python Online Course

Reply

daisoftware 22 July 2020 at 20:06

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

Reply

swaroop 27 July 2020 at 04:12


This post is really nice and informative. The explanation given is really comprehensive and informative..

Web Designing Training in Chennai

https://bidsarmanish.blogspot.com/2017/10/python-interview-questions-2.html 19/21
11/14/21, 10:58 AM Networking And Scripting : Python Interview Questions-2
Web Designing Course in Chennai

Web Designing Training in Bangalore

Web Designing Course in Bangalore

Web Designing Training in Hyderabad

Web Designing Course in Hyderabad

Web Designing Training in Coimbatore

Web Designing Training

Web Designing Online Training

Reply

Priyanka 12 August 2020 at 20:05


Attend The Artificial Intelligence course From ExcelR. Practical Artificial Intelligence course Sessions With Assured Placement Support
From Experienced Faculty. ExcelR Offers The Artificial Intelligence course.

Artificial Intelligence Course

Reply

Python 19 October 2020 at 04:49


Very useful information, the post shared was very nice.

Python Online Training


Reply

Tecocraft_Python 21 December 2020 at 23:19


Thanks for sharing with us the best python interview career related questions.

hire python developers in US


Reply

Python 18 January 2021 at 03:48


Thank you for sharing.

Data Science Online Training

Salesforce Online Training


Reply

Keerthi55 26 April 2021 at 20:21


This comment has been removed by the author.
Reply

Keerthi55 26 April 2021 at 20:21


will omit your great writing due to this problem.

angular js training

sql server dba training

oracle golden gate training

Reply

IT Trainers 15 July 2021 at 03:26


I liked this article very much. The content is very good. Keep posting.

Python Online Training


Reply

Ramesh Sampangi 5 October 2021 at 05:33


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

Python Training Hyderabad


Reply

bhanu 27 October 2021 at 05:33

https://bidsarmanish.blogspot.com/2017/10/python-interview-questions-2.html 20/21
11/14/21, 10:58 AM Networking And Scripting : Python Interview Questions-2
Thanks for sharing an information to us.

Python Online Training In Hyderabad

Python Online Training

Reply

pawan 28 October 2021 at 22:30


Hi, I read your whole blog. This is very nice. Good to know about the .net and is very demanding in future. We are also providing various
Python Training & Certification Courses, anyone interested can Python Training for making their career in this field.

Reply

Enter your comment...

Comment as:
Google Accoun

Publish Preview

Newer Post Home Older Post

Subscribe to:
Post Comments (Atom)

Picture Window theme. Powered by Blogger.

https://bidsarmanish.blogspot.com/2017/10/python-interview-questions-2.html 21/21

You might also like