Python is one of the most used programming languages. It is easy to learn as it has very simple syntax and it is freely available. Python is becoming increasingly popular due to its simplicity and ability to perform various functionality in fewer lines of code.
Python is used in Machine Learning, Artificial Intelligence, Web Development, Web Scraping, and other fields because of its ability to handle strong calculations through powerful libraries. Companies are eager to provide incredible advantages and rewards to these developers.
In the following article, we’ll see the most commonly asked questions from python and their answers in the interview.
Table of Contents
Q1. What is python?
Python is a collection of instructions that we provide to our computer in the form of a program to do a specific task. It is a programming language with features such as being interpreted, object-oriented, and also high-level. It is widely used in web development, software development, and machine learning related fields.
Q2. What are some of the key features of python?
The following are some of the key features of python:
- Easy to learn and read syntax
- High level and object oriented language
- Convenient and interactive language
- Widely supported libraries
Q3. What are different python data types?
Data types in python includes:
Numbers
There are 3 types of numeric data types- integer, float, complex numbers.
Integer- 1,2,3 and so on.
Float- 1, 1.1, 1.2, 1.3….2, 2.1 and so on.
Complex no- 1+2j, 2+3j and so on.
Sequence
There are 3 types of sequences- string, list, tuple
String- “Name”
List- [4,1.2,’a’]
Tuple- (‘c’,3,1.1)
Boolean
(True, False)
Sets
{1,2,2,3,3}
Dictionary
{1:’A’, 2:’B’}
Q4. Explain string, list and tuple.
- Strings represent characters, words etc. It also includes special characters. String is written in single or double quotations. Example: name =’john’. Here, john is in a string
- List stores and organize multiple values. It always has square brackets and is separated by commas. It can have different data types. List can be modified (i.e. we can add or remove the elements called mutable). Example:
grocery_list=['apples','banana','grapes']
mixed_list=['56',"Hello,world!",True,6.98]
print(grocery_list)
output: ['apples','banana','grapes']
- Tuples are immutable and similar to lists i.e. values cannot be changed once defined. They are enclosed by parentheses and can have diff data types. Example-
student_score= (89,78,98,56,67)
first_score=student_score[0]
print(first_score)
Output: 89
Q5. What is the difference between mutable and immutable data type?
Python includes mutable and immutable data types.
- Mutable data types can be changed once created.
Example of mutable list:
list= [1,2,3,4,5]
list [2]=9
print("modified_mutable_list:",list)
output:
modified_mutable_list: [1, 2, 9, 4, 5]
Example of mutable dictionary:
student_marks={'S1':87,'S2':98,'S3':76,'S4':67}
student_marks['S2']=89
print("modified_marks:",student_marks)
output:
modified_marks: {'S1': 87, 'S2': 89, 'S3': 76, 'S4': 67}
- Immutable data types cannot be changed once created. Tuple,integer,strings are immutable.
Example of immutable tuple:
tuple1 = (1, 2, 3)
tuple1[1] = 4
print(tuple1)
Output:
Type Error: 'tuple' object does not support item assignment
Q6. Differentiate between arrays and lists in python.
- A list in Python is a built-in collection of things that can contain elements of many data kinds, such as numeric, character, and logical values. It is an ordered collection that supports negative indexing. List is created using [] and is separated by commas.
Example:
list_1= [1,’a’,’b’]
Print(list_1)
- An array is a vector which has homogeneous elements, because they all belong to the same data type. Elements are assigned memory places that are next to one another. The size of an array is fixed. The insertion and deletion costs are higher than for lists, but indexing is faster in arrays due to contiguous memory allocation. Arrays can be accessed by importing the array module.
Example:
importing "array" for array creations
import array as arr
creating an array with integer type
a = arr.array('i', [1, 2, 3])
print(type(a))
for i in a:
print(i, end=" ")
Output:
<class 'array.array'>
1 2 3
Q7. What are the different libraries in python?
In python, there are more than 137000 libraries. Most used libraries in python are mentioned below:
This is popular library in python. It is used in machine learning, and it provides support to matrices and arrays. NumPy is used to do scientific and mathematical computations which includes mathematical methods, algorithms, and software tools, forecast outcomes, and gain insights into numerous scientific and engineering disciplines.
This library helps in data analysis and plotting numerical data. It is used for creating visualizations and graphical representations. It is an open-source library and used to make different types of charts and graphs, say, histogram, pie chart.
Pandas helps in data processing and analysis, making it an essential tool for anyone who works with data in Python. It’s a great library that allows you to easily manipulate, analyze, and transform data.
Seaborn is used for visualizing data, and it is built on Matplotlib. It means that Seaborn uses Matplotlib’s core capabilities while adding its own additions to make your data visualizations not only instructive but also visually appealing, with less effort.
SciPy means scientific python. SciPy is an open-source library for high-level scientific computations. It is an extension of NumPy and works with NumPy to handle complex computations.
Scikit-learn is a well-known Python library for working with complex data. It supports supervised and unsupervised machine learning algorithms.
Q8. What is slicer in python?
Slicing allows you to extract a portion or a slice of list, tuple or string.
Basic syntax is- subset=iterable[start:stop:step] where start represents the index of the first element, stop represents the first element that you don’t want in the slice and step is number of indices between elements (if not given, assume it to be 1).
Example 1:
fruits=['apple','banana','grapes','kiwi']
subset=fruits[0:3]
print(subset)
Output:
['apple', 'banana', 'grapes']
Example 2:
numbers=[0,1,2,3,4,5,6,7,8]
sub=numbers[1:8:2]
print(sub)
Output:
[1, 3, 5, 7]
Q9. How many data types are mutable and how many are immutable?
Dictionaries, sets and lists are mutable data types whereas numbers, strings and tuples are immutable data types in python.
Q10. What do you mean by scope?
In Python, every object functions with scope. A scope is a block of Python code that keeps an object relevant. Namespaces uniquely identify all of the objects in a program. However, these namespaces have a scope stated for them, enabling you to use their objects without the prefix. Some examples of scope generated during code execution in Python are as follows:
Local scope
Global scope
Module level scope
Outermost scope
Q11. How to swap values among three variables? Give an example.
The following is the example on how to swap variables among three variables:
a = 5
print(f'old value of a is {a}')
b = 10
print(f'old value of b is {b}')
c = 15
print(f'old value of c is {c}')
#Swapping values a, b, c = b, c, a
print(f'new value of a is {a}')
print(f'new value of b is {b}')
print(f'new value of c is {c}')
Output:
10
15
5
Also Read>>> Top 40+ SQL Interview Questions and Answers for 2024
Q12. What are the different types of conditional statements?
1. If Statement: A simple if statement checks a single condition. The code block under the if statement is implemented, if the condition is true. Otherwise, it is skipped.
2. if-else statement: This statement gives us two options to choose from based on a condition: one option if the condition is true and another option if it is false.
3. if-elif-else statement: The if-elif-else statement is useful when we have multiple conditions to check. It allows us to provide different actions for different conditions. If the conditions before this one were not satisfied, then consider checking this condition.
4. Nested if statements: These are if statements within other if statements, allowing us to create more complex decision-making structures.
Q13. Give an example of if and if-else statements.
Example for if condition:
age =int(input("Enter age:"))
if age >= 18:
print("You are eligible to vote.")
Output:
Enter age:20
You are eligible to vote
Example for if-else condition:
age = int(input("Enter age:"))
if age >= 18:
print("You are eligible to vote.")
else:
print("Not eligible to vote.")
Output:
Enter age:16
Not eligible to vote
Q14. Define __init__ () in python.
In Python, the __init__ is the constructor method and is invoked automatically to assign memory when a new object or instance is made. Every class has a function called __init__. For example:
class Student:
def __init__(self, name, age):
self.studentname = name
self.age = age
# creating a new object
stu1 = Student("abc", "xyz", 21)
Q15. What is the use of / and // operator?
In Python, the / operator divides and returns the quotient as a float.
For example, 10 / 5 = 2.0
The // operator divides and returns the quotient as an integer.
For example, 10 / 5 = 2
Q16.Differentiate between merge, join, and concatenate.
- Merge connects two DataFrames using the column(s) we specify. It takes two DataFrames, a common column in both, and “how” you want to merge them. Two dataframes can be joined left, right, outer, inner, or cross. It is an inner join by default.
pd.merge(df1, df2, how='outer', on='Id')
- The join method combines two DataFrames based on their index. It needs an optional ‘on’ argument, which can be one or more column names. By default, the join function does a left join.
df1.join(df2)
- Concatenate combines two or more DataFrames vertically or horizontally or joins them along a specific axis (rows or columns). It does not require an ‘on’ argument.
pd.concat(df1,df2)
Q17.What is the difference between append() and extend()?
- The function append() adds an element to the end of the list
Example:
list=[1, 2, 3, 4]
list.append(5)
list
Output:
[1,2,3,4,5]
- The function extend() adds elements from an iterable to the end of the list.
Example:
list=[1, 2, 3]
list.extend([4,5])
list
Output:
[1,2,3,4,5]
Q18. What is docstring?
Docstrings are used to create documentation for different Python modules, classes, functions, and methods.
Q19. What is break, continue and pass?
- The break statement immediately ends the loop, and control is passed to the statement after the loop’s body.
- The continue statement terminates the current iteration of the statement, skips the remaining code in the current iteration, and transfers control to the next iteration of the loop.
- Pass keyword in Python is commonly used to fill empty blocks and is equivalent to an empty statement represented by a semicolon in languages such as Java, C++, and Javascript.
Also read>>> SQL Commands | DDL, DQL, DML, DCL and TCL Commands
Q20. Why use else in Python’s try/except construct?
The commands ‘try:’ and ‘except:’ are well-known for their exceptional handling in Python, but where does ‘else:’ come in handy? If no exception is raised, the ‘else:’ statement will be executed.
On our first try, use 2 as the numerator and “d” as the denominator. This is incorrect, and ‘except:’ was triggered with “Invalid input!”
On the second try, we used 2 as the numerator and 1 as the denominator, yielding the result 2. Because no exception was raised, it triggered the ‘else:’ statement, which printed the message “Division is successful.”
Example:
num1 = int(input('Enter Numerator:'))
num2 = int(input('Enter the denominator:'))
divide = num1/num2
print(f'Result: {division}')
except:
print('Invalid input!').
else:
print('Division was successful.')
Q21. Which command is used to delete a file in python?
By using the following command, we can delete the python file:
import os
os.remove("ChangedFile.csv")
print("File Removed!")
Q22.How two dictionaries are merged in python?
To merge the two dictionaries, update() command is used.
dict1()= {“a”:1,”b”:2}
dict2()={“c”:3,”d”:4}
merged_dict=dict1.copy()
merged_dict.update(dict2)
FAQs
How to ace a Python coding interview?
You should be able to develop clean production-ready code, comprehend job-specific Python libraries, tools, and techniques, and provide distinctive and concise solutions to each problem. All of this can be accomplished through everyday practice. You can also share your creations on GitHub or other websites.
How to prepare for a Python interview?
You have to study Python syntax, functions, classes, data types, algorithms, data structures, and exception handling. Furthermore, you must read technical tutorials, evaluate sample projects, cheat sheets, and practice problems, and complete code challenges. Practice the above-mentioned questions with their responses.