0% found this document useful (0 votes)
24 views63 pages

2.python-Interview Questions

PYTHON-INTERVIEW QUESTIONS

Uploaded by

bpkdeveloper45
Copyright
© © All Rights Reserved
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
0% found this document useful (0 votes)
24 views63 pages

2.python-Interview Questions

PYTHON-INTERVIEW QUESTIONS

Uploaded by

bpkdeveloper45
Copyright
© © All Rights Reserved
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/ 63
‘7 a ues See oar Aue 4 rs 4 i is ea i e: | ~— ~~ | ee RED eer er ees Ce Seema 3) Scr. = .. Ream et ae eect INOW WHTCH THIS VEDIO : Python interview questions and answers in telugu a as eee ee eek ee eee) Bases ore] eels serene nee er ¥ High-level, interpreted & object-oriented scripting language y¥ Readable code and large library Enables programmers to Y Works on all operating systems feus 9” solutions rather than syntax i) Always go prepared to answer basic questions well ji) They set the tone for the interview et rue Beri letereresr eet te Y¥ Open Source Language ¥ Supports both procedure-oriented & object-oriented programming ¥ Interpreted language y¥ Dynamically-typed, Automatic memory management ¥ Interfaces to all major databases ycan be integrated with C, C++, COM, ActiveX, CORBA & Java. ¥ Portable ‘ erase te Y Private heap containing Python objects and data arcu ¥ Allocation of heap space for Python objects taken care of by Python memory manager ¥ Built-in garbage collector recycles all unused memory a aa y¥ Like a real-world dictionary vy Stores data as key-value pairs ¥ Member of a directory accessed using key vy Key separated from it value by colon (:) ¥ Key, value pairs separated by comma (,) vo Immutable list of Python objects ¥ Once assigned, Tuple elements can’t be changed ¥ Used to store read-only collections ¥ Written as a collection of comma-separated values enclosed with round brackets ¥ Lists are mutable and written with square brackets vo Immutable list of Python objects ¥ Once assigned, Tuple elements can’t be changed ¥ Used to store read-only collections ccteeeieee seleeieeeeenatly ¥ Written as a collection of comma-separated values enclosed with round brackets y¥ Lists are mutable and written with square brackets ¥ // Floor Division Division operation Result — Quotient with decimal values removed Example ifa=5,b=2thena//b=2 Bez 1d Experienced Candidates vy %: Modulus Returns remainder when left hand operand is divided by right hand operand. Example if a=50, b=10 then a%b =0 ¥ **: Exponent Performs exponential calculation on operands. . Example ~ a**b means a raised to the power of b | Break Continue | Pass Causes programto - Returns the control Causes program exit from the loop to the beginning of control to pass by when the conditionis the loop without executing met - Causes programto any code skip all the remaining statements in the current iteration of the loop | remove fe Removes first Deletes elements matching value using their index. Doesn’t return any value Example Example list=[1,2,3,4] list = [4,5,6,7,8] list.remove(2) del list[1] # Updated list # Updated list \ (1, 3, 4] [4,6,7,8] ye Removes element by index. Returns removed element Example list = [5,6,7,8] list.pop(1) # Updated list [5,7,8] Removes first Deletes elements matching value using their index. Doesn’t return any value exe SO Example list=[1,2,3,4] list = [4,5,6,7,8] list.remove(2) del list[1] | # Updated list # Updated list \ (1, 3, 4] [4,6,7,8] ye Removes element by index. Returns removed xf element Example list = [5,6,7,8] list.pop(1) # Updated list 5,7,8] urns removed Y Pickling — Converting an object in memory to a byte stream that can be stored on a disk or sent over a network Y Unpickling — Loading a pickled file back into a Python program Eee nnang y¥ Refer elements from end to start Example: arr=[4, 8, 12, 16, 20] print (arr[-1]) print (arr[-2]) Output: vy Both methods are used to expand lists at runtime append() extend() Single element added at the end All elements of iterables are of list added at the end of the list List length increases by “one” The increase depends on number of elements in iterables Any list, string or number can be Only elements of iterables can added to the list be added v¥ Extending the functionalities of existing functions without modifying them Deep copy Creates new and separate copy of the objects and its elements Any change made in new copy doesn’t reflect on original one 14. Deep copy vs Shallow copy REC Waae) ya Creates copy of the object but rather than copying the elements of object, it copies the references to their memory addresses. Any change made to the copy reflects in the original 7 vy Extending the functionalities of existing functions without modifying 14. Deep copy vs Shallow copy Creates new and separate copy of the objects and its elements Any change made in new copy doesn’t reflect on original one Shallow copy Creates copy of the object but rather than copying the elements of object, it copies the references to their memory addresses. Any change made to the copy reflects in the original 7 Cage ¥ Simple, one line function y¥ Can have any number of arguments v¥ Keyword ‘lambda’ Example of Lambda Function lambda a,b:a+b Traditional python function of the above lambda function \ def add(a,b): returnat+b ‘ @ Why is Python called an interpreted language? Python is an interpreted language. Interpreted means: Executes instructions directly and line-by-line. Does not compile and run a complete program at once. When it encounters an error, it stops. This makes Python easier to debug. Python doesn't need a separate compilation step (like C++ or Java). You can just write Python code and run it directly. This makes python fast to develop. Analytics Vichy TOP 21 PYTHON INTERVIEW QUESTIONS @ Do we need indentation in Python? Yes, indentation is a must in Python and is part of the language's syntax. Indentation provides readability to the code. Java Python for (i=4; i<11; i++) ~~ foriinrange (4:8) 7 6 ; = print(i) print(‘Analytics”) printf(“Analytics”) TOP 21 PYTHON INTERVIEW QUESTIONS @) What are the built in data types in Python? There are 7 types of built in data types. They are: |. Text type: str Il. Numeric Types: int, float, complex numbers Ill. Sequence Types: list, tuple, range IV. Map Type: dictionary V. Set types: set, frozenset VI. Boolean Type: bool VI. Binary types: bytes, bytearray, memoryview VII. None Type: NoneType TOP.21 Python Interview Questions & Answers | Freshers & Experienced Candidates | Crack Interviews TOP 21 PYTHON INTERVIEW QUESTIONS @ What are classes and objects in Python? - InPython, a class is a blueprint for creating objects. - And an object is an instance of a class. OBJECTS (HOUSE 1) OBJECTS (HOUSE 2) Class (House Blueprint) OBJECTS Analytics @ What is a Dictionary in Python? Dictionary is an unordered collection of elements. These elements in a dictionary are stored as key value pairs. Example, myDictionary = {Name: ‘John’, Place: ‘USA} . re, You can modify the dictionary by removing key-value pairs. TOP 21 PYTHON INTERVIEW QUESTIONS (5) What is a Dictionary in Python? # Create a dictionary person ={ "name": "John", 30, “city": "New York" } print(person) Output: {'‘name': John} ‘age’: 30, ‘city’: 'New York'} Analytics TOP 21 PYTHON INTERVIEW QUESTIONS 6 What are Python functions, and how do they help in code optimization? - Code reuse: Functions allow you to reuse code by encapsulating it ina single place and calling it multiple times from different parts of your program. e Example: ? def say_hello(): print("Hello, World!") say_hello() Output: Hello, World! Improved readability: By dividing your code into logical blocks, functions can make your code more readable and easier to understand. Analytics “TOP 21 21 PYTHON INTERVIEW QUESTIONS @) What are Python sets? Explain some of the properties of sets. - InPython, a set is an unordered collection of unique objects. - Sets are defined using curly braces ({ and }) and a comma-separated list of values. Example: fruits = {"apple", "banana’, "cherry"} SETS= © J print(fruits) Output: ‘apple’, ‘cherry’, 'banana’} “TOP 21 PYTHON INTERVIEW QUESTIONS (> @ What is the difference between list and tuple? List Tuple Mutability Lists are mutable. They can be modified after creation (adding, removing, changing items). Tuples are immutable. Once created, their content cannot be changed. Lists are defined using square brackets ({)). Tuples are defined using parentheses (0). Lists take up more memory due to. their ability to change and grow. Tuples are more memory efficient and usually faster because they are immutable. TOP 21 PYTHON INTERVIEW QUESTIONS oO What is the difference between a module and a package? maths.py def add(x,y): return x+y def sub(x,y): return x-y def mul(x,y): return x*y def div(x,y) return x/y Analytics arithmetic.py Output Import maths 5 x=2 6 y=3 print(maths.add(x,y)) print(maths.mul(x,y)) TOP 21 PYTHON INTERVIEW QUESTIONS oO What is the difference between a module and a package? Amodule in Python is simply a .py file containing Python code. This code can be imported and used in another Python script using the import statement. The syntax is import TOP 21 PYTHON INTERVIEW QUESTIONS oO What is the difference between a module and a package? maths.py def add(x,y): return x+y def sub(x,y): return x-y def mul(x,y): return x*y def div(x,y) return x/y Analytics arithmetic.py Output Import maths 5 x=2 6 y=3 print(maths.add(x,y)) print(maths.mul(x,y)) Pereneee Lr eee Oere area Tey TOP 21 PYTHON INTERVIEW QUESTIONS oO What is the difference between a module and a package? Package: - Apackage, on the other hand, is a collection of modules. It is a way of organizing related Python modules into a directory. - Essentially, it's a directory that contains multiple module files, along with a special file called _init_.py, which tells Python that the directory is a package. TOP 21 PYTHON INTERVIEW QUESTIONS 10 What is Indexing? And What is Negative Indexing? - Aniterable is any object capable of returning its members one at a time. This means that you can "iterate" over the object, usually using a loop like a for loop. TOP 21 PYTHON INTERVIEW QUESTIONS 10 What is Indexing? And What is Negative Indexing? Indexing: Away to access individual elements or groups of elements in an iterables by their position. In Python, indexes start at 0. So, if you have a list: my_list = [‘apple’, banana’, 'cherry'] The index of ‘apple’ is 0, banana’ is 1, and 'cherry' is 2. See ee sors | Freshers & Experienced Candidates | Crack Interviews TOP 21 PYTHON INTERVIEW QUESTIONS 10 What is Indexing? And What is Negative Indexing? 0 ua 2 banana TOP 21 Python Interview Questions & Answers | Freshers & Experienced Candidates | Crack Interviews, TOP 21 PYTHON INTERVIEW QUESTIONS an Explain the logical operators in Python. - InPython, the logical operators and, or, and not can be used to perform boolean operations on truth values (True and False). TOP 21 PYTHON INTERVIEW QUESTIONS an Explain the logical operators in Python. The and operator: This operator returns True if both the operands (the conditions on both sides of the operator) are true. If either condition is false, it returns False. Input: x=10 y=20 ifx> Sandy > 15: print("Both conditions are True") Output: Both conditions are True TOP 21 PYTHON INTERVIEW QUESTIONS an Explain the logical operators in Python. The not operator: This operator returns the opposite of the operand (condition). If the condition is True, it returns False. If the condition is False, it returns True. Input: x=10 ifnotx< 5: print("x is not less than 5") Output: Xis not less than 5 TOP 21 PYTHON INTERVIEW QUESTIONS e 12 Explain the use of lambda expressions in Python. When is it useful? - The lambda is used to define a function without a name in Python. They are useful in situations where you need a small, temporary function that you won't need to use elsewhere in your code. Analytics TOP 21 PYTHON INTERVIEW QUESTIONS 12 Explain the use of lambda expressions in Python. When is it useful? A regular function looks like: A lambda function looks like: it: Input: dd (x,y) add2= lambda xy: x+y return(x+y) print(add2(4,5)) print(add(4,5) Output: Output 2. 9 Analytics TOP 21 PYTHON INTERVIEW QUESTIONS 13 Explain Slicing in Python. Slicing in Python is a feature that allows you to access a subset or a"slice" of alist. Slice specifies a start index and an end index of a list. fruits = ['apple’, ‘banana’, ‘cherry’, ‘date’, ‘mango”] 1 2 3 4 TOP 21 PYTHON INTERVIEW QUESTIONS 13 Explain Slicing in Python. - The slice () function is used to get a slice of a sequence. Input: fruits = ['apple’, ‘banana’, ‘cherry’, ‘date’, (mango’] slice1 = fruits[1:4] print(slice1) Output: ['banana’, ‘cherry’, 'date'] Analytics TOP 21 PYTHON INTERVIEW QUESTIONS 13 Explain Slicing in Python. - Ifone leaves out the start index, it will assume it to be zero. And if one leaves out the end index, the output Will be the entire length of the list. Input: fruits = ['apple’, banana’, ‘cherry’, ‘date’, ‘mango’] slice1 = fruits[:] print(slice1) Output: ['apple’, ‘banana’, ‘cherry’, ‘date’, ‘mango’] Analytics Pee te ee ee es reefer eet a eM Tey © TOP 21 PYTHON INTERVIEW QUESTIONS (~ 14 Explain the difference between mutable and immutable objects in python. - In Python, objects can be of two types: - Mutable objects - Immutable objects. TOP 21 PYTHON INTERVIEW QUESTIONS 14 Explain the difference between mutable and immutable objects in python. # Mutable Object: Dictionary student = { ‘name’: Alice’, ‘age’: 25, ‘course’: ‘Computer Science’ } # Modifying the ‘age’ value in the dictionary student['age'] = 26 # Adding a new key-value pair to the dictionary student['gender’] = ‘Female’ print(student) Output: TOP 21 PYTHON INTERVIEW QUESTIONS 14 Explain the difference between mutable and immutable objects in python. Immutable Objects: They cannot be updated once defined. Example: string. = Opel a Pag ta String object TOP 21 PYTHON INTERVIEW QUESTIONS 14 Explain the difference between mutable and immutable objects in python. # Immutable Object: String name = "John" # Trying to change the first character of the string (this will raise an error) name[0] ='M' : Output: This line will raise a TypeError To modify the string, you need to create a new one. Example: modified_name = 'M' + name[1:] print(modified_name) TOP 21 PYTHON INTERVIEW QUESTIONS 15 What is the use of PASS keyword in Python? Pass: Pass is a null statement that basically does nothing. Usage: It is often used as a placeholder where a statement is required syntactically, but no action needs to be taken. For example, if you want to define a function or a class but haven't yet decided what it should do, you can use the pass as a placeholder. def my_function(): pass # TODO: implement this function Analytics TOP 21 PYTHON INTERVIEW QUESTIONS 16 What are Generators? Tell about their use in Python. Generator: - Agenerator in Python returns an iterator that produces sequences of values one at a time. - Weuse the yield keyword to produce salues. Usage: - Since the generator doesn't produce all the values at the same time, it saves memory if we ‘aaa use the generator to process the sequence of values without the need to save the initial values. Analytics TOP 21 PYTHON INTERVIEW QUESTIONS 16 What are Generators? Tell about their use in Python. Generator: - Agenerator in Python returns an iterator that produces sequences of values one at a time. - Weuse the yield keyword to produce values. Usage: - Since the generator doesn't produce all the values at the same time, it saves memory if we 7 "Rath : use the generator to process the sequence of values without the need to save the initial values. Analytics TOP 21 PYTHON INTERVIEW QUESTIONS 7 What is Shallow Copy and Deep Copy in Python? Shallow copy: A shallow copy is a copy of an object that stores the reference of the original elements. It makes copies of the nested objects' reference and doesn't create a copy of the nested objects. So if we make any changes to the copy of the object, it will reflect in the original object. TOP 21 PYTHON INTERVIEW QUESTIONS 7 What is Shallow Copy and Deep Copy in Python? Deep copy: A deep copy is a process where we create a new object and add copy elements recursively. The independent copy is created of the original object and its entire elements Changes made in one object do not affect the other. TOP 21 PYTHON INTERVIEW QUESTIONS What is inheritance in Python? What is the difference between single and multiple inheritance? - Inheritance: In Python, inheritance is a way we can define a new class (child class) that takes on attributes and methods from an existing class (parent class). TOP 21 PYTHON INTERVIEW QUESTIONS What is inheritance in Python? What is the difference between single and multiple inheritance? Single Inheritance is when a class inherits from a single superclass. For example: class Parent: def speak(self): » print("Parent speaking!") class Child(Parent): def talk(self): print("Child talking!") # Creating an object of Child child = Child() child.speak() #Output: Parent speaking! child.talk() # Output: Child talking! TOP 21 PYTHON INTERVIEW QUESTIONS What is inheritance in Python? What is the difference between single and multiple inheritance? Multiple inheritance is when a class can inherit from more than one superclass. For example: class Mother: def speak(self): print("Mother speakin, class Father: def talk(self): print("Father talking!") class Child(Mother, Father): pass # Creating an object of Child child = Child) child.speak() # Output: Mother speaking! child.talk()_ # Output: Father talkin; TOP 21 PYTHON INTERVIEW QUESTIONS 19 What is exception handling and how it is done in Python? Exception handling in Python involves using special blocks of code. So that it can catch and handle errors or "exceptions" that occur when your program runs. The main keywords for exception handling in Python are try, except, finally, and raise. TOP 21 PYTHON INTERVIEW QUESTIONS 19 What is exception handling and how it is done in Python? try: This keyword is used to specify a block of code that might raise an exception. except: This keyword is used to catch and handle the exception(s) that are encountered in the try block. finally: This keyword is used to specify a block of code that will be executed no matter if an exception is raised or not. raise: This keyword is used to manually raise an exception. TOP 21 PYTHON INTERVIEW QUESTIONS 19 What is exception handling and how it is done in Python? try: # Try block num = int(input("Enter a number: ")) # This line could raise a ValueError print(f"You entered: {num}") except ValueError: # Except block print("That's not a valid number!") finally: # Finally block . print("This gets executed no matter what") TOP 21 PYTHON INTERVIEW QUESTIONS 20 What is the use of decorators in Python? Decorators: In Python, decorators are a special kind of function that add extra functionality to another function. They do this without changing the other function's code. TOP 21 PYTHON INTERVIEW QUESTIONS 20 What is the use of decorators in Python? Input def my_decorator(func): def wrapper(): print("Something is happening before the function is called.") func() print("Something is happening after the function is called.") return wrapper @my decorator def say_hello(): print("Hell say_hello() Output: Something is happening before the function is called. Hello! ‘Something is happening after the function is called. TOP 21 PYTHON INTERVIEW QUESTIONS 21 Explain the difference between “is” and “==” in Python. "==" checks for value equality, It compares the values of the two objects and returns True if they are equal and False if they are not. For example: list1 =[1, 2, 3] list2 = [1, 2, 3] print(list4 == list2) Output: True TOP 21 PYTHON INTERVIEW QUESTIONS 21 Explain the difference between “is” and “==” in Python. - "is" checks for identity. It returns True if both variables point to the same object (not just equal values, but the exact same instance in memory), and False otherwise. For example: list1 = [1, 2, 3] list2 = list1 #list2 now references the same object as list1 print(list1 is list2) Output: True

You might also like