We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 80
‘7nai24, 3:44 PM
In
In
In
In
1 string = "Pyth
Python interview codes - Jupyter Notebook
1. Converting an Integer into Decimals
: import decimal
integer = 10
print (decimal .Decimal(integer))
print (type (decimal .Decimal (integer)))
2. Converting an String of Integers into
Decimals
: import decimal
string = '12345'
print (decimal Decimal (string))
print (type(decimal Decimal (string)))
3. Reversing a String using an Extended Slicing
Technique
Programming”
1))
print (strin
4. Counting VOWELS in a Given Word
count = 2
for character in word:
if character in vowel:
count += 1
print (count)
5. Counting CONSONANTS in a Given Word
localhost 8888inotebooks/Python interview codes.ipynbi 11807nai24, 3:44 PM
In[ ]:
In[ ]:
In [14]:
In[ ]:
Python interview codes - Jupyter Notebook
vowel
word
count =
for character in word:
if character not in vowel:
count += 1
print (count)
6. Counting the number of occurances of a
character in a String
word = "progranming”
character = "g"
count = 2
for i in word:
if i == character:
count+=1
print (count)
7. Writing FIBONACCI Series
fib = [0,1]
# Range starts from @ by default
nes
for i in range(n):
fib.append(fib[-1] + fib[-2])
a#Converting the List of integers to string
print(', '.join(str(e) for e in fib))
® 1,1, 2,3, 5,8
8. Finding the Maximum Number in a list
numberList = [12, 3, 55, 23, 6, 78, 33, 4]
max = numberList[o]
for num in numberList:
if max < num:
max = num
print (max)
9. Finding the Minimum Number in a List
localhost 8888inotebooks/Python interview codes.ipynbit 21807nai24, 3:44 PM
In[ ]:
In [ ]:
In[ ]:
Int}:
Python interview codes - Jupyter Notebook
numberList = [12, 3, 55, 23, 6, 78, 33, 4]
min = numberList[a]
for num in numberList:
af min > num:
min = num
print(min)
10. Finding the middle Element in a list
numList = [12, 3, 55, 23, 6, 78, 33, 5]
midelement = int((len(numList)/2))
print (numList [midElement ])
11, Converting a list into a string
ay, Ty
-join(list)
print (string)
print (type(string))
12. Adding Two List Elements Together
Asti
Ast2
= 2,2,3]
= [45,6]
res_ist = []
for i in range(®, len(1sta)):
res_1st.append(1sti[i] + 1st2[i])
print(res_1st)
13. Comparing Two Strings for ANAGRAMS
localhost 8888inotebooks/Python interview codes.ipynbi 1807nai24, 3:44 PM
In[ ]:
In[ ]:
In [ ]:
In [ ]:
Python interview codes - Jupyter Notebook
= stri.replace( )-upper()
str2 = str2.replace(" ","").upper()
if sorted(str1)
print("True")
else:
print("False")
orted(str2):
14. Checking for PALINDROME Using Extended
Slicing Technique
sted ="Kayak".lower()
if str1 == stri[
print("True")
else:
print("False")
15. Counting the white spaces in a string
string = "P rogram in g"
print(string.count(" "))
16. Counting Digits, Letters, and Spaces ina
String
# importing Regular Expressions Library
import. re
name = ‘Python is 2°
digitCount = re-sub("["2-9]", "*,name)
letterCount = re.sub("[*a-2A-z]", "",name)
spaceCount = re.findall("[ \s]", name)
print (len(digitCount))
print(len(1etterCount))
print (len(spaceCount))
localhost 8888inotebooks/Python interview codes.ipynbit 41807nai24, 3:44 PM
In[ ]:
In[ ]:
In[]:
In[]:
Python interview codes - Jupyter Notebook
17. Counting Special Characters in a string
def count_sp_char(string):
sp_char = "1@#$%°8*()<>2/\(]{}
count =
for i in string:
if i in sp_char:
count+=1
return count
text = ‘Hello! How are you? #specialchars! 123°
result = count_sp_char(text)
print (count)
18. Removing All Whitespace in a String
import re
ope"
re.compile(r’\s+")
= re.sub(spaces, "", string)
print (result)
string ope"
string2 = "".join(char for char in string if char !=
print (string2)
‘cope!
string2 = string.replace(" ",""
print (string2)
19. Building a Pyramid in Python
localhost 8888inotebooks/Python interview codes.ipynbi 51807nai24, 3:44 PM Python interview codes - Jupyter Notebook
In [1]: def pyramid(n):
for i in range(n):
for j in range(i,n
print(" “end:
for j in range(i+1
print ("*",end:
for j in range(i):
print ("en
print("")
pyramid(5)
ERE RRR
num=int(input("enetr odd number")) #5
cnt=num//2 #2
scnt=1
for i in range(cnt+1):
print(cnt®" "#"*"*sent)
entecnt-1
sent=sent+2
for i in range('
print(cnt*”
ent-2
entecnt+1
enetr odd numbers
20. Randomizing the Items of a List in Python
localhost 8888inotebooks/Python interview codes.ipynbt 61807nai24, 3:44 PM Python interview codes - Jupyter Notebook
In [ ]: from random import shuffle
Ast = ['Python", ‘is', ‘Easy']
shuffle(1st)
print(1st)
21. Create a generator to produce first n prime
numbers
In [1]: def isprime(num):
for i in range(2, num):
if numXi == 0:
return False
return True
def prime_generator(n):
num = 2
while n:
if isprime(num)
ityield keyword used to return a value and then the code
is resumed inside the function unlike the return keyword end
the code when it is called
ityield keyword will turn any expression that is given with it
into a generator object and return it to the caller
yield num
ne=1
numé=1
x = int(input("Enter no. of prime numbers required"))
it = prime_generator(x)
for e in il
print(e, en
")
Enter no. of prime numbers required 10
2357111317 19 23 29
localhost 8888inotebooks/Python interview codes.ipynbt 71807nai24, 3:44 PM
In [2]:
out[2]:
In [1]:
out[2]:
In [4]:
Python interview codes - Jupyter Notebook
‘program to check if a given number is prime or not
def prime_no(n):
Flag = False
afin < 2:
return Flag
els:
for i in range(2,n):
if nx
return Flag
else:
Flag = True
return Flag
num = int(input("Enter a number
prime_no(num)
Enter a number:37
True
def prime_no(n):
Flag = False
ifn:
return Flag
else:
for i in range(2,n):
if nMi == 0
return Flag
Flag = True
return Flag
num = int(input("Enter a number:"))
prime_no(num)
Enter a number: 25
False
22. Implementing variable length arguments in
python
def average(*t): # *t for tuple of variable Length
avg = sum(t)/len(t)
return avg
result1 = average(32,5,65,22,87,34,2,57)
result2 = average(5,10,15,20,25,30,35,40,45,50)
print("Average is
print("Average is:
result1)
sresult2)
Average is: 38.0
Average is: 27.5
localhost 8888inotebooks/Python interview codes.ipynbt 8/807nai24, 3:44 PM Python interview codes - Jupyter Notebook
In [5]: def average_with_kwargs(**kwargs): # **kwargs for a dictionary of variable Lengi
values = list (kwargs.values())
avg = sun(values) / len(values)
return avg
result = average_with_kwargs(nun=32, nun2:
resutl2 = average_with_kwargs(valuei=5, value:
» num3=65, num4=22, num!
2, value3=15, value
print(#'Average i:
print(#'Average ii
{resulti:.2#}')
{result2:.2}')
Average is: 38.00
Average is: 27.50
23. Creating instance member variables in
python
In [ ]: class Test:
def __init_(self):
# 1st instance variable inside init function
self.a = 5
def f1(self):
# 2nd instance variable inside funcition f1
self.b = 10
t1 = Test()
t2 = Test()
41.10)
# 3rd instance variable
thee 15
print(t1._dict_)
print(t2._dict_)
24. Addition using Lambda functions
In [ ]: # Lanbda function to add two variables
f = lambda a,b : avd
r= £(3,7)
print(r)
#0R
print((ambda a,b:a+b)(3,7))
25. Finding factorial using lambda function
localhost 8888inotebooks/Python interview codes.ipynbt 21807nai24, 3:44 PM
In [14]:
out[14]:
In [13]:
In [ ]:
Python interview codes - Jupyter Notebook
= lambda nn: 1 if
(5)
0 else n*f(n-1)
num = int (input
#7
factorial
if num < 0
print("Sorry, factorial does not exist for negative numbers")
elif nun == 0:
print("The factorial of @ is 1"
else:
for i in range(1,num + 1):
factorial = factorial*i
print(f"The factorial of {nun} is",factorial)
# 5040
Enter a number: "))
1
Enter a number: 3
The factorial of 3 is 6
26. List Compression ( to create a list in single
line)
# List of even numbers
li = [2*e for e in range(1, 10)]
print(11)
# to create a List of even numbers from a given List
List = [23,56,65,22,62, 32, 65,76, 33,99]
12 = [e for e in list if ex2==0]
print (12)
List comprehension is 2 concise and expressive way to create
lists in Python. It provides a more compact syntax for generating
lists conpared to using traditional loops.
27. What is the use of split and join function of
str?
localhost 8888inotebooks/Python interview codes.ipynbt 107807nai24, 3:44 PM Python interview codes - Jupyter Notebook
In [3]: $= “What is right in your mind is right in your world"
Asplit - to convert string into List of string
si=s.split(" ")
print(s1)
si=si[::-1]
print(s1)
#join - to convert the List again into string
print(" ".join(s1))
['what', ‘is', ‘right’, ‘in’, ‘your’, ‘mind’, ‘is', ‘right’, "in", ‘your’, ‘wor
1é']
['world', *your',
at']
world your in right is mind your in right is what
in', ‘right', ‘is’, ‘mind’, ‘your’, ‘in’, ‘right’, ‘is', ‘wh
28. Global and local variable
In [4]: x = 5 # global variable
def #10):
global x
x = 15 # global variable updated
y = 10 # Local variable
print("x=8d y=%d"%(x,y))
£10)
print(x)
x=15 y=10
15,
29. Globals function
In [5]: # globals function returns dictionary
You can use the globals() function to access or modify global variables
fwithin a function or code block.
x = 5 #global variable
def fun():
x = 10 #local variable
d= globals() # d is dictionary
# d['x'] = 15 # x is the key in dictionary d which assigns value to global ve
print( “local x-%d global x-%d"%(x,d["x"]))
fun()
#
local x=1@ global x=5
30. Type conversion basics
localhost 8888inotebooks/Python interview codes.ipynbt 1807nai24, 3:44 PM
In[ ]:
In [1]:
Python interview codes - Jupyter Notebook
= int('123")
float(‘123.42")
complex(*3+4j")
str(a2)
bool(‘True')
bin(25) #binary
oct (25)
hex(25)
ord(’A') #char to unicode
i = chr(98) #unicode to character
print (x,a,b,¢,de,#,8)N,i,5ep="\n")
31. Type conversion
Kes
print (type(x))
sl = '123'
print(type(si))
print(str(x) + s1)
print(x + int(s1))
5123
128
32. What is python decorator ?
localhost 8888inotebooks/Python interview codes.ipynbt
+218074124, 3:44 PM Python interview codes - Jupytar Notabook
In [3]: #function decorator
def welcome(Fx):
def mfx(*t,**d):
print("Before hello function")
fx(*t,**d) #args to take arguments as tuple, **kwargs to take arguments
print("Thanks for using the function")
return mfx
decorator function without arguments
@uelcome
def hello():
print(
‘ello
fdecorator function with arguments
@uelcome
def add(a,b):
print(atb)
hello()
add(1,3)
Before hello function
Hello !
Thanks for using the function
Before hello function
4
Thanks for using the function
In [7]: #class Decorator
class Calculator:
def _init (self, func):
Self. function = func
def _call_(self,*t,**d):
result=self.function(*t, **d)
return result**2
@calculator
def add(a,b):
return atb
# add = Calculator(add)
add(10,2@) #add._call__(a,b) since function type is callable
out[7]: 9¢8
localhost 8888inotebooks/Python interview codes.ipynbt 1918074124, 3:44 PM Python interview codes - Jupytar Notabook
In [2]: # Decorators are used to modify the behavior of functions or methods without
# changing their code.
# Decorator function is a function that takes another functions as there
# argument.
def decor_result (nesult_function):
def distinction(marks):
results = [] # List to store results for each element
for m in marks:
if m >= 75
print ("DISTINCTION")
results.append(result_function({m])) # Pass a List with the current
return results # Return the collected results
return distinction
‘@decor_result
def result(marks):
for m in mark
if m >= 33:
pass
else:
print ("FAIL")
return “FAIL” # Return FAIL if any element fails
els!
print("PASS"
return "PASS" # Return PASS if all elements pass
4# Get the results for each element
results = result([45, 78, 88, 34, 66, 90])
print("Results:", results)
DISTINCTION
DISTINCTION
DISTINCTION
PASS:
In [8]:
Pass
DISTINCTION
PASS
DISTINCTION
Pass:
PASS
Pass
DISTINCTION
PASS
Results: ["PASS', ‘PASS', 'PASS', "PASS', "PASS", 'PASS"]
localhost 8888inotebooks/Python interview codes.ipynbt +41807nai24, 3:44 PM
In [5]:
Python interview codes - Jupyter Notebook
33. What are iterators in python?
An iterable is any Python object that can be looped over or iterated. It can be a sequence (e.9., lst,
tuple, string), a collection (e.g., set, dictionary), or any object that supports iteration,
An iterator used to access the objects of the iterables one by one from 1st element to last element.
An iterator is an object that represents a stream of data. It provides two essential methods: iter()
and next()
11 = [23,65,22,76,34,98,43]
it = iter(11)
while True:
try:
print (next (it))
except Stoplteration:
break
23
65.
22
76
34
98
43
33. What are generators in python? Create a
generator for first n natural even numbers.
Generators in Python are a type of iterable, lke lists or tuples, but they allow you to iterate over
their elements lazily, one at a time, on-the-fly. This means that generators generate values as you
need them, rather than storing all values in memory at once. This can be highly memory-efficient,
especially when dealing with large datasets or when generating an infinite sequence.
localhost 8888inotebooks/Python interview codes.ipynbt 151807nai24, 3:44 PM
In [8]:
In [4]:
Python interview codes - Jupyter Notebook
def evenNum(n):
isa
while nz
yield 2*4
in
ne
it = evenNum(10)
even_list=[]
while True:
try:
even_list. append(next(it))
except StopIteration:
break
print(even_list)
[2, 4 6, 8, 10, 12, 14, 16, 18, 20]
34. Is Function overloading allowed in python ?
In Python, function overloading as seen in languages like C+ or Java is not directly supported
However, Python provides several ways to achieve similar behavior through default arguments,
variable-length arguments, and more advanced techniques like using functools.singledispatch
Here are a few methods to achieve function overloading in Python:
1. Using Default Arguments
‘You can use default arguments to provide different behavior based on the number of arguments
passed,
def greet(nane, greeting="Hello"):
return f"{greeting}, {name}!"
print (greet ("Ashutos!
print(greet("Bob","Hi"))
Hello, Ashutosh!
Hi, Bob!
2. Using Variable-Length Arguments
‘You can use *args and **kwargs to accept a variable number of arguments.
localhost 8888inotebooks/Python interview codes.ipynbt 161807nai24, 3:44 PM
In [5]:
In [14]:
Python interview codes - Jupyter Notebook
def add(*t):
return sum(t)
print(add(1,3))
print(add(1,3,5,6))
15
3. Using functools.singledispatch
‘The functoots.singledispatch decorator allows you to create a single-dispatch generic function,
which can have different implementations based on the type of the first argument.
from functools import singledispatch
@singledispatch
def process(value):
raise NotImplenentedError( "Unsupported type")
@process.register(int)
def _(value)
return #"Processing an integer: {value}"
@process.register(str)
def _(value):
return #"Processing a string: {value]
print(process(19))
print(process("hello"))
Processing an integer: 10
Processing a string: hello
4. Using Class Methods
You can also achieve overloading behavior using class methods.
localhost 8888inotebooks/Python interview codes.ipynbt
‘71807nai24, 3:44 PM
In [9]:
In [2]:
Python interview codes - Jupyter Notebook
class Math:
@staticmethod
def multiply(a,b):
return a*b
@staticmethod
def multiply(a,b,c)
return a*b*c
‘python does not support method overloading, so the Last defined method will be t
4To achieve overloading Like behavior, you can use different method names or vari
class Math:
@staticmethod
def multiply(*t):
result = 1
for num in t:
result *= num
return result
print (Math.multiply(2,3))
print (Math.multiply(2,3,4,5))
120
35. What are positional arguments in python?
There two types of arguments in python, positional arguments and keyword arguments. Keyword
arguments are assigned with the keywords that are defined with the function. Keyword arguments
should always be declared after the positional arguments.
def f1(a, b)
print(
1(3,5) Mpositional argument
4#F1(b=30,5) #syntax error(compile time error)
1(30,b=4)
# FI(2,
1@) type error : multiple values of a (run time error)
1(a=23,b=34) # keyword argument
3, bes
30, b= 4
a= 23, b= 34
36. Difference between sorted and sort function
in python.
Sorted is a predifined function all the iterables in python, which retums a new list in sorted form.
localhost 8888inotebooks/Python interview codes.ipynbt +81807nai24, 3:44 PM
In [51]:
In [49]:
In [56]:
Python interview codes - Jupyter Notebook
tl = (34, 64, 32, 78, 88, 83, 95, 64)
s_t1 = sorted(t1)
print(s_t1)
type(s_t1)
[32, 34, 64, 64, 78, 83, 88, 95]
li = [34, 64, 32, 78, 88, 83, 95, 64]
1i.sort()
print(type(11)) —#nonetype
print(11) #none
[32, 34, 64, 64, 78, 83, 88, 95]
11. append (45)
print(14)
# to add element to list in sorted manner
from sortedcontainers import SortedList
13+SortedList(11)
13.add(2s)
print(13)
[32, 34, 64, 64, 78, 83, 88, 95, 45, 45, 45, 45, 45, 45]
SortedList([32, 34, 45, 45, 45, 45, 45, 45, 45, 64, 64, 78, 83, 88, 95))
37. How to create static member variables in
class?
Static variables are shared among all instances of a class and are typically used to store class-
level data.
Class Method: Use @classmethod when you need to access or modify the class state or call the
method on the class itself. Static Method: Use @staticmethod for utility functions that don't need to
access or modify class or instance state but logically belong to the class.
Static methods are methods that are bound to a class rather than an instance and do not have
access to instance-specific data, To declare a static method, use the @staticmethod decorator
before defining the method
Use Case: Static methods are typically used for uli functions that perform a task in isolation and
do not need to access or modify class or instance data.
Static Variables: a is defined as a static variable directly within the class body. b, c, d, e, and f are
also static variables, but they are defined within methods. g is defined as a static variable outside
the class body.
Instance Variables: x is an instance variable, initialized within the
localhost 8888inotebooks/Python interview codes.ipynbt 197807nai24, 3:44 PM Python interview codes - Jupyter Notebook
Local Variables: y is a local variable, initialized within the init method. It is only accessible within
this method.
In [57]: class myclass:
a=5 #static variable
def __init_(self):
self.x = 1@ #instance variable - can be used anywhere in class using sely
y = 4 #local variable
myclass.b = 34 #static variable
def f1(self,
myclass.c = 65 #static variable
@staticmethod
def £2(self):
myclass.d = 66 #static variable
@classmethod
def £3(cls):
cls.e =15 #static variable
myclass.f = 53 #static variable
myclass.g = 11 #static variable
38.How to use else with loop in python?
Else can be used with if and while loops in python.
After the break statement in the loop the else statement is not executed.
Else statement is only executed when the condition of the loop is false.
In [79]: i214
while ic=10:
print (i, end:
if
break
i
else:
print("You are in else ")
12345
localhost 8888inotebooks/Python interview codes.ipynbt 201807nai24, 3:44 PM Python interview codes - Jupyter Notebook
In [80]: d= 2
while 4c=10:
print (i,end=
if is=12:
els!
print("\n You are in else")
12345678910
You are in else
In [84]: for i in range(10)
print (i, en
if ise12:
break
else:
print("You are in else")
@ 123456789 You are in else
39. What is name mingling in python?
When a variable is initialized with double underscore, its name is automatically changed by python
to _class__variableName. This phenomenon is called Name Mingling in python.
Name mangling is a technique used in programming to generate unique names for entities like
functions and variables to avoid name collisions. This is especially important in languages with
features like function overloading and namespaces. The main purposes of name mangling are:
1. Avoiding Name Collisions: Ensures unique names for entities with the same name in
different scopes or modules.
2. Supporting Function Overloading: Encodes function names with parameter types to
differentiate overloaded functions.
3. Encapsulating Namespaces and Classes: Incorporates namespace or class names into
entity names to maintain uniqueness within different contexts.
4, Linker Compatibility: Helps the linker correctly match references to their definitions across
separate compilation units.
5. Debugging and Maintenance: Makes relationships between code parts clearer, aiding in
debugging and maintenance.
For example, in C++, two functions Foo::display(int) and Bar::display(int) would be
mangled to unique names like _ZN3Foo7displayEi and _ZN38ar7displayéi , incorporating
the namespace and parameter type information
localhost 8888inotebooks/Python interview codes.ipynbt 211807nai24, 3:44 PM
In [4]:
In [2]:
Python interview codes - Jupyter Notebook
class world:
x
— 20
print(world.x)
print (world._world india)
10
20
40. What is difference between class object and
instance object ?
Class object is called only once, instance object can be called any no. of times.
Class object declared with class. object
Instance object is declared with t1 = class(positional arguments) and where the first argument is
instance object(t1) implicitly. Also init method is called implicitly after declaring instance object.
class test:
x = 20
def _init_(self, a, b):
Self.asa_ #instance menber argument
self.b=b #instance menber argument
def show(self):
print(self.a,self.b)
print(test.x) #class object
t1 = test (4,5) #instance object
t1.show()
# Displaying instance variables directly
print(t1.a)
print(t1.b)
20
41. What is init method in python?
init method is just like constructor in c++ and java. But incase of c++ and java if we don't create a
constructor the program creates one implicitly. Incase of python we have create init method
explicitly
localhost 8888inotebooks/Python interview codes.ipynbt
221807nai24, 3:44 PM
In [15]:
In [12]:
Python interview codes - Jupyter Notebook
class test
def _ init__(self):
self.a = 10
self.b = 20
ti = test() tno need to provide the arguments
print(ti.a, t1.b)
10 20
42. What are default arguments in functions?
The arguments that are declared and assigned a value while creating a function are called default
arguments.
Itis not allowed to have non-default arguments after default arguments.
: def add(a, b, c=5): # ¢ is default argument
return atb+c
s = add(2,3)
print("The addition is: ",s)
The addition is: 10
43. Extract int type values from a list of
heterogeneous element?
11 = ['abc',34.56, 32,3443, "b',55,65.7,'90",180]
print(11)
12 =[]
for ¢ in 11:
Af type(e)=-int:
12.append(e)
print(12)
['abe', 34.56, 32, (3445),
[32, 55, 180)
55, 65.7, '98', 180]
44. Does python support multiple inheritance?
‘When a class inherits attributes from more than one class it is called muttiple inheritance,
Python supports multiple inheritance.
localhost 8888inotebooks/Python interview codes.ipynbi 231807nai24, 3:44 PM
In [14]:
In [5]:
Python interview codes - Jupyter Notebook
class B(AL, A2):
pass
45. What is monkey patching ?
Monkey patching is replace a function object with a new function object, so that the function is now
pointing to new function object. Mostly used when you want to replace a function for testing
purpose.
class Test:
def _init_(self,x):
self.a = x
def get_data(self):
print("send code to fetch data from database")
def 1(self):
self.get_data()
def 2(self):
self.get_data()
tisTest(4)
print("Before Monkey patching\n ")
t1.f1()
+1.2()
def get_new_data(self):
print("Some to code fetch data from test data")
Test.get_data = get_new_data
print(*\nafter Monkey Patching\n")
t1.f1()
t1.f2()
Before Monkey patching
send code to fetch data from database
send code to fetch data from database
After Monkey Patching
Some to code fetch data from test data
Some to code fetch data from test data
46. Accept a number user check whether it is
prime or not
localhost 8888inotebooks/Python interview codes.ipynbt 24807nai24, 3:44 PM
In [2]:
In [3]:
In [9]:
Python interview codes - Jupyter Notebook
num=int(input("enetr number*))
for i in range(2,num)
if nun:
print
break
else:
print(*number is prime")
wumber is not prime")
enetr number47
number is prime
47. Write a program to print the given number is
odd or even.
num = int(input("Enter a number: "))
if nunk2==0:
print(f"Entered number {num} is even")
else:
print(f"Entered number {num} is odd")
Enter a number: 34212
Entered number 34212 is even
48. Write a program to find the given number is
positive or negative.
nun = float(input("Enter 2 nunber: "))
if nun > 0:
print("Nunber is positive")
elif num==0:
print(*Nunber is zero")
else:
print(*Nunber is negative")
Enter a number: 4
Number is positive
49. Write a program to find the sum of two
numbers.
localhost 8888inotebooks!Python interview codes.ipynbit 251807nai24, 3:44 PM
In [12]:
In [18]:
out[18]:
Python interview codes - Jupyter Notebook
num = int(input("Enter ist number
num2 = int(input("Enter 2nd number:
print(*numl + num2 =",numi+num2)
Enter 1st number: 3333
Enter 2nd number: 666
umd + num2 = 3999
50. Write a program to find GCD of two
numbers.
numa
num2,
int(input("Enter 1st number
int(input("Enter 2nd number
def gcd(a,b):
if
elif b==0:
return a
elif arb:
return gcd(a-b,b)
return gcd(a,b-a)
gcd(numt, nun)
Enter Ist number: 235
Enter 2nd number: 875
5
51. Write a program to print the following
pattern.
localhost 8888inotebooks/Python interview codes.ipynbi
261807nai24, 3:44 PM
In [7]:
In [32]:
Python interview codes - Jupyter Notebook
s = int(input("Enter a nunber*))
for i in range(1,s+1):
print("™* "#i)
ited
Enter a numbers
52.Write a program to print the following
pattern.
s (input("Enter a number"))
for i in range(1,s+1):
for j in range(1,i+1):
print(j,end="_")
print()
dte1
Enter a numbers
2
23
234
2345
53. Write a program to print the following
pattern.
localhost 8888inotebooks/Python interview codes.ipynbi 271807nai24, 3:44 PM
In [8]:
Python interview codes - Jupyter Notebook
def tri(n)
num=1
for i in range(@,n):
for j in range(0,i+1)
print(num, end=
fum+=1
print()
tri(s)
ai on HH
s = int(input("Enter a number: "))
for i in range(1,s#1
for j in range(1
print(p,end=
pis
print()
heed
ist):
1
23
456
78910
11 12 13:14 15
Enter a number: 5
1
2
4
7
1
3
56
8910
112 13 14 15,
54, Write a program to print the following
pattern.
localhost 8888inotebooks/Python interview codes.ipynbit
2818074124, 3:44 PM
In [9]:
In [13]:
Python interview codes - Jupytar Notabook
def apha(n):
p=65
for i in range(n):
for j in range(i+1):
ch = chr(p)
print(ch, end:
ptet
print()
apha(s)
ait on Hit
int(input("Enter a number:
5
for i in range(1,s+1):
for j in range(1,i+1):
print(chr(p) , end:
pest
print()
ite
8
¢
D
mon
E
ater a number: 5
moneemmoner
mone
mon
def apha(n):
p=65
for i in range(n):
for j in range(i,n):
ch = chr(p)
print(ch, end:
pes
print()
apha(s)
AA
B
mone>
onw>
oo>
localhost 8888inotebooks/Python interview codes.ipynbit
221807nai24, 3:44 PM Python interview codes - Jupyter Notebook
In [23]: def apha(n):
p=65
for i in range(n):
for j in range(i,n):
print(" ",end=
for j in range(i+1):
print(chr(p), en
for j in range(i):
print(chr(p), end=
pest
print()
apha(5)
55. Write a program to print the following
pattern.
localhost 8888inotebooks/Python interview codes.ipynbit
30/8074124, 3:44 PM
In [3]:
In [8]:
Python interview codes - Jupytar Notabook
def apha(n):
pe65
for i in range(n):
for j in range(i+1):
ch = chr(p)
pei
print(ch, end:
print()
apha(s)
iit on Hit
n= int(input("Enter a number:
p= 65
for i in range(n):
for j in range(i+1):
print(chr(p) , end:
pe=d
print()
A
B
Dd
6
kK
=H
°
p=65
for i in range(n):
for j in range(i+1):
print(” ",end=
for j in range(i,n):
print(chr(p) , end:
pial
print()
ABCDE
FGHI
JKL
MN
°
localhost 8888inotebooks/Python interview codes.ipynbit
31/807nai24, 3:44 PM Python interview codes - Jupyter Notebook
In [12]: eS
p=65
for i in range(n):
for j in range(i,n):
print(" ",end=
for j in range(i+1)
print(chr(p),end="_")
pes.
print()
)
D
H
B
E
I
WN
6
KL
In [ ]: def apha(n):
p=65
for i in range(n):
for j in range(i,n
print(” "jen
for j in range(i+1
print(chr(p), end=
for j in range(i):
print(chr(p), end='
apha(5)
56. Write a program to print the following
pattern.
localhost 8888inotebooks/Python interview codes.ipynbit 32/807nai24, 3:44 PM Python interview codes - Jupyter Notebook
In [2]: def apha(n):
num = 65
for i in range(n):
for j in range(i,n)
print(" “,end="")
for j in range(i+1):
print(chr(num),end =" ")
fum+=1
num = 65
print()
apha(s)
A
AB
ABC
ABCD
ABCDE
57. Write a program to print the following
pattern.
ce a
Perera ee)
In [3]: def apha(n):
num = 65
for i in range(n+1):
for j in range(n-i):
print( ")
for j in range(1,i+1)
print(chr(num), end
num+=1
print("")
apha(s)
A
Bc
DEF
GHrI3
KLMNO
localhost 8888inotebooks/Python interview codes.ipynbi
33/807nai24, 3:44 PM Python interview codes - Jupyter Notebook
58. Write a program to create pyramid with 5
rows.
In [6]: n=5
for i in range(n):
for j in range(i,n):
print(” ",end=" "
print()
In [7]: ne5
for i in range(n):
for j in range(i,n)
print(" "yen
for j in range(i+1
print("*",end=" “
print()
59. Create a sandglass pattern.
localhost 8888inotebooks/Python interview codes.ipynbt 4/807nai24, 3:44 PM
In [54]: ne
for i in range(n):
for j in range(i+1)
print(""end="
for j in ran
print("*
print()
for i in range(n):
for j in range(isn)
print("",end="
for j in range(i+1)
print ("en
print()
59. Create a butterfly pattern.
localhost 8888inotebooks/Python interview codes.ipynbit
Python interview codes - Jupyter Notebook
35/807nai24, 3:44 PM
In [13]:
In [73]:
Python interview codes - Jupyter Notebook
neS
for i in range(n):
for i in range(n):
for j in range(i,n-2
print ("en
print(” ",en
for j in range(i+1)
print(” ",end=
for j in range(i,n-2
print("*",end="
print()
60. Create a reverse pyramid.
nS
for i in range(n):
for j in range(i+1)
print(" "jen
for j in range(i,n):
print("*" end=
print()
61. Create a hill triangle pattern.
localhost 8888inotebooks/Python interview codes.ipynbit
381807nai24, 3:44 PM Python interview codes - Jupyter Notebook
1
123
12345
1234567
123456789
In [82]: n=5
for i in range(n):
pel
for j in range(i,n):
print(" ",en
for j in range(i
for j in range(i+1):
print(p,end=" ")
pest
print()
Bune
anew
62. Create the following pattern.
54321
4321
321
21
1
localhost 8888inotebooks/Python interview codes.ipynbi 371807nai24, 3:44 PM Python interview codes - Jupyter Notebook
In [94]:
p=5
for i in range(n):
kp
for j in range(i+1)
print(* ",end=
for j in range(i,n)
print(k,end="_")
ke=1
pest
print()
54
4
63. Create the diamond patterns
1
222
33333
4444444
555555555
6666666
77777
88s
9S
localhost 8888inotebooks/Python interview codes.ipynbi 38/807nai24, 3:44 PM
In [107]:
for i in range(n-1):
for j in range(i,n)
print(” ",end
for j in range(i+1
print(p, end:
for j in range(i)
print(p,end:
pie
print()
for i in range(n):
for j in range(i+1)
print(” ",end:
for j in range(:
print(p,end
for j in range(iti,n):
print(p,end="
piel
print()
awe
@Vannwn
@Vannwn
aus
localhost 8888inotebooks/Python interview codes.ipynbt
Python interview codes - Jupyter Notebook
1
222
33333
4444444
555555555
4444444
33333
222
1
39/807nai24, 3:44 PM
In [115]:
for i in range(n-1):
for j in range(i,n):
print(" "en
for j in range(i+1)
print(p, end:
for j in range(i
print(p, end:
P
print()
for i in range(n):
for j in
for j in range(isn):
print(p,end="
for j in range(i+1,n):
print (p, en
print()
aus
wonaeun
No kaeow
Boe
Python interview codes - Jupyter Notebook
64. Print the following pattern.
localhost 8888inotebooks/Python interview codes.ipynbt
A
cc
EEE
GGGG
Piriid
401807nai24, 3:44 PM Python interview codes - Jupyter Notebook
In [16]:
$
for i in range(n):
for j in range(i+1):
print (che(p),en
pts2
print()
A
cc
EEE
6666
TIQIIaT
ZZZZZZZZZ
oa000000
Z2ZZZ2zZ
ooo
22
0
In [24]:
i in range(n):
for j in range(i+1)
print(" "yen
for j in range(i,n)
if x2
print("z",end=" ")
else:
print("o" end:
for j in range(i,n-1)
if in2==0:
print(*z
else:
print(”
print()
oNONON
localhost 8888inotebooks/Python interview codes.ipynbit 411807nai24, 3:44 PM
Python interview codes - Jupyter Notebook
A
ABC
ABCDE
ABCDEFG
ABCDEFGHI
In [33]: n=5
for i in range(n):
p=65
for j in range(i,n):
print(" ",end="
for j in range(i):
print(chr(p),end="
pi=i
for j in range(i+1)
print(chr(p),end="
pi=i
print ()
A
ABC
BCD
CDE
DEF
ne>
E
FG
AB GHI
")
")
A
BCD
EFGHI
JKLMNOP
QRSTUVWXY
localhost 8888inotebooks/Python interview codes.ipynbit
421807nai24, 3:44 PM Python interview codes - Jupyter Notebook
In [35]:
s
for i in range(n):
for j in range(i,n):
print( "jen
for j in range(i):
print (chr(p) end
pe.
for j in range(i+1)
print(chr(p),end:
peel
print()
<220
<
EDCBA
EDCB
EDc
ED
In [42]: ne
for i in range(n):
p=69
for j in range(i+1)
print(* "jen
for j in range(i,n)
print (chr(p),en
po=1
print()
ED
E
localhost 8888inotebooks/Python interview codes.ipynbit 431807nai24, 3:44 PM Python interview codes - Jupyter Notebook
EDCBA
DCBA
CBA
BA
A
In [49]: n=s
k=69
for i in range(n):
p-k
for j in range(it1)
print(” "yen
for i in range(i,n)
print (chr(p) ,end=
E
DED
CDEDC
BCDEDCB
ABCDEDCBA
localhost 8888inotebooks!Python interview codes.ipynbit 44807nai24, 3:44 PM Python interview codes - Jupyter Notebook
In [72]:
9
for i in range(n):
pk
for j in range(i,n)
print(* "Jeni
for j in range(i):
print (che(p),end=
pest
for j in range(i+1)
print(chr(p),end="
po=i
print()
A
ABA
ABCBA
ABCDCBA
ABCDEDCBA
localhost 8888inotebooks!Python interview codes.ipynbit 45807nai24, 3:44 PM
In [69]: ne
for i in range(n):
p65
for j in range(i,n):
print(" "en
for j in range(i
print (chr(p) , end:
pest
for j in range(i+1)
print(chr(p),end:
p-=1
print()
a>
ne>
ona>
ona>
ne>
a>
In [73]: s="CODER"
en(s)
for i in range(n):
for j in range(i+1)
print(s[p],end="
peel
print()
localhost 8888inotebooks/Python interview codes.ipynbt
Python interview codes - Jupyter Notebook
oo
DDD
EEEE
RRRRR
461807nai24, 3:44 PM Python interview codes - Jupyter Notebook
R
EE
DDD
oooo
ccccc
In [74]:
for i in range(n):
for j in range(i+1
print(s[p],end:
pest
print()
R
EE
Doo
0000
cecce
co
coD
CODE
CODER
localhost 8888inotebooks!Python interview codes.ipynbit 471807nai24, 3:44 PM Python interview codes - Jupyter Notebook
In [76]: s="CODER"
en(s)
for i in range(n):
p=0
for j in range(i+1)
print(s[p],end:
pe
print()
c
co
cop
CODE
CODER
REDOC
EDOC
DOC
oc
c
In [80]:
for i in range(n):
p-k
for j in range(i+1)
print(" ",end=
for j in range(isn)
print(s[p],end="
p=
print()
k
Doc
Doc
Doc
oc
c
localhost 8888inotebooks/Python interview codes.ipynbit 4218074124, 3:44 PM
In [18]: # square matrix
=o
for i in range(n):
for j in range(n):
print("*",en
print()
localhost 8888inotebooks/Python interview codes.ipynbit
Python interview codes - Jupytar Notabook
SIMPLY o:
print("Yes")
else:
print("No")
print("No of zeros in number:", count)
Yes
No of zeros in number: 4
69. Check if the number is Neon number.
Number, digits of whose square are equal to the
number itself.
In [30]:
n//1
if sumzsn:
print("Yes")
else:
print ("No")
70. Check if a number is automorphic number or
not. It is a number which is contained in the last
digit(s) of its square. eg. 25 in 625.
localhost 8888inotebooks/Python interview codes.ipynbi 58/807nai24, 3:44 PM
In [39]:
In [3]:
In [7]:
Python interview codes - Jupyter Notebook
print("Yes")
print("No")
No
71, Check if a number is Krishna Murthy special
number or not. A number which is equal to the
sum of factorial of its digits. eg. 145 = 1!+4!+5!
import math
n=145
sumz@
while mi=0:
demX10
sum=suntmath.factorial(d)
mm=m//10
if sumeen:
print("Yes")
else:
print ("No")
No
72. Find the factors of a number.
nsint(input("Enter a nunber: *))
for i in range(1,n+1):
if nXizs0:
print (i,end=
Enter a number: 45
135915 45
73. Find if a number is prime or not.
localhost 8888inotebooks!Python interview codes.ipynbit 59/807nai24, 3:44 PM
In [17]:
In [19]:
In [12]:
Python interview codes - Jupyter Notebook
neint(input("Enter a number: "))
count=0
for i in range(1,n+1):
if nXi==0:count+=1
Enter a number: 23
Prime
74, Find if a number is a perfect number. A
number is equal to sum of its factors or divisors,
other than the number itself.
n=int(input("Enter a number: "))
sum=@
for i in range(1,n-1):
if nXis=0:
sum=sum+i
if n==sum:
print("Yes")
else:
print("No")
Enter a number: 6
Yes
75. Find if a number is composite number or not.
Anumber having more than one factor other than
1 and itself.
nsint(input("Enter a number: "))
count=0
for i in range(1,n+1):
if nXi==@:counte=1
if count:
print ("Composite number")
else:
print ("Not a Composite number")
Enter a number: 34
Composite number
76. Find if the number is an abundant number or
deficient . Here the sum of factors of the number
localhost 8888inotebooks!Python interview codes.ipynbit 601807nai24, 3:44 PM
In [1]:
In [12]:
Python interview codes - Jupyter Notebook
is greater than the number itself.
neint(input("Enter a number: "))
sun=0
for i in range(1,n):
if nXiz=0:
sum=sum+i
if sumon:
print("Abundant number")
else:
print("Deficient number")
Enter a number: 34
Deficient number
77. Find if the number is pronic or not. Number
which is the product of two consecutive
numbers.
n=int(input("Enter a number: "))
fact=0
for i in range(1,n+1):
if (i*(i41)==n):
yx 41} = {n}")
if fact>o:
print("Pronic number")
else:
print("Not a Pronic number number”)
Enter a number: 56
7x8 = 56
Pronic number
78. Arithematic series - sequence where the
difference between two consecutive terms are
the same.
1+24+3+4'...N
localhost 8888inotebooks!Python interview codes.ipynbit 6118074124, 3:44 PM Python interview codes - Jupyter Notebook
In [7]:
nt (input (" Enter N: "))
su
for i in range(1,N+1):
sum=sum + i
print("Sum of series: “,sum)
Enter N: 20
Sum of series: 210
In [6]: Ne
nt (input(" Enter Nz "))
for i in range(1,N+1):
sum=sum + a
area
print ("Sum of series: ",sum)
In [8]: Neint(input(" enter N: *))
for i in range(1,Ne1):
sum=esum + a
a
print ("Sum of series: ",sum)
Enter N: 20
Sum of series: 420
localhost 8888inotebooks/Python interview codes ipynbi 6218074124, 3:44 PM Python interview codes - Jupyter Notebook
In [9]: Neint(input(" Enter N: *))
for i in range(1,N+1):
sum=sum + a
a
print ("Sum of series: ",sum)
Enter N: 20
Sum of series: 400
In [12]: Nednt(input(" Enter Nz "))
for i in range(1,Ne1):
sum=sum + a
print("Sum of series: ",sum)
Enter N: 10
Sum of series: 55
In [23]: Neint(input(" enter N: "))
nt (input ("Enter x: "))
sum=@
@
for i in range(1,Ne1):
sum=sum + X*
print("Sum of series: ",sum)
Enter N: 10
Enter x: 3)
Sum of series: 88572
localhost 8888inotebooks/Python interview codes ipynbt 6318074124, 3:44 PM Python interview codes - Jupyter Notebook
In [15]: import math as m
nt(input(" Enter N: "))
(=int (input (“Enter X: "))
for i in range(1,N+1):
‘sum=sumem, factorial (a)/X
ated
print ("Sum of series: ",sum)
Enter N: 10
Enter x: 2
Sum of series: 5.981112715901029e+55
In [16]: Neint(input(" Enter N: "))
Xzint (input (“Enter x: "))
for i in range(1,N+1):
sum=sum + a**X
a
print("Sum of series: ",sum)
Enter N: 20
Enter X: 2
Sum of series: 1148@
In [17]:
for i in range(1,N+1):
sum=sum + (a*#3)/X
print("Sum of series: ",sum)
Enter N: 20
Enter xX: 2
Sum of series: 159800.0
localhost 8888inotebooks/Python interview codes.ipynbi74124, 3:44 PM
In [19]:
In [5]:
Python interview codes - Jupytar Notabook
Neo
‘sum=@
a2
be10
for i in range(1,N+1):
sum=sum + a/b
print("Sum of series: ",sum)
Sum of series: 44,43730158730159
79. Geometric Series - Every term is derived by
multiplying previous term by a fixed number.
Neint (input ("Enter N: "))
sum=@
a2
for i in range(1,N+1):
sum=sum + a*2
aza*2
print("Sum of series: ",sum)
Enter N: 20
Sum of series: 4194300
localhost 8888inotebooks/Python interview codes ipynbi 6518074124, 3:44 PM
In [8]:
In [9]:
In [22]:
Python interview codes - Jupytar Notabook
nt (input (“Enter N: "))
for i in range(1,N+1):
sum=sum + a
azat3
print ("Sum of series: ",sum)
Enter N: 20
Sum of series: 3486784400
Neint(input (“Enter N: "))
@
for i in range(1,N+1):
sum=sum + a
azat3
print("Sum of series: ",sum)
Enter N: 20
Sum of series: 17433922000
Neint (input ("Enter N: "))
sum=@
ass,
for i in range(1,Ne1):
sum=sum + a
aza*3
print ("Sum of series: ",sum)
Enter N: 10
Sum of series: 147620
localhost 8888inotebooks/Python interview codes ipynbi
6618074124, 3:44 PM Python interview codes
upyter Notebook
In [12]: Neint(input("enter N: "))
nt (input (“Enter x: "))
for i in range(1,Ne1):
sum=sum + X/a
aza*2
print("Sum of series: ",sum)
Enter N: 10
Enter x: 2
Sum of series: 1.998046875
In [16]:
l=int (input (“Enter Nz "))
for i in range(1,N+1):
if 1x2
sum=sum=a
else:
sum=sumea
azat3
print("Sum of series: ",sum)
Enter N: 20
Sum of series: -1743392200
In [17]: Neint(input("Enter N: "))
int (input (“Enter x: "))
b=10
for i in range(1,N+1):
‘sum=sum+(Xta)/b
print("Sum of series: ",sum)
Enter N: 10
Enter X: 2
Sum of series: @,7499364934207186
localhost 8888inotebooks/Python interview codes.ipynbi
678074124, 3:44 PM
In [1]:
In [18]:
Python interview codes - Jupytar Notabook
import math as m
meine
for i in range(1,Né2):
‘sun=sum+(X*a**2)/(itm. factorial (b))
ara*5;b4=1
print("Sum of series: ",round(sum,2))
Enter N: 5
Enter X: 2
Sum of series: 34570.38
80. Convert Numbered string by reversing and
converting to character string using ascii values
[A-Z]=65-90 and [a-z]=97-122.
ssinput(‘Enter the string: ') #796115110113721110141108
se s[:2-1
print(s)
0
res:
while(iclen(s)=1):
xes(i]+s[i+1]
res=res+!
elif int(x) in range(6s, 91) or int(x) in range(97,123):
res=res+chr(int(x))
elif i+2
83. File Handling in python
In [5]: # reading a file
fhand = open(‘mbox-short.txt')
inp = fhand.read()
print(1en(inp))
print (inp[ :20])
94626
From stephen.marquar
localhost 8888inotebooks/Python interview codes.ipynbt 78074124, 3:44 PM Python interview codes - Jupytar Notabook
In [14]: # reading a file
fhand = open(‘mbox-short.txt')
for line in fhand:
if Line. startswith( “From
print (Line)
):
localhost 8888inotebooks/Python interview codes.ipynbt
75,807nai24, 3:44 PM
From: stephen.marquard@uct.
From: [email protected].
Fror
[email protected]
From: rjloe@iupui .edu
From: [email protected]
From: rjlowe@iupui edu
From: [email protected]
From: [email protected]
Fror
: [email protected]
From: [email protected]
Fror
[email protected]
Fror
[email protected]
Froy
[email protected]
Fror
[email protected]
Fror
Python interview codes - Jupyter Notebook
edu
[email protected]
From: [email protected]
From: david. [email protected].
From: [email protected].
Fror
Fror
Fror
Fror
Fror
Fror
From: [email protected]
From:
[email protected]
From: [email protected]
localhost 8888inotebooks/Python interview codes.ipynbt
: david.horwitz@uct .ac.
: [email protected].
stephen. marquard@uct.
Loui sfmedia.berkeley.
Loui sémedia.berkeley.
za
za
za
za
ac.za
edu
edu
[email protected]
761807nai24, 3:44 PM Python interview codes - Jupyter Notebook
In [15]: |# reading a file
fhand = open(‘mbox-short.txt")
for line in fhand:
line = Line.rstrip()
Af Line. startswith("Fron:"):
print (Line)
[email protected]
: louis@media. berkeley. edu
[email protected][email protected][email protected]
+ [email protected]
: [email protected]
: [email protected]
: [email protected][email protected]
: [email protected]
: [email protected]
2 wagnermp@iupui .edu
: [email protected][email protected][email protected][email protected]
: [email protected][email protected]
+ [email protected][email protected]
: [email protected][email protected][email protected][email protected][email protected][email protected]
localhost 8888inotebooks/Python interview codes.ipynbt
771807nai24, 3:44 PM
In [17]:
In [2]:
Python interview codes - Jupyter Notebook
# reading a file
fhand = open('mbox-short. txt!)
for line in fhand:
line = Line.rstrip()
Af not Line.startswith("From:"):
continue
print(Line)
+ [email protected]
Loui sémedia.berkeley.edu
[email protected][email protected]
+ [email protected]
: rjlowe@iupui .edu
: [email protected][email protected][email protected]
: [email protected]
2 [email protected]
: [email protected]
: wagnermr@iupui .edu
[email protected][email protected][email protected]
: [email protected][email protected]
+ [email protected]
david [email protected]
+ [email protected]
Loui [email protected]
Loui sémedia.berkeley.edu
[email protected][email protected][email protected][email protected]
# input file name to read and handle exceptions
fname = input("Enter the file name
fhand = open(fname)
except:
print("File cannot be opened:", fname)
exit()
count = @
for line in fhand:
if Line. startswith('Subject:')
count = count + 1
print(‘There were’, count, ‘subject lines in’, fname)
Enter the file name:mbox-short.txt
There were 27 subject lines in mbox-short.txt
localhost 8888inotebooks/Python interview codes.ipynbit
e1807nai24, 3:44 PM Python interview codes - Jupyter Notebook
In [7]: # writing files
fout = open(*output.txt’, ‘w")
print(fout)
linet = "This is the first line\n"
fout.write(line1)
line2 = "This is the second Line\n"
fout.write(line2)
# Close the file after writing
fout.close()
# Open the file in read mode
fout = open(‘output.txt', 'r')
# Read the contents of the file
inp = fout.read()
print (inp)
# Close the file after reading
fout .close()
<_1o. TextLOWrapper name
This is the first line
This is the second line
Jo.
‘output.txt’ mode:
84. When you encounter a line that starts with "X-DSPAM-Confidence:" pull apart the line to
12. Count these lines and then compute the total of
extract the floating-point number on the
the spam confidence values from these lines. When you reach the end of the file, print out the
average spam confidence.
localhost 8888inotebooks/Python interview codes.ipynbt
e1807nai24, 3:44 PM Python interview codes - Jupyter Notebook
In [5]: try:
fname = input("Enter file name:
fhand = open(fname)
except:
if fname == ‘na na boo boo":
print("NA NA B00 B00 TO YOU - You have been punk'd
else:
print("Please enter correct file name:",fname)
count = @
total = @
try:
for line in fhand:
if Line. startswith("
count = count #2
start = line.find(” ")
num = float(line[start:])
total += num
avg = total/count
print (“Average spam confidence
except ZeroDivisionError:
print("C")
-DSPAM-Confidence
vave)
Enter file name:na na boo boo
NA NA B00 800 TO YOU - You have been punk'd!
In[ ]:
localhost 8888inotebooks/Python interview codes.ipynbt
0180