0% found this document useful (0 votes)
165 views13 pages

Python Interview Questions-Ccbp Format

Uploaded by

Naga Suresh
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
165 views13 pages

Python Interview Questions-Ccbp Format

Uploaded by

Naga Suresh
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 13

Pyton interview questions

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?


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.

Q. Is Python a dynamically typed programming language?


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.

8. What is floor division?


To find integral part of quotient we use Floor Division Operator //.

a // b

print(3 // 2) //output : 1

9. 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.
Reminder = Dividend % D
Where:

dividend is the number being divided


divisor is the number dividing the dividend
result is the remainder of the division

BODMAS
The standard order of evaluating an expression

Brackets (B)
Orders (O)
Division (D)
Multiplication (M)
Addition (A)
Subtraction (S)

(5 * 2) + (3 * 4 + 4 / 2)
(10) + (3 * 4 + 2)
(10) + (12 + 2)
(10) + (14)
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
Here the equals to = sign is called an Assignment Operator as it is used to assign values to variables.
age = 10

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 Types int, float
Sequence Types list, tuple
Mapping Type dict
Boolean Type bool

12. What are the numeric data types in Python?


The Numeric Data Types in Python are:

Integers
Float
Complex Numbers

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.
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
Examples: int, float, str, tuple Examples: list, dict, set

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

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@example.com"
"1234"

8. What is String Slicing?


Obtaining a part of a string is called String Slicing.

end_index is not included in the slice.


message = "Hi Ravi"
part = message[3:7]
print(part) //Rav

Slicing to End
If the end index is not specified, slicing stops at the end of the string.
message = "Hi Ravi"
part = message[3:]
print(part) //Ravi

Slicing from Start


If the start index is not specified, slicing starts from the index 0.
message = "Hi Ravi"
part = message[:2]
print(part) //Hi

19. How to reverse a string?


A string can be reversed using extended slicing.
-1 for step will reverse the order of the characters.
string_1 = "Program"
string_2 = string_1[::-1]
print(string_2) /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.
sentence = "proGraMmiNg"
capitalized_string = sentence.capitalize()
print(capitalized_string) //Programmin

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)

sentence = "teh cat and teh dog"


sentence = sentence.replace("teh", "the")
print(sentence)

the cat and the

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.

a = round(3.14159, 2)
print(a)
a = round(5.6777)
print(a)

3.14
6

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.

24. 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.
__iter__() Called to initialize the iterator. It must return an iterator object.
__next__() Called to iterate over the iterator. It must return the next value in the data stream.
2. What are conditional statements?
The Conditional Statement allows you to execute a block of code based on a condition.
If statement
The Conditional Statement allows you to execute a block of code only when a specific condition is
True.
if True:
print("If Block")
print("Inside If")

//If Block
Inside I

If-Else statement
When If-Else conditional statement is used, the Else block of code executes if the condition is False.

a = int(input())
if a > 0:
print("Positive")
else:
print("Not Positive")
print("End")// input :- 2 //Positive
End

3. What are Loops?


Loops allow us to execute a block of code several times.

The loops in Python are:

While Loop
For Loop

4. What is the use of while loop?


While loop allows us to execute a block of code several times as long as the condition is True.

a = int(input())
counter = 0
while counter < 3:
a=a+1
print(a)
counter = counter + 1 //input :- 4 //output :- 5 6 7

5. How to create a do-while loop in python?


Generally, in other programming languages, we will have another loop called the do-while loop.

In do-while loops, the code in the loop runs at least once before checking if the condition is True.

The do-while loop is not directly available in Python.

#include <stdio.h>

int main () {
int a = 1;
do {
printf("%d\n", a);
a = a + 1;
}while( a < 4 );
return 0;
}

What is the use of for loop?


The for loop is used to execute a block of code a known number of times. The for statement
iterates over each item of a sequence.
word = "Python"
for each_char in word:
print(each_char)
// output:-
P
y
t
h
o
N
7. What are range() and xrange() functions?
range():
The range() function generates a sequence of integers starting from 0 to n(n is not included) and
returns it.
Syntax: range(n)
for number in range(3):
print(number) //0
1
2

Range with Start and End


Syntax: range(start, end)
Generates a sequence of numbers starting from start to end (end is not included).
for number in range(5, 8):
print(number)

xrange():
The xrange() function generates a sequence of integers starting from 0 similar to range() function.
Note: The xrange() function is deprecated from Python3. You cannot run xrange() function in our
code playground

Q. What is the range function in Python?


The range() function returns a sequence of numbers, starting from 0 by default, and increment the
step by 1 (by default), and stops before a specified number.

range(start, stop, step)


x = range(3, 9, 2)
for n in x:
print(n) #Output: 3 5 7

8. When does an infinite loop occurs?


An infinite loop occurs when the condition always evaluates to True i.e. incorrect termination
condition.

a = 10
while a > 3:
a=a+1
print(a)

9. What are Nested Loops?


An inner loop within the repeating block of an outer loop is called Nested Loop.

The Inner Loop will be executed one time for each iteration of the Outer Loop.

for i in range(2):
print("Outer: " + str(i))
for j in range(2):
print(" Inner: " + str(j))

// output
Outer: 0
Inner: 0
Inner: 1
Outer: 1
Inner: 0
Inner: 1

Q. How does Inner loop work in nested loops in Python?


In Python, the term inner loop typically refers to a loop that is nested (inside) within another loop.

10. What is a break statement?/ How to exit from a loop?


Break statement makes the program exit a loop early.

Generally, break is used to exit a loop when a condition is satisfied.

for i in range(5):
if i == 3:
break
print(i)
print("END")
//0
1
2
END

11. What is continue in loops?


The continue statement makes the program skip the remaining statements in the current iteration
and begin the next iteration.
Generally, continue is used to skip the remaining statements in the current iteration when a
condition is satisfied.

0
1
2
4
END

12. What is pass in Python?


The pass statement is a syntactic placeholder. When it is executed, nothing happens.
Generally it used when we have to test the code before writing the complete code.

Q. Write a program to print the following pattern:


First Line: Odd Numbers
Second Line: Even Numbers
Example : //
135
246

not:-The interviewer expects you to print the odd numbers on the first line and the even numbers
on the second line, for numbers ranging from 1 to N.

even_numbers_string = ""

for num in range(1,number+1):


if num % 2 != 0:
odd_numbers_string += str(num)
else:
even_numbers_string += str(num)

print(odd_numbers_string)
print(even_numbers_string)

Q. Write a program to print the following pattern.

1
13
13

The interviewer expects you to print the odd numbers as a right angled triangle of N rows

rows = int(input())

odd_number = 1
for i in range(1, rows + 1):
odd_number = 1
output = ""
for j in range(1, i + 1):
output += str(odd_number) + " "
odd_number += 2
print(output)

he outer loop for i in range(1, rows + 1)represents the range of rows, the inner loop for j in range(1,
i + 1) iterates through the rows, prints the odd numbers, and then increments the odd number
odd_number += 2.

Q. Write a program to print Right angled traingle with odd numbers.

def print_triangle(n):
current_number = 1
for i in range(1, n + 1):
row_values = ""
for j in range(i):
row_values += str(current_number) + " "
current_number += 2
print(row_values)

rows = int(input())
print_triangle(rows)

1. What are the Data Structures?


Data Structures allow us to store and organize data efficiently.
This will allow us to easily access and perform operations on the data.

In Python, there are four built-in data structures

List
Tuple
Set
Dictionary

. What is a list?
The List is the most versatile python data structure that holds an ordered sequence of items.

Creating a List
A List can be created by enclosing elements within [square] brackets where each item is separated
by a comma.

a=2
list_a = [5, "Six", a, 8.2]

print(type(list_a))
print(list_a)//<class 'list'>
[5, 'Six', 2, 8.2]

3. Explain a few List Methods?


Append
Adds an element to the end of the list.

Syntax
list.append(value)

list_a = []
for x in range(1, 4):
list_a.append(x)

print(list_a)

[1, 2, 3]

Extend
Adds all the elements of a sequence to the end of the list.

Syntax
list_a.extend(list_b)

list_a = [1, 2, 3]
list_b = [4, 5, 6]
list_a.extend(list_b)

print(list_a)

[1, 2, 3, 4, 5]

Insert
Inserts the given element at the specified index.

Syntax
list.insert(index, value)

list_a = [1, 2, 3]
list_a.insert(1, 4)

print(list_a)

[1, 4, 2, 3]

Pop
Removes the last item from the list.

Syntax
list.pop()
list_a = [1, 2, 3]
list_a.pop()

print(list_a)

[1, 2]

Remove
Removes the first matching element from the list.

Syntax
list.remove(value)

list_a = [1, 3, 2, 3]
list_a.remove(3)

print(list_a)

[1, 2, 3]

Clear
Removes all the items from the list.
Syntax
list.clear()

list_a = [1, 2, 3]
list_a.clear()

print(list_a) /[]

Index
Returns the index of the first occurrence of the specified item in the list.

Syntax
list.index(item)

list_a = [1, 3, 2, 3]
index = list_a.index(3)

print(index)

Count
Returns the number of elements with the specified value.

Syntax
list.count(value)

list_a = [1, 2, 3]
count = list_a.count(2)

print(count)

Sort
Sorts the items of a list in ascending ascending order. The sort() method modifies the original list.

Syntax
list.sort()

list_a = [1, 3, 2]
list_a.sort()

print(list_a)//[1, 2, 3]

Sorted
Sorts the items of a list in ascending ascending order. The sorted() method returns the modified list.

Syntax
sorted()

Q. With which data types can we use the pop() method in Python?
The pop() method can be used with three different data types in Python: lists, dictionaries, and sets.

Lists: The pop() method removes the specified item from a list. If no index is specified, the last
element is removed.
Dictionaries: The pop() method removes the specified item from a dictionary. The method returns
the value of the removed item.

Sets: The pop() method removes a random item from a set. The method returns the removed item.

The append() method is used to add an entire list to another list. In this case, temp is appended to
lst, resulting in lst containing 1, 2, and the entire temp list.

The extend() method is used to add the elements of one list to the end of another list. In this case,
the elements of temp are added to the end of lst. Therefore, lst will contain the following elements: 1,
2, [3, 4], 3, 4.

2. Explain List extends in Python?


Intent of the interviewer:

Extending a list in Python means adding one or more elements to the end of the list. There are
several ways to extend a list in Python, including:

Using the extend() method: Adds all the elements of an iterable to the end of the list.
Using the + operator: Concatenate two lists together.
Using list slicing: Insert a new element or list of elements into the end of a list.

There are four methods to add elements to a List in Python.

append(): append the element to the end of the list.

insert(): This method inserts the element at a specific position in the list.

extend(): Adds all the elements of an iterable to the end of the list.

List Concatenation: Concatenate two lists together.

Q. What is the difference between the append() and extend() methods for lists in Python?
When I use append(), it adds a single element to the end of the list. This element can be of any data
type, and it's added as a single item. So, if I append another list to an existing list, the entire list will be
added as a single element.

On the other hand, extend() is used to merge two lists or add multiple elements. When I use
extend() with a list as an argument, each element of the list argument is added individually to the end
of the original list.

5. How to use the split() method?


The split() splits a string into a list at every specified separator.

Syntax:
str_var.split(separator)

7. What is List Slicing?


Obtaining a part of a list is called List Slicing.

Syntax:

end_index is not included in the slice.


Extended Slicing
Similar to string extended slicing, we can extract alternate items from the list using the step.

Syntax:
variable[start_index:end_index:step]

Q. What is Slicing in python?


Slicing in Python refers to the technique of extracting a portion of a sequence, such as a list, tuple,
or string. It allows you to create a new sequence by specifying a range of indices.

sequence[start:stop:step]

You might also like