Live Classes: Upskill your knowledge Now!
Chat NowPublished - Tue, 06 Dec 2022
A list of frequently asked Python interview questions with answers for freshers and experienced are given below.
Python was created by Guido van Rossum, and released in 1991.
It is a general-purpose computer programming language. It is a high-level, object-oriented language which can run equally on different platforms such as Windows, Linux, UNIX, and Macintosh. Its high-level built-in data structures, combined with dynamic typing and dynamic binding. It is widely used in data science, machine learning and artificial intelligence domain.
It is easy to learn and require less code to develop the applications.
It is widely used for:
Python is used in various software domains some application areas are given below.
Python provides various web frameworks to develop web applications. The popular python web frameworks are Django, Pyramid, Flask.
Python's standard library supports for E-mail processing, FTP, IMAP, and other Internet protocols.
Python's SciPy and NumPy helps in scientific and computational application development.
Python's Tkinter library supports to create a desktop based GUI applications.
Advantages of Python are:
Interpreted: Python is an interpreted language. It does not require prior compilation of code and executes instructions directly.
Free and open source: It is an open-source project which is publicly available to reuse. It can be downloaded free of cost.
Extensible: It is very flexible and extensible with any module.
Object-oriented: Python allows to implement the Object-Oriented concepts to build application solution.
Built-in data structure: Tuple, List, and Dictionary are useful integrated data structures provided by the language.
Portable: Python programs can run on cross platforms without affecting its performance.
PEP 8 stands for Python Enhancement Proposal, it can be defined as a document that helps us to provide the guidelines on how to write the Python code. It is basically a set of rules that specify how to format Python code for maximum readability. It was written by Guido van Rossum, Barry Warsaw and Nick Coghlan in 2001.
Literals can be defined as a data which is given in a variable or constant. Python supports the following literals:
String Literals
String literals are formed by enclosing text in the single or double quotes. For example, string literals are string values.
Example:
Output:
JavaTpoint JavaTpoint Java T point
Numeric Literals
Python supports three types of numeric literals integer, float and complex.
Example:
Output:
10 12.3 3.14j
Boolean Literals
Boolean literals are used to denote Boolean values. It contains either True or False.
Example:
Output:
p is True q is False r: 4 s: 7
Special literals
Python contains one special literal, that is, 'None'. This special literal is used for defining a null variable. If 'None' is compared with anything else other than a 'None', it will return false.
Example:
Output:
None
A function is a section of the program or a block of code that is written once and can be executed whenever required in the program. A function is a block of self-contained statements which has a valid name, parameters list, and body. Functions make programming more functional and modular to perform modular tasks. Python provides several built-in functions to complete tasks and also allows a user to create new functions as well.
There are three types of functions:
Example: A general syntax of user defined function is given below.
Python zip() function returns a zip object, which maps a similar index of multiple containers. It takes an iterable, convert into iterator and aggregates the elements based on iterables passed. It returns an iterator of tuples.
Signature
Parameters
iterator1, iterator2, iterator3: These are iterator objects that are joined together.
Return
It returns an iterator from two or more iterators.
There are two parameters passing mechanism in Python:
By default, all the parameters (arguments) are passed "by reference" to the functions. Thus, if you change the value of the parameter within a function, the change is reflected in the calling function as well. It indicates the original variable. For example, if a variable is declared as a = 10, and passed to a function where it's value is modified to a = 20. Both the variables denote to the same value.
The pass by value is that whenever we pass the arguments to the function only values pass to the function, no reference passes to the function. It makes it immutable that means not changeable. Both variables hold the different values, and original value persists even after modifying in the function.
Python has a default argument concept which helps to call a method using an arbitrary number of arguments.
Python's constructor: _init__ () is the first method of a class. Whenever we try to instantiate an object __init__() is automatically invoked by python to initialize members of an object. We can't overload constructors or methods in Python. It shows an error if we try to overload.
Example:
Output:
Name: rahul Email id: rahul@gmail.com
The user can use the remove() function to delete a specific object in the list.
Example:
Output:
[3, 5, 7, 3, 9, 3] After removal: [5, 7, 3, 9, 3]
If you want to delete an object at a specific location (index) in the list, you can either use del or pop.
Example:
Output:
[3, 5, 7, 3, 9, 3] After deleting: [3, 5, 3, 9, 3]
We cannot use these methods with a tuple because the tuple is different from the list.
It is a string's function which converts all uppercase characters into lowercase and vice versa. It is used to alter the existing case of the string. This method creates a copy of the string which contains all the characters in the swap case. If the string is in lowercase, it generates a small case string and vice versa. It automatically ignores all the non-alphabetic characters. See an example below.
Example:
Output:
it is in lowercase. IT IS IN UPPERCASE.
To remove the whitespaces and trailing spaces from the string, Python providies strip([str]) built-in function. This function returns a copy of the string after removing whitespaces if present. Otherwise returns original string.
Example:
Output:
javatpoint javatpoint javatpoint After stripping all have placed in a sequence: Javatpoint javatpoint javatpoint
To remove leading characters from a string, we can use lstrip() function. It is Python string function which takes an optional char type parameter. If a parameter is provided, it removes the character. Otherwise, it removes all the leading spaces from the string.
Example:
Output:
javatpoint javatpoint After stripping all leading whitespaces: javatpoint javatpoint
After stripping, all the whitespaces are removed, and now the string looks like the below:
The join() is defined as a string method which returns a string value. It is concatenated with the elements of an iterable. It provides a flexible way to concatenate the strings. See an example below.
Example:
Output:
aRohanb
This method shuffles the given string or an array. It randomizes the items in the array. This method is present in the random module. So, we need to import it and then we can call the function. It shuffles elements each time when the function calls and produces different output.
Example:
Output:
Original LIST1: ['Z', 'Y', 'X', 'W', 'V', 'U'] After the first shuffle of LIST1: ['V', 'U', 'W', 'X', 'Y', 'Z'] After the second shuffle of LIST1: ['Z', 'Y', 'X', 'U', 'V', 'W']
The break statement is used to terminate the execution of the current loop. Break always breaks the current execution and transfer control to outside the current block. If the block is in a loop, it exits from the loop, and if the break is in a nested loop, it exits from the innermost loop.
Example:
Output:
2 X 11 X 22 X 33 Y 11 Y 22 Y 33 BREAK
Python Break statement flowchart.
A tuple is a built-in data collection type. It allows us to store values in a sequence. It is immutable, so no change is reflected in the original data. It uses () brackets rather than [] square brackets to create a tuple. We cannot remove any element but can find in the tuple. We can use indexing to get elements. It also allows traversing elements in reverse order by using negative indexing. Tuple supports various methods like max(), sum(), sorted(), Len() etc.
To create a tuple, we can declare it as below.
Example:
Output:
(2, 4, 6, 8) 6
It is immutable. So updating tuple will lead to an error.
Example:
Output:
tup[2]=22 TypeError: 'tuple' object does not support item assignment (2, 4, 6, 8)
The Python provides libraries/modules that enable you to manipulate text files and binary files on the file system. It helps to create files, update their contents, copy, and delete files. The libraries are os, os.path, and shutil.
Here, os and os.path - modules include a function for accessing the filesystem
while shutil - module enables you to copy and delete the files.
Python provides four modes to open files. The read-only (r), write-only (w), read-write (rw) and append mode (a). 'r' is used to open a file in read-only mode, 'w' is used to open a file in write-only mode, 'rw' is used to open in reading and write mode, 'a' is used to open a file in append mode. If the mode is not specified, by default file opens in read-only mode.
An operator is a particular symbol which is used on some values and produces an output as a result. An operator works on operands. Operands are numeric literals or variables which hold some values. Operators can be unary, binary or ternary. An operator which requires a single operand known as a unary operator, which require two operands known as a binary operator and which require three operands is called ternary operator.
Example:
Output:
# Unary Operator -12 # Binary Operator 25 156 # Ternary Operator 12
Python uses a rich set of operators to perform a variety of operations. Some individual operators like membership and identity operators are not so familiar but allow to perform operations.
Arithmetic operators perform basic arithmetic operations. For example "+" is used to add and "?" is used for subtraction.
Example:
Output:
35 -11 276 0.5217391304347826
Relational Operators are used to comparing the values. These operators test the conditions and then returns a boolean value either True or False.
# Examples of Relational Operators
Example:
Output:
False True True True
Assignment operators are used to assigning values to the variables. See the examples below.
Example:
Output:
12 14 12 24 576
Logical operators are used to performing logical operations like And, Or, and Not. See the example below.
Example:
Output:
False True True
Membership operators are used to checking whether an element is a member of the sequence (list, dictionary, tuples) or not. Python uses two membership operators in and not in operators to check element presence. See an example.
Example:
Output:
False True
Identity Operators (is and is not) both are used to check two values or variable which are located on the same part of the memory. Two variables that are equal does not imply that they are identical. See the following examples.
Example:
Output:
False True
Bitwise Operators are used to performing operations over the bits. The binary operators (&, |, OR) work on bits. See the example below.
Example:
Output:
8 14 6 -11
In Python 3, the old Unicode type has replaced by "str" type, and the string is treated as Unicode by default. We can make a string in Unicode by using art.title.encode("utf-8") function.
Example:
Output:
unicode_1: ('ģ', '♥', '
Fri, 16 Jun 2023
Fri, 16 Jun 2023
Fri, 16 Jun 2023
Write a public review