Example 1
Explanation
- The code creates a list L containing integers 1, 2, and 3
- It attempts to call the upper() method on the list, which is a string method not available for lists
- This will raise an AttributeError because lists don't have an upper() method
- The error occurs at runtime when trying to execute L.upper()
- Expected outcome is a traceback showing AttributeError: 'list' object has no attribute 'upper'
Output
Example 2
Explanation
- This code attempts to add the character 'x' to the string 'hello' using the append method
- Strings in Python are immutable objects, so they don't have an append method like lists do
- The code will raise an AttributeError because string objects don't support the append operation
- Key API error: AttributeError is raised when calling append() on a string object
- Expected outcome: Runtime error occurs before any output can be produced
Example 3
Explanation
- This comment emphasizes that Python treats everything as objects, which is a fundamental concept in the language
- It highlights how even basic elements like numbers, strings, and functions are objects with properties and methods
- The statement reflects Python's object-oriented nature where every entity has a type and can be manipulated through object methods
- This principle enables powerful features like dynamic typing, method calling on any object, and flexible programming patterns
- The comment serves as a reminder that understanding object behavior is crucial when working with Python's rich ecosystem of built-in and custom objects
Example 4
Explanation
- Creates a list variable L with elements 1, 2, and 3
- Uses the type() function to determine the data type of L
- Prints the result showing that L is a list object
- The type() function returns the class type of an object
- Output will display "<class 'list'>" indicating L is a list data structure
Output
Example 5
Explanation
- The code calls the
upper()method on variableL, which converts all lowercase characters inLto uppercase upper()is a built-in string method that returns a new string with all letters capitalized- The code assumes
Lcontains a string value, asupper()only works on string data types - This operation creates a new string rather than modifying the original
Lin place - If
Lis not a string type, this would raise an AttributeError since non-string objects don't have anupper()method
Output
Example 6
Explanation
- Creates an empty list object using the list() constructor function
- Stores the empty list in variable L
- Prints the empty list to console, which outputs: []
- Uses Python's built-in list() constructor to initialize a new list instance
- Demonstrates basic object instantiation syntax in Python with empty parentheses
Output
Example 7
Explanation
- Creates an empty string object using the str() constructor and assigns it to variable s
- Prints the empty string, which displays nothing visible since it contains no characters
- Uses the built-in str() function to create a string type instance
- The print() function outputs the string representation of s to console
- Side effect is displaying an empty line in the console output
Example 8
Explanation
- This code defines an ATM class that simulates basic banking operations like creating/changing pins, checking balance, and withdrawing money
- The
__init__method is a constructor that initializes instance variablespinandbalance, and prints the object's memory address when created - The
menumethod displays a text-based interface for users to choose different ATM operations through input prompts - Each operation method (
create_pin,change_pin,check_balance,withdraw) handles specific user requests and validates PIN authentication before proceeding - The program runs continuously until user chooses to exit, with each method calling
self.menu()to return to the main menu after completing its task
Example 9
Explanation
- Creates a new instance of an ATM class called 'obj'
- Uses the Atm() constructor to initialize the object
- No parameters are passed to the constructor
- This object will have all methods and attributes defined in the Atm class
- The variable 'obj' now references this newly created ATM instance
Output
Example 10
Explanation
- The code calls the built-in
id()function to get the unique identity number of the objectobj - This identity number represents the object's memory address in Python's memory management system
- The
id()function returns an integer that uniquely identifies the object during its lifetime - The comment suggests that
selfandobjrefer to the same object instance, so they would have identical memory addresses - This demonstrates how Python objects are referenced by their memory location rather than by value or name
Output
Example 11
Explanation
- Creates two separate instances of an Atm class using the constructor
- Uses the built-in id() function to get the unique memory address identifier for each object
- Both objects are different instances even though they're of the same class
- Each object will have its own memory location and unique id value
- The print statements show different memory addresses confirming these are separate object instances
Output
Example 12
Explanation
- This code shows three attributes/operations that would typically be part of a bank account object
obj.pinandobj.balanceare likely instance variables storing the account PIN and current balanceobj.change_pin()is a method that would modify the account's PIN value- The code suggests an object-oriented approach where account details are encapsulated within a class
- This pattern allows for secure access and modification of account information through defined methods
Output
Example 13
Explanation
- This code demonstrates the difference between functions and methods in Python by showing two ways to operate on a list
len(L)is a function call that takes the list as an argument and returns its length, whileL.append(4)is a method call that modifies the list object directly- The key distinction is that functions are called independently with arguments, whereas methods are called on objects using dot notation
len()is a built-in function that works with any iterable, not just lists, whileappend()is a specific method available only on list objects- Both operations modify or provide information about the list, but they follow different syntax patterns for calling them
Example 14
Explanation
- Defines a class named
Tempwith an__init__method that prints 'hello' when called - Creates an instance of the
Tempclass by callingTemp()which triggers the__init__method - The
__init__method automatically executes when a new object is instantiated - Prints 'hello' to the console as the object is being created
- No return value or additional side effects beyond the print statement execution
Output
Example 15
Explanation
- Performs floating-point arithmetic multiplication of two fractions
- Uses Python's standard division operator
/to calculate 0.75 times 0.5 - Returns the result of the mathematical operation as a float value
- Expected output is
0.375which represents the product of the two fractions - No side effects or additional functions involved, purely mathematical computation
Output
Example 16
Explanation
- This code defines a Fraction class that represents mathematical fractions with numerator and denominator parts
- It uses magic methods like str, add, sub, mul, and truediv to enable natural syntax for printing and arithmetic operations on fraction objects
- The class supports basic fraction arithmetic including addition, subtraction, multiplication, and division using standard mathematical formulas
- The convert_to_decimal method provides a way to get the decimal representation of a fraction by dividing numerator by denominator
- When you create Fraction objects and use operators like +, -, *, /, the magic methods automatically handle the calculations and return formatted string results
Example 17
Explanation
- Creates a new Fraction object with default values (0/1)
- Uses the Fraction class constructor without any arguments
- Results in a fraction representing zero (0/1)
- No additional libraries or imports needed since Fraction is part of Python's fractions module
- The variable fr1 now holds a Fraction instance that can be used in mathematical operations
Output
Example 18
Explanation
- Creates two fraction objects using the Fraction class from the fractions module
fr1represents 1/2 andfr2represents 3/4- Both fractions are stored as immutable objects with numerator and denominator attributes
- No arithmetic operations are performed, so no calculations or comparisons occur
- These fraction objects can be used later in mathematical operations or comparisons
Example 19
Explanation
- Prints the contents of two variables
fr1andfr2to the console - Uses the
print()function to display the values stored in these variables - Likely shows data frames, lists, or other data structures depending on what
fr1andfr2contain - No return value or side effects beyond displaying output
- The
frprefix suggests these might be DataFrame objects from pandas library
Output
Example 20
Explanation
- Performs arithmetic operations (addition, subtraction, multiplication, division) between two fraction objects fr1 and fr2
- Calls convert_to_decimal() method on both fractions to display their decimal representations
- Uses Python's built-in operator overloading for fraction arithmetic operations
- Prints the results of all mathematical operations and decimal conversions to console
- Side effect is displaying computed values including fraction results and their decimal equivalents
Output
Example 21
Explanation
- Creates a Fraction object with numerator 5 and denominator 6 using the Fraction class
- The print function displays the fraction in its simplest form as "5/6"
- Uses the Fraction API from the fractions module to represent rational numbers exactly
- No mathematical simplification occurs since 5 and 6 share no common factors
- Output shows the fraction displayed in standard mathematical notation
Output
Example 22
Explanation
- Combines three variables (fr1, fr2, fr3) using the + operator, likely concatenating strings or adding pandas DataFrames
- Uses the print() function to display the combined result to the console output
- The fr1, fr2, fr3 variables appear to contain data that can be added together, possibly string values or numeric data structures
- This operation will produce a single combined output that prints all three values sequentially
- The exact behavior depends on the data types of fr1, fr2, and fr3 - they must support the + operator for the operation to work
Output
Example 23
Explanation
- This code defines a Fraction class that represents mathematical fractions with numerator and denominator parts
- It implements magic methods (str, add, sub, mul, truediv) to enable natural syntax for fraction arithmetic operations like addition, subtraction, multiplication, and division
- The class uses parameterized constructor to initialize fraction objects and includes a helper method to convert fractions to decimal values
- When printing a fraction object, it displays the format "numerator/denominator" using the str magic method
- The arithmetic operations create new Fraction objects with properly calculated numerators and denominators without modifying the original fractions
Example 24
Explanation
- Creates three Fraction objects with values 1/2, 3/4, and 5/6 using the Fraction class
- Adds all three fractions together using the + operator, which automatically finds common denominators
- The print statement outputs the simplified result of the addition
- Uses the Fraction class from the fractions module for precise rational number arithmetic
- Expected output is 13/4 or 3.25 when printed as a fraction
Output
Example 25
Explanation
- Creates four
Fractionobjects representing the fractions 1/2, 3/4, 5/6, and 4/5. - Uses the
Fractionclass from thefractionsmodule to handle rational number arithmetic. - Adds the four fractions together using the
+operator, which automatically simplifies the result. - The
printfunction outputs the sum of the fractions as a simplifiedFractionobject.
Output
##Q-1: Rectangle Class
-
Write a Rectangle class in Python language, allowing you to build a rectangle with length and width attributes.
-
Create a Perimeter() method to calculate the perimeter of the rectangle and a Area() method to calculate the area of the rectangle.
-
Create a method display() that display the length, width, perimeter and area of an object created using an instantiation on rectangle class.
Eg. After making above classes and methods, on executing below code:-
Output:
Example 26
Explanation
- Defines a
Rectangleclass with private attributes for length and width, initialized via the constructor. - Contains private methods
__perimeterand__areato calculate the perimeter and area of the rectangle, respectively. - The
displaymethod prints the length, width, perimeter, and area of the rectangle. - An instance of
Rectangleis created with length 4 and width 5, and thedisplaymethod is called to output the dimensions and calculated values. - Expected output includes the length, width, perimeter (18), and area (20) of the rectangle.
Output
##Q-2: Bank Class
- Create a Python class called
BankAccountwhich represents a bank account, having as attributes:accountNumber(numeric type),name(name of the account owner as string type),balance. - Create a constructor with parameters:
accountNumber, name, balance. - Create a
Deposit()method which manages the deposit actions. - Create a
Withdrawal()method which manages withdrawals actions. - Create an
bankFees()method to apply the bank fees with a percentage of 5% of the balance account. - Create a
display()method to display account details. Give the complete code for the BankAccount class.
Eg. After making above classes and methods, on executing below code:-
Output:
Example 27
Explanation
- Defines a
Bankclass to manage a bank account with attributes for name, account number, and balance. - The
__init__method initializes the account details and uses private variables to encapsulate data. - The
displaymethod prints the account number, name, and balance in a formatted manner. - The
depositmethod increases the account balance by a specified amount. - The
withdrawlmethod checks for sufficient funds, deducts the withdrawal amount, and applies a bank fee before updating the balance.
Output
##Q-3:Computation class
-
Create a
Computationclass with a default constructor (without parameters) allowing to perform various calculations on integers numbers. -
Create a method called
Factorial()which allows to calculate the factorial of an integer n. Integer n as parameter for this method -
Create a method called
naturalSum()allowing to calculate the sum of the first n integers 1 + 2 + 3 + .. + n. Integer n as parameter for this method. -
Create a method called
testPrime()in the Calculation class to test the primality of a given integer n, n is Prime or Not? Integer n as parameter for this method. -
Create a method called
testPrims()allowing to test if two numbers are prime between them. Two integers are prime to one another if they have only1as their common divisor. Eg. 4 and 9 are prime to each other. -
Create a
tableMult()method which creates and displays the multiplication table of a given integer. Then create anallTablesMult()method to display all the integer multiplication tables 1, 2, 3, ..., 9. -
Create a static
listDiv()method that gets all the divisors of a given integer on new list called Ldiv. Create another method that gets all the prime divisors of a given integer.
Example 28
Explanation
- Defines a
Computationclass with methods for various mathematical operations including factorial, natural sum, primality tests, multiplication tables, and finding divisors. - The
factorialmethod calculates the factorial of a given numbernusing a loop. - The
naturalSummethod computes the sum of the firstnnatural numbers. - The
testPrimemethod checks if a numbernis prime by counting its divisors. - The
testPrimsmethod determines if two numbers are co-prime by checking their common divisors and prints the result.
Output
##Q-4: Build flashcard using class in Python.
Build a flashcard using class in python. A flashcard is a card having information on both sides, which can be used as an aid in memoization. Flashcards usually have a question on one side and an answer on the other.
Example 1:
Approach:
- Create a class named FlashCard.
- Initialize dictionary fruits using init() method. Here you have to define fruit name as key and it's color as value. E.g., {"Banana": "yellow", "Strawberries": "pink"}
- Now randomly choose a pair from fruits by using random module and store the key in variable fruit and value in variable color.
- Now prompt the user to answer the color of the randomly chosen fruit.
- If correct print correct else print wrong.
Output:
Example 29
Explanation
- Imports the
randommodule to facilitate random selection of fruit-color pairs. - Defines a
FlashCardclass with a private dictionary of fruits and their corresponding colors. - The
quizmethod repeatedly asks the user to identify the color of a randomly selected fruit and checks the user's answer. - Provides feedback on whether the user's answer is correct or incorrect and allows the user to continue or exit the quiz.
- The expected output includes prompts for user input and feedback messages based on the user's responses.
Output
Q-5: Problem 5 based on OOP Python.
TechWorld, a technology training center, wants to allocate courses for instructors. An instructor is identified by name, technology skills, experience and average feedback. An instructor is allocated a course, if he/she satisfies the below two conditions:
- eligibility criteria:
- if experience is more than 3 years, average feedback should be 4.5 or more
- if experience is 3 years or less, average feedback should be 4 or more
- he/she should posses the technology skill for the course
Identify the class name and attributes to represent instructors. Write a Python program to implement the class chosen with its attributes and methods.
Note:
- Consider all instance variables to be private and methods to be public.
- An instructor may have multiple technology skills, so consider instance variable, technology_skill to be a list.
- check_eligibility(): Return true if eligibility criteria is satisfied by the instructor. Else, return false
- allocate_course(technology): Return true if the course which requires the given technology can be allocated to the instructor. Else, return false.
Represent a few objects of the class, initialize instance variables using setter methods, invoke appropriate methods and test your program.
Example 30
Explanation
- Defines an
Instructorclass with attributes for name, technology expertise, experience, and feedback score. - The
check_eligibilitymethod evaluates if the instructor is eligible based on experience and feedback criteria. - The
allocate_coursemethod checks if the instructor is eligible and if they can learn a specified technology. - An instance of
Instructoris created with specific attributes, and theallocate_coursemethod is called with 'Data Science' as the argument. - The expected output is 'He/She can learn' since the instructor meets the eligibility criteria and has expertise in 'Data Science'.
Output

