0% found this document useful (0 votes)
3 views43 pages

Interview Questions Python

Uploaded by

c9440279
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views43 pages

Interview Questions Python

Uploaded by

c9440279
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Interview Questions

Recently Asked Questions and Answers

1. What is software?

Software is a set of instructions for the hardware.

2. What is Python and what are its applications?

Python is an object-oriented programming language that is easy to learn and simple to


implement.

Applications of Python

Python is a versatile language that has applications in almost every field

●​ Artificial intelligence (AI)


●​ Machine Learning (ML)
●​ Big Data
●​ Smart Devices/Internet of Things (IoT)
●​ Cyber Security
●​ Game Development
●​ Backend Development, etc.

3. What are the features of Python?

Features of Python:

●​ Easy to learn & code


●​ Open Source Programming Language
●​ Object-Oriented Language
●​ Dynamic Typed Language
●​ Large Standard Library

4. Is Python case-sensitive?

Yes, Python is case-sensitive. The username, UserName, and userName are

three different variables, and using these names interchangeably causes an error.

Code
username = "Rahul"

print(username)

print(userName)

Output

Rahul

NameError: name 'userName' is not defined

Q. Is Python a dynamically typed programming language?

Companies Asked: Translytics Business Services

Yes, Python is a dynamically typed language. This means that in Python the type
checking of a variable is done only as code runs, and the type of a variable is allowed to
change over its lifetime. There is no need to declare the type of the variable
While programming languages like C, Java, C++, etc are statically typed languages
where we cannot change the data type of a variable during the execution of the
program.

Code

1.x = 6

[Link](type(x))

3.x = 'Rahul'

[Link](type(x))

Output

<class 'int'>

<class 'str'>

Question 4 of 4
Which code will give the output as

<class 'str'>?

x = 123

print(type(x))

x = '123'

print(type(x))

x = [123]

print(type(x))

x = 123.0

print(type(x))

6. What are the advantages of Python over Java?


Basis of Python Java
Comparison

Learning Compared to Python, it's difficult


Easy to learn
curve to learn

Typing Dynamically-typed Statically-typed

Syntax Easy to read and remember Difficult to read and remember

Applicati Artificial Intelligence, Data Science and Enterprise, Embedded and


ons Machine Learning applications Cross-platform applications

Code More lines of code compared to


Fewer lines of code compared to Java
Length Python

public class Simple {

public static void main(String


Example
print("Hello World") args[]){
Program

[Link]("Hello World");
}}
Q. What are the specifications, benefits of Python
compared to C.

Feature Python C
s

Python has a clean and


Syn
readable syntax, making it C has a more complex syntax compared to Python.
tax
easy for beginners to learn.

For
It uses indentation to define
mat It uses curly braces {} to define blocks of code.
blocks of code.
ting

Python is dynamically typed,


Typi meaning variable types can be C is statically typed, and variable types must be
ng changed over time, offering declared before use.
flexibility.

Me
mor
y Python has automatic memory
C requires manual memory management using
Ma management through a
functions like malloc() and free().
nag garbage collector.
em
ent
Exe Python is an interpreted
C is a compiled language, and the entire program is
cuti language, executing code line
compiled before execution.
on by line at runtime.

Perf
Python is generally slower
orm
than C due to its interpreted C is known for its high performance and efficiency.
anc
nature.
e

Co C has a well-established community, particularly in


Python has a large and active
mm systems programming and embedded systems, but it
community with extensive
unit may lack in modern web and application development
libraries and frameworks.
y libraries.

Question 3 of 3

What is a benefit of using Python over C?

Python has a more complex syntax compared to C.

C's low-level abstractions make it easier for beginners to learn.

Python provides a vast ecosystem of libraries and frameworks, enhancing


productivity.

None of the above


7. How to perform the arithmetic operations using Python?

Addition

The addition is denoted by

+ sign. It gives the sum of two numbers.

Code

print(2 + 5)

print(1 + 1.5)

Output

2.5
Subtraction

The subtraction is denoted by

- sign. It gives the difference between the two numbers.

Code

print(5 - 2)

Output

Multiplication

The multiplication is denoted by

* sign.

Code

print(2 * 5)
print(5 * 0.5)

Output

10

2.5

Division

The division is denoted by

/ sign.

Code

print(5 / 2)

print(4 / 2)

Output
2.5

2.0

Modulus

To find the remainder between two numbers, we use the Modulus operator

Code

print(6 % 3)

Output

Exponent

To calculate a power b, we use Exponent Operator


**

Code

print(2 ** 3)

Output

8. What is floor division?

To find integral part of quotient we use Floor Division Operator

//.

●​ a // b

Code

print(3 // 2)
Output

Q. What is the modulus operator and how does it work in


Python?

The modulus operator, also known as the modulus or remainder operator, is


represented by the percent sign (%) in Python. It is used to find the remainder of a
division operation.

Syntax:

Reminder = Dividend % Divisor

Where:

●​ dividend is the number being divided


●​ divisor is the number dividing the dividend
●​ result is the remainder of the division
More Information

Question 4 of 4

What will be the output after executing the following code:

number = 15

if number % 5 == 0:

print("Fizz")

else:

print("Buzz")

Fizz

Buzz

15

0
Q. What is the output of 1 % 4 and 2 % 4?

●​ The output for 1%4 is:

print(1 % 4) # Output: 1

●​ The output for 2%4 is:

print(2 % 4) # Output: 2

Question 3 of 3

What will be the output for the following code?

print(5%7)

1
3

9. What is Operator Precedence in Python?

The operator precedence determines which operator is executed first if there is more
than one operator in an expression.

The operator precedence in Python is listed in the following table. It is in descending


order (the upper group has higher precedence than the lower ones).

Operators Meaning

() Parentheses

** Exponent

Unary plus, Unary minus,


+x, -x, ~x
Bitwise NOT

Multiplication, Division, Floor


*, /, //, %
division, Modulus
+, - Addition, Subtraction

<<, >> Bitwise shift operators

& Bitwise AND

^ Bitwise XOR

| Bitwise OR

Comparisons, Identity,
==, !=, >, >=, <, <=, is, is not, in, not in
Membership operators

not Logical NOT

and Logical AND

or Logical OR

BODMAS
The standard order of evaluating an expression
●​ Brackets (B)
●​ Orders (O)
●​ Division (D)
●​ Multiplication (M)
●​ Addition (A)
●​ Subtraction (S)

Expression:

(5 * 2) + (3 * 4 + 4 / 2)

Step by Step Explanation

(5 * 2) + (3 * 4 + 4 / 2)

(10) + (3 * 4 + 2)

(10) + (12 + 2)

(10) + (14)

24

Code
print((5 * 2) + (3 * 4 + 4 / 2))

Output

24

10. What is a Variable?

Variables are like containers for storing values.

Assigning Value to Variable

The following is the syntax for assigning an integer value

10 to a variable age

age = 10

Here the equals to


= sign is called an Assignment Operator as it is used to assign values to variables.

Q. What are Data Types?

Rephrased Question: What are different data types in Python?

In programming languages, every value or data has an associated type to it known as


data type.
Some commonly used data types

Data Type Type

Text Type str

Numeric
int, float
Types

Sequence
list, tuple
Types
Mapping Type dict

Set Type set

Boolean Type bool

This data type determines how the value or data can be used in the program. For
example, mathematical operations can be done on Integer and Float types of data.

More Information

●​ Text Types: The Text Data Type holds sequence of characters.


●​ Numeric Types: The Numeric Data Type holds numeric values.
●​ Sequence Types: The Sequence Data Type holds collection of items.
●​ Mapping Type: The Mapping Data Type holds data in key-value pair form.
●​ Set Type: The Set Data Type hold collection of unique items.
●​ Boolean Type: The Boolean Data Types holds either​
True or False.

Question 4 of 4

What is the data type used to represent a collection of elements with no duplicate
values in Python?

list
tuple

set

dict

12. What are the numeric data types in Python?

The Numeric Data Types in Python are:

●​ Integers
●​ Float
●​ Complex Numbers

Code

a = 10

print("Type of a: ", type(a))

b = 10.0

print("Type of b: ", type(b))


c = 10 + 20j

print("Type of c: ", type(c))

Output

Type of a: <class 'int'>

Type of b: <class 'float'>

Type of c: <class 'complex'>

13. What is meant by mutability? Name some mutable


data types?

Mutable means capable of being changed. In Python, objects whose value can be
changed are said to be mutable.

Some of the mutable data types in Python are list, dictionary, set and user-defined
classes.
14. What is meant by immutability? Name some
immutable data types?

Immutable means capable of not being changed. In Python, objects whose value cannot
be changed are said to be immutable.

Some of the immutable data types in Python are tuple, integer, boolean, string, etc.

Question 2 of 2

Which of the following is an example of an immutable data type in Python?

List

Integer

Dictionary

Set
Q. What are the differences between the mutable and
immutable data types?

Rephrased Question: What is immutability and mutability?

Mutable and Immutable are terms primarily used to refer to whether an object can
be changed (modified) after it's created.

Immutable Data Types Mutable Data Types

Cannot be changed after creation Can be modified after creation

Can be used as dictionary keys Cannot be used as dictionary keys

Reduces potential bugs from unintended


More prone to bugs if not handled carefully
side effects

Examples: int, float, str, tuple Examples: list, dict, set


A shallow copy references the same objects in the
Creating a new instance doesn't affect the
original object; a deep copy creates an independent
original object
object.; deep copy creates an independent object

For some operations, immutable data types


Adding an element to a list or modifying a dict in-place
might require the creation of many
can be efficient
temporary objects, which can be inefficient

Question 5 of 5

What is the value of

my_str at the end of the code?

my_str = 'Hello'

my_str += ' World'

'Hello World'

'Hello'

' World'
'HelloWorld'

16. What is type conversion or type casting?

Converting the value of one data type to another data type is called Type
Conversion or Type Casting.
We can convert

●​ String to Integer
●​ Integer to Float
●​ Float to String and so on.

String to Integer

int() converts valid data of any type into integer

Code

a = "5"

a = int(a)

print(type(a))
print(a)

Output

<class 'int'>

Integer to String

str() converts data of any type into a string.

Code

a = input()

a = int(a)

b = input()

b = int(b)
result = a + b

print("Sum: " + str(result))

Input

Output

Sum: 5

Similarly,

●​ float() -> Converts to a float data type


●​ bool() -> Converts to a boolean data type

17. What is a String?


A String is a stream of characters enclosed within quotes.
Stream of Characters

●​ Capital Letters ( A – Z )
●​ Small Letters ( a – z )
●​ Digits ( 0 – 9 )
●​ Special Characters (~ ! @ # $ % ^ . ?,)
●​ Space

Some examples:

●​ "Hello, World!"
●​ "some@[Link]"
●​ "1234"

18. What is String Slicing?

Obtaining a part of a string is called String Slicing.

Syntax:

variable_name[start_index:end_index]
●​ end_index is not included in the slice.

Code

message = "Hi Ravi"

part = message[3:7]

print(part)

Output

Ravi

Slicing to End

If the end index is not specified, slicing stops at the end of the string.

Code

message = "Hi Ravi"


part = message[3:]

print(part)

Output

Ravi

Slicing from Start

If the start index is not specified, slicing starts from the index 0.

Code

message = "Hi Ravi"

part = message[:2]

print(part)

Output
Hi

Extended Slicing

Syntax:

variable[start_index:end_index:step]

Step determines the increment between each index for slicing.

Code

a = "Waterfall"
part = a[1:8:2]

print(part)

Output

aefl

19. How to reverse a string?

A string can be reversed using extended slicing.

Syntax:

variable[start:end:negative_step]

-1 for step will reverse the order of the characters.

Code
string_1 = "Program"

string_2 = string_1[::-1]

print(string_2)

Output

margorP

20. What is string capitalize() in Python?

The

capitalize() method converts the first character of a string to an uppercase letter and all
other alphabets to lowercase.

Code

sentence = "proGraMmiNg"
capitalized_string = [Link]()

print(capitalized_string)

Output

Programming

21. What is string replace() in Python?

The

replace() returns a new string after replacing all the occurrences of the old substring
with the new substring.

Syntax:

str_var.replace(old, new)

Code
sentence = "teh cat and teh dog"

sentence = [Link]("teh", "the")

print(sentence)

Output

the cat and the dog

22. What is round() function?

Rounds the float value to the given number of decimal digits.

Syntax:

round(number, digits(optional))

digits -> defines the number of decimal digits to be considered for rounding.
●​ When digits not specified, the default value is 0.

Code

a = round(3.14159, 2)

print(a)

a = round(5.6777)

print(a)

Output

3.14

23. How to write comments in Python?


A comment starts with a hash

It can be written in its own line next to a statement of code.

Code

n = 5

# Finding if Even

even = (n % 2 == 0)

print(even) # prints boolean value

Output

False

Q. What are Iterators in Python?


An iterator is a special object in Python that allows us to traverse through a collection of
items one at a time.

In Python, we implement two special methods known as iterators methods:

Method Description

__iter__() Called to initialize the iterator. It must return an iterator object.

Called to iterate over the iterator. It must return the next value in the data
__next__()
stream.

More Information

Python iterable and Python iterator are different. The main difference between them is,
iterable in Python cannot save the state of the iteration, whereas in iterators the state of
the current iteration gets saved.

Iterating over an iterator

tup = ('a', 'b', 'c', 'd', 'e')


tup_iter = iter(tup)

print("Inside loop:")

for index, item in enumerate(tup_iter):pPYA4LJZ

print(item)

if index == 2:

break

Expand

Create an iterator named


tup_iter by calling the iter() function on the tup tuple. The code iterates over the tup_iter
iterator, printing each item in the tuple to the console. The loop breaks after the third
item is printed. The next() method is used to get the next element from the iterator
object.

Question 5 of 5

What is the purpose of the

__iter__() method in Python iterators?

It initializes the iterator.

It returns the next value in the data stream.

It creates the iterator object.

It defines the collection of items to be iterated.

You might also like