Core Python Basic Questions & Answers
Core Python Basic Questions & Answers
& Answers
1)How does the python code executes?
Answer:-
Below are the steps to execute the Python program.
Write a python program
Execute the program using Python Compiler.
Python compiler converts Python code to byte code.
By using PVM we convert byte code into machine code.
The processor reads the machine code and its result is displayed.
• None Type
• Numeric Types
• Sequences
• Sets
• Mappings
The data types which are created on the basis of business requirements are called
user-defined datatypes. The following data types are available in Python
. Array
. Class
. Module
. int
. long
. float
. complex
When we write the second lambda function inside the lambda functions, it is
called the nested lambda function.
<strong>Syntax:</strong>
map(function_name, iterable )
Function name - This is the function which performs the operation on all the elements and
the modified elements are returned and they are stored in another sequence.
An iterable - iterable sequence such as list, string, or tuple
• List Comprehension
• Set Comprehension
• Dictionary Comprehension
def squr(num) :
x = 10
print(x)
print(x+num)
squr(5)
print(x)
In Python classes, the reserved method init serves a similar purpose as constructors
in object-oriented programming (OOP) terminology. When a new object is created,
the init method is automatically called, initializing the object and allocating memory
for it. This method can also be utilized to set initial values for variables.
class Human:
def __init__(self, age):
self.age = age
def say(self):
print('Hello, my age is', self.age)
h = Human(22)
Output:
Hello, my age is 22
38) What Are The Principal Differences Between The Lambda And Def?
Answer:-
Def can hold multiple expressions while lambda is a uni-expression function.
Def generates a function and designates a name to call it later. Lambda forms a
function object and returns it.
Def can have a return statement. Lambda can’t have return statements.
Lambda supports to get used inside a list and dictionary.
== checks for equality of values, while ‘is’ checks for identity (whether they refer to
the same object).
50) How do you represent a complex number in Python?
Answers:-
Complex numbers are represented as a + bj in Python, where ‘a’ and b are real
numbers, and j represents the imaginary unit.
Answer:-
Answer:-
The continue is a jump statement in Python which moves the control to execute the
next iteration in a loop leaving all the remaining instructions in the block unexecuted.
The continue statement is applicable for both the “while” and “for” loops.
Answer:-
Python provides a break statement to exit from a loop. Whenever the break hits in
the code, the control of the program immediately exits from the body of the loop.
The break statement in a nested loop causes the control to exit from the inner iterative block.
54)What is Encapsulation?
Answer:-
Encapsulation is also a part of the OOPs concept. It refers to the bundling of data
with the methods that operate on that data. It also helps to restrict any direct access
to some of an object’s components.
In Python, a constructor is a special method used to initialize objects. You can think
of it as blueprint instructions for creating objects.
If you don’t define a constructor in your class, Python provides a default one.
However, defining your own constructor gives you more control over the object
initialization process.
A decorator in Python is a function that you can use to modify or extend the behavior
of other functions or methods without changing their code. In the context of OOP,
decorators can be used to add functionality to methods within classes, such as
logging or access control.
You can think of decorators as wrappers around a function or method. When you call
a decorated function, the decorator’s code runs first, allowing you to perform actions
before or after the original function. It helps keep the code clean and adhere to the
OOP reusability principle.
For example, while using a mobile, you know, how can you message or call someone
but you don’t know how it actually happens.
This is data abstraction as the implementation details are hidden from the user.
Within this class, you can define abstract methods using the @abstractmethod
decorator. These abstract methods serve as a blueprint for other classes, enforcing
that the derived classes must provide a concrete implementation of these methods.
If a derived class does not implement the abstract methods, an instantiation error will occur.
59)Differentiate between an abstract class and an interface?
Answer:-
An interface can have only abstract methods, but an Abstract class can have abstract
and non-abstract methods.
The interface should be used if just the requirement specification is known and
nothing about implementation. If the implementation is known, but partially, then an
abstract class should be used. If the implementation is known completely, then a
concrete Class should be used.
If you have a method in a child class with the same name as a method in the parent
class, you can use super() to call the parent method within the child method. This is
particularly useful when you want to extend or modify the behavior of the parent
method in the child class.
By using super(), you ensure that your code follows the inheritance hierarchy. It also
makes the code more maintainable, as changes in the parent class can be easily
propagated to child classes.
A class method, on the other hand, is defined with the @classmethod decorator and
takes a reference to the class itself as its first parameter – usually named “cls.” It can
access and modify class-level attributes, while a static method can’t.
A class method is more versatile as subclasses can override it, whereas a static
method remains unchanged.
62)Are class and structure the same? If not, what's the difference between a class and
a structure?
Answer:-
No, class and structure are not the same. Though they appear to be similar, they
have differences that make them apart. For example, the structure is saved in the
stack memory, whereas the class is saved in the heap memory. Also, Data
Abstraction cannot be achieved with the help of structure, but with class, Abstraction
is majorly used
63)What is meant by Garbage Collection in OOPs world?
Answer:-
Object-oriented programming revolves around entities like objects. Each object
consumes memory and there can be multiple objects of a class. So if these objects
and their memories are not handled properly, then it might lead to certain memory-
related errors and the system might fail.
Garbage collection refers to this mechanism of handling the memory in the program.
Through garbage collection, the unwanted memory is freed up by removing the
objects that are no longer needed.
Practical
1) Converting numbers from decimal to binary using while loop
Answers:-
num = int(input("Enter a number: "))
b=0
p=1
n = num
while n>0:
rem = n%2
b += rem * p
p = p*10
n = n//2
print("Binary value: ",b)
2)
3)python function program to display a calender?
def string_test(s):
d={"UPPER_CASE":0, "LOWER_CASE":0}
for c in s:
if c.isupper():
d["UPPER_CASE"]+=1
elif c.islower():
d["LOWER_CASE"]+=1
else:
pass
print ("Original String : ", s)
print ("No. of Upper case characters : ", d["UPPER_CASE"])
print ("No. of Lower case Characters : ", d["LOWER_CASE"])
5) Write a Python function to create and print a list where the values are the squares
of numbers between 1 and 30 (both included).
def printValues():
l = list()
for i in range(1,21):
l.append(i**2)
print(l)
printValues()
For example : "The quick brown fox jumps over the lazy dog"
print ( ispangram('The quick brown fox jumps over the lazy dog'))
7) Write a Python function that checks whether a passed string is a palindrome or not.
Note: A palindrome is a word, phrase, or sequence that reads the same backward as
forward, e.g., madam or nurses run.
def isPalindrome(string):
left_pos = 0
right_pos = len(string) - 1
while right_pos >= left_pos:
if not string[left_pos] == string[right_pos]:
return False
left_pos += 1
right_pos -= 1
return True
print(isPalindrome('aza'))
8) Write a Python function that takes a number as a parameter and checks whether
the number is prime or not.
Note : A prime number (or a prime) is a natural number greater than 1 and that has no
positive divisors other than 1 and itself.
def test_prime(n):
if (n==1):
return False
elif (n==2):
return True;
else:
for x in range(2,n):
if(n % x==0):
return False
return True
print(test_prime(9))
8) How do you swap the values of two variables in Python without using a temporary
variable? and write a program to swap values using tuple or arithmetic operations ?
Answer:-
Example:
a=6
b=9
b, a = a, b
print("a =", a)
print("b =", b)
Output
a=9
b=6
a=6
b=9
a=a+b
b=a-b
a=a-b
print("a =", a)
print("b =", b)
Output
a=9
b=6
9) Filter integer values from the given list and find the sum of the integers
List= ["Python", "Java", "Ruby", 3, 4, 7, "PHP", 10 ,"+C++"]
Answer:-
List= ["Python", "Java", "Ruby", 3, 4, 7, "PHP", 10 ,"+C++"]
integers = [x for x in List if isinstance(x, int)]
sum_of_integers = sum(integers)
print("Integers:", integers)
print("Sum of Integers:", sum_of_integers)
Output
Sum of Integers: 24
11) Write a Python program to create a class that represents a shape. Include
methods to calculate its area and perimeter. Implement subclasses for different
shapes like circle, triangle, and square.
# Import the math module to access mathematical functions like pi
import math
# Define a base class called Shape to represent a generic shape with methods for
calculating area and perimeter
class Shape:
# Placeholder method for calculating area (to be implemented in derived classes)
def calculate_area(self):
pass
# Define a derived class called Circle, which inherits from the Shape class
class Circle(Shape):
# Initialize the Circle object with a given radius
def __init__(self, radius):
self.radius = radius
# Calculate and return the area of the circle using the formula: π * r^2
def calculate_area(self):
return math.pi * self.radius**2
# Calculate and return the perimeter of the circle using the formula: 2π * r
def calculate_perimeter(self):
return 2 * math.pi * self.radius
# Define a derived class called Rectangle, which inherits from the Shape class
class Rectangle(Shape):
# Initialize the Rectangle object with given length and width
def __init__(self, length, width):
self.length = length
self.width = width
# Calculate and return the area of the rectangle using the formula: length * width
def calculate_area(self):
return self.length * self.width
# Calculate and return the perimeter of the rectangle using the formula: 2 * (length +
width)
def calculate_perimeter(self):
return 2 * (self.length + self.width)
# Define a derived class called Triangle, which inherits from the Shape class
class Triangle(Shape):
# Initialize the Triangle object with a base, height, and three side lengths
def __init__(self, base, height, side1, side2, side3):
self.base = base
self.height = height
self.side1 = side1
self.side2 = side2
self.side3 = side3
# Calculate and return the area of the triangle using the formula: 0.5 * base * height
def calculate_area(self):
return 0.5 * self.base * self.height
# Calculate and return the perimeter of the triangle by adding the lengths of its three sides
def calculate_perimeter(self):
return self.side1 + self.side2 + self.side3
# Example usage
# Create a Circle object with a given radius and calculate its area and perimeter
r=7
circle = Circle(r)
circle_area = circle.calculate_area()
circle_perimeter = circle.calculate_perimeter()
# Create a Rectangle object with given length and width and calculate its area and perimeter
l=5
w=7
rectangle = Rectangle(l, w)
rectangle_area = rectangle.calculate_area()
rectangle_perimeter = rectangle.calculate_perimeter()
# Create a Triangle object with a base, height, and three side lengths, and calculate its area
and perimeter
base = 5
height = 4
s1 = 4
s2 = 3
s3 = 5
12)Write a Python class named Student with two attributes student_id, student_name.
Add a new attribute student_class and display the entire attribute and the values of
the class. Now remove the student_name attribute and display the entire attribute with
values.
class Student:
student_id = 'V10'
student_name = 'Jacqueline Barnett'
print("Original attributes and their values of the Student class:")
for attr, value in Student.__dict__.items():
if not attr.startswith('_'):
print(f'{attr} -> {value}')
print("\nAfter adding the student_class, attributes and their values with the said class:")
Student.student_class = 'V'
for attr, value in Student.__dict__.items():
if not attr.startswith('_'):
print(f'{attr} -> {value}')
print("\nAfter removing the student_name, attributes and their values from the said class:")
del Student.student_name
#delattr(Student, 'student_name')
for attr, value in Student.__dict__.items():
if not attr.startswith('_'):
print(f'{attr} -> {value}')
13.Write a Python class to get all possible unique subsets from a set of distinct
integers.
Input : [4, 5, 6]
Output : [[], [6], [5], [5, 6], [4], [4, 6], [4, 5], [4, 5, 6]]
class py_solution:
def sub_sets(self, sset):
return self.subsetsRecur([], sorted(sset))
print(py_solution().sub_sets([4,5,6]))
14.Write a Python class to reverse a string word by word.
Input string : 'hello .py'
Expected Output : '.py hello'
class py_solution:
def reverse_words(self, s):
return ' '.join(reversed(s.split()))
print(py_solution().reverse_words('hello .py'))
15.Write a Python class to find a pair of elements (indices of the two numbers) from a
given array whose sum equals a specific target number.
Note: There will be one solution for each input and do not use the same element
twice.
Input: numbers= [10,20,10,40,50,60,70], target=50
Output: 3, 4
class py_solution:
def twoSum(self, nums, target):
lookup = {}
for i, num in enumerate(nums):
if target - num in lookup:
return (lookup[target - num], i )
lookup[num] = i
print("index1=%d, index2=%d" % py_solution().twoSum((10,20,10,40,50,60,70),50))
16. Write a Python class that has two methods: get_String and print_String ,
get_String accept a string from the user and print_String prints the string in upper
case?
class IOString():
def __init__(self):
self.str1 = ""
def get_String(self):
self.str1 = input()
def print_String(self):
print(self.str1.upper())
str1 = IOString()
str1.get_String()
str1.print_String()
class Employee:
def __init__(self, name, emp_id, salary, department):
self.name = name
self.id = emp_id
self.salary = salary
self.department = department
def print_employee_details(self):
print("\nName: ", self.name)
print("ID: ", self.id)
print("Salary: ", self.salary)
print("Department: ", self.department)
print("----------------------")
18)Create a list with different type of elements as input , find the string elements from
that list.
Eg:-
List inputs:-
list = [10,”ABCD”,True,300,40,”QWERTY”,”Hello”]
Output:-
[”ABCD”, ”QWERTY”, ”Hello”]