Top 10+ Interview Question and Answers on Python
Discover the Top 1o+ Interview Question and Answers on Python to ace your next tech interview. Get expert insights on key concepts, coding, and best practices!
1. Write a Python function custom_print() that demonstrates the use of the sep, end, and file parameters in the print() function.
-
Print three words “Hello”, “World”, and “Python”, with each word separated by a hyphen (-), and the output should end with an exclamation mark (!) instead of a newline.
-
Then, redirect the output to a file called output.txt where the words “SevenMentor”, “DataSci”, and “MachineLearning” should be printed, separated by a comma (,), without a newline at the end.
Ans: –
def custom_print():
# Using sep, end to format the output on the console
print (“Hello”, “World”, “Python”, sep=”-“, end= “! \n”)
# Redirecting output to a file with file parameter
with open (“output.txt”, “w”) as file:
print (“SevenMentor “, ” DataSci “, ” MachineLearning “, sep=”,”, end=””, file=file)
# Call the function to demonstrate the solution
custom_print()
Output 🡪
- Console Output:
Hello-World-Python!
- Content in output.txt:
SevenMentor, DataSci, MachineLearning.
2. What is the purpose of a comment in Python, and how do you create one?
Ans:
A comment is used to explain the code or make the code more readable. It does not affect the execution of the program. They are ignored by the Python interpreter during runtime and are purely for human readability.
purposes:
- Documentation: Comments explain the purpose, logic, and functionality of code segments. They help other programmers (or your future self) understand the code more easily.
- Clarification: Comments provide context, explanations, or reminders about specific parts of the code. They can clarify complex algorithms, business rules, or design decisions.
3 . Debugging: Comments can be used to temporarily disable code segments during testing or debugging. This helps isolate and identify issues in the code.
# This is a single-line comment
print (“Hello, World!”) # This is an inline comment.
3. What is a docstring in Python, and how do you define it? Provide an example of both a single-line and multi-line docstring.
ANS:
A docstring is used to describe a module, class, or function. It provides documentation for the code and is typically used to explain the purpose and usage of a function or class. Docstrings are written inside triple quotes (”’ or “””) and can span multiple lines. A single-line docstring can also be written using triple quotes.
- Single-line docstring:
def greet ():
“””This function prints a greeting message.”””
print(“Hello!”)
- multi-line docstring:
def add (a, b):
“””
This function takes two numbers as input and returns their sum.
Parameters:
a (int or float): The first number.
b (int or float): The second number.
Returns:
int or float: The sum of a and b.
“””
return a + b
For Free, Demo classes Call: 02071171500
Registration Link: Click Here!
4. Explain the text data type in Python and how strings are used to represent textual information.
ANS:
The text data type is represented by strings. A string is a sequence of characters used to store and manipulate textual data. Strings can represent letters, numbers, symbols, or any combination of characters.
- Creating Strings:
- Strings can be defined using either single quotes (‘) or double quotes (“). Both methods are valid and function the same way. And also use triple quotes (”’ or “””) for multi-line strings.
# Single quotes
text1 = ‘Hello, World!’
# Double quotes
text2 = “Python is great!”
# Triple quotes for multi-line strings
text3 = ”’ This is a
multi-line string. ”’
text4 = “”” You can use triple quotes
to span the text over multiple lines. “””
- Using Strings to Represent Textual Information:
Strings are commonly used to represent all kinds of textual information in Python codes.
- Names.
- Sentences or paragraphs.
- User input.
- File paths.
- Any other form of textual data.
name = “SevenMentor”
greeting = “Hello, ” + name + “!”
print(greeting) # Output: Hello, SevenMentor!
Strings are a fundamental data type in Python, used extensively to represent and manipulate text. They support a wide variety of operations and methods that make it easy to work with textual information
- String Operations:
Concatenation: Combining strings together using the + operator.
full_name = “SevenMentor” + ” ” + “PVT Ltd ” # Result: ” SevenMentor PVT Ltd “
Repetition: Repeating a string using the * operator. :
repeated = “Okey” * 3 # Result: ” Okey Okey Okey “
Indexing and Slicing: Accessing individual characters or parts of a string.
text = “Python”
print(text[0]) # Output: ‘P’
print(text[1:4]) # Output: ‘yth’
- Escape Characters:
Strings in Python can include special characters, such as newlines (\n), tabs (\t), or quotes within quotes, by using escape sequences.
text1 = “Hello\nWorld” # Newline between words
text2 = “Tab\tSpace” # Tab space
text3 = “He said, \”Python is awesome!\”” # Quotation marks inside the string.
- String Formatting:
Format strings to insert variable values into a string
# Old-style formatting (using %):
name = “Shiv”
age = 27
message = “My name is %s and I am %d years old.” % (name, age)
print(message) # Output: My name is Shiv and I am 27 years old.
- f-strings (available in Python 3.6+):
name = “Shiv”
age = 27
message = f”My name is {name} and I am {age} years old.”
print(message) # Output: My name is Shiv and I am 27 years old.
5. Define data type casting in Python and explain how it is used to convert data from one type to another.
ANS:
Data type casting (also known as type conversion) in Python refers to the process of converting a variable’s value from one data type to another. This is necessary when you need to perform operations between different data types or when you need to store or process data in a specific type.
Two Types:
- Implicit Type Casting (Automatic Casting)
Implicit type casting occurs when Python automatically converts a lower data type to a higher data type. This usually happens when you mix different types in an operation, and Python handles the conversion for you to prevent data loss.
x = 5 # Integer
y = 3.2 # Float
result = x + y # Python automatically converts x to float
print(result) # Output: 8.2
- Explicit Type Casting (Manual Casting):
Explicit type casting, also known as type conversion, is when you manually convert one data type to another using built-in functions. You can use functions like:
- int () — Converts to an integer.
- float () — Converts to a float.
- str () — Converts to a string.
- bool () — Converts to a Boolean.
num = 3.7
integer_Num = int(num) # Converts float to integer
print(integer_Num) # Output: 3
Output Of the following Code ?
for i in range (1, 6):
if i == 3:
break
print(i)
Answer:
1 2
The for loop runs from 1 to 5. When i == 3, the break statement is encountered, which exits the loop. So, it prints 1 and 2 before the loop terminates.
Output Of the following code ?
x = 0
while x < 5:
x += 1
if x == 3:
continue
print(x)
ANS:
1 2 4 5
The while loop runs as long as x is less than 5. When x == 3, the continue statement is encountered, which skips the print(x) statement for x = 3 and moves to the next iteration. So, it prints 1, 2, 4, and 5.
Output of the following code?
x = 10
y = 5
while x > 0:
if x % y == 0:
break
y += 1
x -= 2
else:
print (“End of loop”)
ANS:
Initially, x = 10 and y = 5.
- In the first iteration of the while loop:
- x % y == 10 % 5 == 0 → the if condition is True.
- The loop immediately breaks due to the break statement.
- Since the else block is associated with the while loop (but only executes if the loop doesn’t break), it is not executed in this case.
- The loop breaks before printing anything.
Output of the following code?
x = 10
y = 20
z = 30
if x > y:
if x > z:
print (“X is the greatest”)
else:
print (“Z is the greatest”)
else:
if y > z:
print (“Y is the greatest”)
else:
print (“Z is the greatest”)
Ans:
Z is the greatest
- Since x = 10, y = 20, and z = 30, the first if condition (x > y) is False, so it moves to the else block.
- In the else block, y = 20 and z = 30. Since z > y, the program prints “Z is the greatest”.
Output of the following code?
x = 2
for i in range (1, 6):
x += 1
if i % 2 == 0:
x -= 2
elif i == 5:
x += 3
else:
x += 4
print (x, end=” “)
Ans:
7 8 8 10 14
- Initially, x = 2. The for loop runs for i from 1 to 5:
- For i = 1: x = 2 + 1 + 4 = 7
- For i = 2: x = 7 + 1 – 2 = 8
- For i = 3: x = 8 + 1 + 4 = 13
- For i = 4: x = 13 + 1 – 2 = 12
- For i = 5: x = 12 + 1 + 3 = 16
- The printed output will be: 7 8 8 10 14
6. From sides of triangle. decide whether it is:
1. equilateral (all sides are equal)
2. isoscalus (any two sides are equal)
3. right angled (pythagoras)
4. scalen (all sides are different)
ANS:
def classify_triangle(a, b, c):
# Check for equilateral
if a == b == c:
return “Equilateral”
# Check for right-angled triangle (using Pythagoras’ theorem)
sides = sorted([a, b, c]) # Sort the sides so that sides[2] is the largest
if sides[0]**2 + sides[1]**2 == sides[2]**2:
return “Right-angled”
# Check for isosceles (any two sides are equal)
if a == b or b == c or a == c:
return “Isosceles”
# If none of the above, it’s scalene
return “Scalene”
# Example usage
a = float (input (“Enter the first side: “))
b = float (input (“Enter the second side: “))
c = float (input (“Enter the third side: “))
# Classify the triangle
triangle_type = classify_triangle(a, b, c)
print (“The triangle is:”, triangle_type)
Input:
Enter the first side: 5
Enter the second side: 5
Enter the third side: 8
Output:
The triangle is: Isosceles
Do Read
7. How do you check if a substring exists in a string by using in operator, find() and index() method?
ANS :
- Using the in operator:
main_string = “Hello, world!”
substring = “world”
# Using the ‘in’ operator
if substring in main_string:
print(“Substring found!”)
else:
print (“Substring not found!”)
- Using the find () method:
main_string = “Hello, world!”
substring = “world”
# Using the ‘find()’ method
index = main_string.find(substring)
if index != -1:
print (f”Substring found at index {index}!”)
else:
print(“Substring not found!”)
- Using the index() method:
main_string = “Hello, world!”
substring = “world”
# Using the ‘index()’ method
try:
index = main_string.index(substring)
print (f”Substring found at index {index}!”)
except ValueError:
print (“Substring not found!”)
8. How do you check if a string contains only ASCII characters?
ANS:
- Using the isascii() method (Python 3.7+)
text = “Hello World!” # ASCII string
if text.isascii():
print(“The string contains only ASCII characters.”)
else:
print(“The string contains non-ASCII characters.”)
Output —- The string contains only ASCII characters.
- Using the all() function with ord()
text = “Hello World!”
# Using Ord () with all () to check if all characters are in the ASCII range (0 to 127)
if all (Ord(c) < 128 for c in text):
print (“The string contains only ASCII characters.”)
else:
print (“The string contains non-ASCII characters.”)
Output — The string contains only ASCII characters.
9. How do you remove duplicate characters from a string in Python?
ANS :
- Using a Set (Preserving First Occurrence Order).
input_string = “programming”
# Using a set to remove duplicates while preserving order
output_string = ”.join(sorted(set(input_string), key=input_string.index))
print(output_string) # Output: ‘progamin’e
- Using a Loop to Build a New String.
input_string = “programming”
output_string = “”
for char in input_string:
if char not in output_string:
output_string += char
print(output_string) # Output: ‘progamin’
10. How do you check if a string is a valid email address in Python?
ANS :
- Using Regular Expressions (Regex)
import re
def is_valid_email(email):
# Define the regular expression for a valid email
email_regex = r’^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$’
# Match the email with the regex pattern
if re.match(email_regex, email):
return True
else:
return False
# Example usage
email = “test@example.com”
if is_valid_email(email):
print(f”{email} is a valid email address.”)
else:
print(f”{email} is not a valid email address.”)
- Using email_validator Library (Recommended)
pip install email-validator
from email_validator import validate_email, EmailNotValidError
def is_valid_email(email):
try:
# Validate email using email_validator
validate_email(email)
return True
except EmailNotValidError as e:
return False
# Example usage
email = “test@example.com”
if is_valid_email(email):
print(f”{email} is a valid email address.”)
else:
print(f”{email} is not a valid email address.”)
- Using validate_email from email.utils (Basic Syntax Checking)
from email.utils import parseaddr
def is_valid_email(email):
name, addr = parseaddr(email)
if addr and ‘@’ in addr:
return True
return False
# Example usage
email = “test@example.com”
if is_valid_email(email):
print(f”{email} is a valid email address.”)
else:
print(f”{email} is not a valid email address.”)
11. Write a Python program to find the third-largest number in a list.
- By sorting the list.
def third_largest(numbers):
# Sort the list in descending order
sorted_numbers = sorted(numbers, reverse=True)
# Return the third-largest number
if len(sorted_numbers) >= 3:
return sorted_numbers[2]
else:
return “The list does not have enough elements.”
# Example usage
numbers = [10, 20, 4, 45, 99, 77]
result = third_largest(numbers)
print(“The third-largest number is:”, result)
OutPut — The third-largest number is: 45
- Using a Set (to Remove Duplicates) and Sorting.
def third_largest(numbers):
# Remove duplicates by converting to a set, then sort in descending order
unique_numbers = sorted(set(numbers), reverse=True)
# Return the third-largest number
if len(unique_numbers) >= 3:
return unique_numbers[2]
else:
return “The list does not have enough unique elements.”
# Example usage
numbers = [10, 20, 4, 45, 99, 77, 99]
result = third_largest(numbers)
print(“The third-largest unique number is:”, result)
OutPut– The third-largest unique number is: 45
- Using a Loop (Efficient Method).
def third_largest(numbers):
if len(numbers) < 3:
return “The list does not have enough elements.”
# Initialize three variables to store the largest, second-largest, and third-largest numbers
first, second, third = float(‘-inf’), float(‘-inf’), float(‘-inf’)
for num in numbers:
if num > first:
first, second, third = num, first, second
elif num > second:
second, third = num, second
elif num > third:
third = num
return third
# Example usage
numbers = [10, 20, 4, 45, 99, 77]
result = third_largest(numbers)
print(“The third-largest number is:”, result)
OutPut — The third-largest number is: 45
Do visit our channel to learn More: Click Here
Author:-
Shivsharan Kunchalwar
Call the Trainer and Book your free demo Class for Python Call now!!!
| SevenMentor Pvt Ltd.
© Copyright 2025 | SevenMentor Pvt Ltd