3. Problem to create a Python class with instance method

In this Python oops program, we will create a Python class with instance method. The program creates a class with a constructor and methods to display and update the name attribute of an object. It creates an object, displays its initial name, updates the name, and then displays the updated name.

Python class with instance method

Steps to solve the program
  1. The code demonstrates how to create a Python class with instance method and variables for updating and displaying the value of an attribute.
  2. The constructor method __init__() is used to initialize the name instance variable when an object is created.
    The display_name() method allows us to print the value of the name instance variable.
  3. The update_name() method provides a way to update the value of the name instance variable by passing a new name as a parameter.
  4. By combining these methods, we can create objects of the MyClass class, set and update the name attribute, and display the updated name whenever needed. In the example, the name is initially set to “Omkar” and then updated to “Ketan”.
				
					class MyClass:
    def __init__(self, name):
        self.name = name
    
    def display_name(self):
        print("Name:", self.name)
    
    def update_name(self, new_name):
        self.name = new_name

# Create an object of the class
obj = MyClass("Omkar")
obj.display_name()

obj.update_name("Ketan")
obj.display_name()
				
			

Output:

				
					Name: Omkar
Name: Ketan
				
			

Related Articles

create a class with an instance variable.

create a class with class variables.

2. Problem to create a Python class with instance variables

In this Python oops program, we will create a Python class with instance variables. The program creates a class with a constructor that initializes an instance variable and then creates an object of that class to access and print the value of the instance variable.

Python class with instance variables.

Steps to solve the program
  1. The code demonstrates the usage of an instance variable within a class in Python.
  2. An instance variable is a variable that is specific to each instance (object) of a class. In this case, the instance_var instance variable is created within the constructor method __init__().
  3. When an object of the MyClass class is created, the constructor is called, and the instance_var instance variable is initialized with a value of 25.
  4. By accessing obj.instance_var, we can retrieve and print the value of the instance_var instance variable for the obj object, which will output 25 in this case.
  5. Instance variables provide a way to store and access data that is unique to each instance of a class.

				
					class MyClass:
    def __init__(self):
        self.instance_var = 25

# Create an object of the class
obj = MyClass()
print(obj.instance_var)
				
			

Output:

				
					25
				
			

Related Articles

create a class with the constructor.

create a class with Instance methods.

1. Problem to create a Python class constructor program

In this Python oops program, we will create a Python class constructor program. We will create a class in Python using a constructor with the help of the below-given steps.

Python class constructor

Steps to solve the program
  1. The code demonstrates the creation of a class MyClass and the usage of its constructor method and a simple instance method.
  2. The constructor method __init__() is used to initialize the object’s state. In this case, it takes a name parameter and assigns it to the instance variable self.name.
    The display_name() method provides a way to access and display the value of the name instance variable. It is called on an object of the class and prints the name to the console.
  3. By using classes, objects, and methods, we can create reusable and organized code structures in Python. In this example, the MyClass class allows us to create objects with a name attribute and display that name whenever needed.

				
					class MyClass:
    def __init__(self, name):
        self.name = name
    
    def display_name(self):
        print("Name:", self.name)

# Create an object of the class
obj = MyClass("Omkar")
obj.display_name()
				
			

Output:

				
					Name: Omkar
				
			

Related Articles

create a class with an instance variable.

Python MCQ Questions (Multiple Choice Quizz)

1. Python Variable Tutorial: A Comprehensive Guide

Python Variable:

Introduction:
Variables are an important concept in any programming language, including Python. In simple language, a variable is a named location in memory that stores a value. In Python, you can use variables to store any type of data, including numbers, strings, and even complex data structures like lists and dictionaries.

Creating Variables in Python:

To create a variable in Python, you need to give it a name and assign a value to it. Here’s an example:
Name = “ Omkar “
Age = 25
Profession = “Software Engineer “
In the example above, we created three variables: Name, Age, and Profession.
The name variable is a string.
The age variable is an integer.
The Profession variable is also a string.

 

Python Variable Naming Rules:

When creating variables in Python, there are a few rules that you need to follow:
1. Variable names must start with a letter or underscore (_), followed by any combination of letters, digits, and underscores.
2. Variable names are case-sensitive, which means name and Name are two different variables.
3. A variable name cannot start with a number.
4. A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ).

Python Variable Types:

Python Variable types:
1. Numbers – Consists of integers, floating-point numbers, and complex numbers.
2. Strings – Consists of characters in quotes.
3. Booleans – Consists of True or False values.
4. Lists – Consists of ordered sequences of elements.
5. Tuples – Consists of ordered, immutable sequences of elements.
6. Sets – Consists of unordered collections of unique elements.
7. Dictionaries – Consists of unordered collections of key-value pairs.

Checking types of the variable:
First, we will create some Python variable.
Name = “ Omkar “
Age = 25
Height = 5.8 ft

To check the type of the variable use the type() function.
print(type(Name)) #Output: <class ‘str’>
print(type(Age)) #Output: <class ‘int’>
print(type(Height)) #Output: <class ‘float’>

Python variable assignment types:

Value Assignment:

To assign the value to a Python variable use equal sign ( = ).
Example:
A = 10
We can also assign the same value to multiple Python variables.
A = B = C = 10

Multiple value assignment:

We can assign different values to different Python variables at the same time. We separate the variables and their values by ‘ , ‘.
Example:
a, b, c = 40, 50, 60
Here,
Value of variable a is 40 , b is 50 and c is 60.

Python Variable scope:

Scope of Variable:

In Python, the scope of a variable determines where in the code the variable can be accessed and used. The scope of a variable is defined by where the variable is created and assigned a value.
There are two types of Python variable scopes: global scope and local scope.

1. Global Scope: Variables created outside of any function or class have a global scope. This means that they can be accessed and modified from anywhere in the code, including within functions and classes.
Example:
number = 100 # global Python variable

def print_number():
print(number) # accessing global variable

def modify_number():
global number # declaring number as global variable
number = 200 # modifying global variable

print_number() # Output: 100
modify_number()
print_number() # Output: 200
In the example above, the variable number is declared outside of any function, so it has a global scope. The function print_number() can access and print the value of the number, and the function modify_number() can modify the value of the number by declaring it as a global variable using the global keyword.

2. Local Scope: Variables created inside a function or class have a local scope. This means that they can only be accessed and modified within that function or class.
Example:
def my_function():
number = 100 # local Python variable
print(number) # accessing local variable

my_function() # Output: 100
print(number) # NameError: name ‘number’ is not defined

Basic Mathematical operations using variables:

Creating variables and assigning value to them:
a, b = 10 , 20

Performing operations and printing output:
print(a+b) #Output: 30
print(a-b) #Output: -10
print(a*b) #Output: 200
print(a/b) #Output: 0.5

Variables are an important concept in Python programming language. They allow you to store and manipulate data in your code and are important for writing effective programs. By understanding how to create, name, and use variables, you can write Python code that is easy to read and maintain.

Python OOPS Programs, Exercises

Python OOPS Programs help beginners to get expertise in Object-Oriented Programming (OOP). Python programming paradigm that focuses on creating objects that encapsulate data and behavior. Python is an object-oriented programming language, which means it supports OOP concepts such as inheritance, polymorphism, encapsulation, and abstraction.

Python OOPS Programs for Practice

1). Python oops program to create a class with the constructor.

2). Python oops program to create a class with an instance variable.

3). Python oops program to create a class with Instance methods.

4). Python oops program to create a class with class variables.

5). Python oops program to create a class with a static method.

6). Python oops program to create a class with the class method.

7). Write a Python Class to get the class name and module name.

8) Write a Python Class object under syntax if __name__ == ‘__main__’.

9). Python class with Single Inheritance.

10). Python Class with Multiple Inheritance.

11). Python Class with Multilevel Inheritance.

12). Python Class with Hierarchical Inheritance.

13). Python Class with Method Overloading.

14). Python Class with Method Overriding.

15). Write a Python Class Program with an Abstract method.

16). Write a Python Class program to create a class with data hiding.

17). Python Class Structure for School Management System.

18). Write a Python Class Structure for Employee Management Application.

19). Write a Python Class with @property decorator.

20). Write a Python Class structure with module-level Import.

21). Create 5 different Python Classes and access them via a single class object.

22). Create 5 Python classes and set up multilevel inheritance among all the classes.

23). Set Instance variable data with setattr and getattr methods.

24). Python oops program with encapsulation.

25). Create a Python class called Rectangle with attributes length and width. Include methods to calculate the area and perimeter of the rectangle.

26). Create a Python class called Circle with attributes radius.
Include methods to calculate the area and circumference of the circle.

27). Create a Python class called Person with attributes name and age. Include a method to print the person’s name and age.

28). Create a Python class called Student that inherits from the Person class.
Add attributes student_id and grades. Include a method to print the student’s name, age, and student ID.

29). Create a Python class called Cat that inherits from the Animal class.
Add attributes breed and weight. Include a method to print the cat’s name, color, breed, and weight.

30). Create a Python class called BankAccount with attributes account_number and balance. Include methods to deposit and withdraw money from the account.

31). Create a Python class called SavingsAccount that inherits from the BankAccount class. Add attributes interest_rate and minimum_balance. Include a method to calculate the interest on the account.

32). Create a Python class called CheckingAccount that inherits from the BankAccount class. Add attributes transaction_limit and transaction_fee. Include a method to check if a transaction is within the limit and deduct the fee if necessary.

33). Create a Python class called Car with attributes make, model, and year.
Include a method to print the car’s make, model, and year.

34). Create a Python class called ElectricCar that inherits from the Car class.
Add attributes battery_size and range_per_charge. Include a method to calculate the car’s range.

35). Create a Python class called StudentRecord with attributes name, age, and grades. Include methods to calculate the average grade and print the student’s name, age, and average grade.

36). Create a Python class called Course with attributes name, teacher, and students. Include methods to add and remove students from the course and print the course’s name, teacher, and list of students.

37). Create a Python class called Shape with a method to calculate the area of the shape. Create subclasses called Square and Triangle with methods to calculate their respective areas.

38). Create a Python class called Employee with attributes name and salary.
Include a method to print the employee’s name and salary.

39). Create a Python class called Manager that inherits from the Employee class.
Add attributes department and bonus. Include a method to calculate the manager’s total compensation.

40). Create a Python class called Customer with attributes name and balance.
Include methods to deposit and withdraw money from the customer’s account.

41). Create a Python class called VIPCustomer that inherits from the Customer class. Add attributes credit_limit and discount_rate. Include a method to calculate the customer’s available credit.

42). Create a Python class called Phone with attributes brand, model, and storage.  Include methods to make a call, send a text message, and check storage capacity.

43). Create a Python class called Laptop with attributes brand, model, and storage. Include methods to start up the laptop, shut down the laptop, and check storage capacity.

44). Create a Python class called Book with attributes title, author, and pages.
Include methods to get the book’s title, author, and number of pages.

45). Create a Python class called EBook that inherits from the Book class.
Add attributes file_size and format. Include methods to open and close the book.

46). Create a Python class called ShoppingCart with attributes items and total_cost. Include methods to add and remove items from the cart and calculate the total cost.

47). Create a Python class called Animal with attributes name and color.
Include a method to print the animal’s name and color.

48). Create a Python class called Dog that inherits from the Animal class.
Add attributes breed and weight. Include a method to print the dog’s name, color, breed, and weight.

Python program to find cartesian product of two sets.

Cartesian product of two sets, Let’s consider we have setA = {3, 5} and setB = {6, 7} then the Cartesian product of two sets will be {(3, 6), (3, 7), (5, 6), (5, 7)}

Cartesian product of two sets with Python

Steps to solve the program

1. Initiate two sets setA and setB.
2. Initiate a result set where we will add the combined value of setA and setB.
3. Apply a nested loop, the first loop will pick the value of setA and the second loop will value of setB.
4. Combine setA and setB values in the tuple and add them to the result set. 
5. Print result set.

				
					# initiate two sets setA and setB
setA = {1, 3}
setB = {2, 6, 7}
result = set()
# use nested loop to interate over setA and setB elements
for val1 in setA:
    for val2 in setB:
        # add combination setA value and setB value to result.
        result.add((val1, val2))
# print output
print(result)

				
			

Output :  Cartesian product of two sets values.

				
					{(1, 2), (3, 7), (1, 7), (3, 6), (1, 6), (3, 2)}
				
			

Related Articles

create two sets of books and find the intersection of sets.

51. Problem to find the longest word in a set

In this Python set program, we will find the longest word in a set from a set of words with the help of the below-given steps.

What is set?
Sets are used to store multiple items in a single variable.
The set is one of 4 built-in data types in Python used to store collections of data.
It is an unordered collection data type that is iterable, mutable and has no duplicate elements.

Longest word in a set:

Steps to solve the program

1. Take a set of words.
2. Create two variables to store the word having maximum length and longest word in a set.
3. Assign their values equal to 0.
4. Use a for loop to iterate over words from the set.
5. Use an if statement with the len() function to check whether the length of the word is greater than the max_len variable.
6. If yes then assign the length of that word to max_len variable and word to max_word variable.
7. Print both the variables after loop is finished to see the result.

				
					Set = {"I","am","Learning","Python"}
max_len = 0
max_word = 0
print("Original Set: ",Set)
for word in Set:
    if len(word)>max_len:
        max_len =len(word)
        max_word = word
print("Word having maximum length: ",max_word)
print("Length of the word: ",max_len)
				
			

Output :

				
					Original Set:  {'Learning', 'am', 'Python', 'I'}
Word having maximum length:  Learning
Length of the word:  8
				
			

Related Articles

create two sets of books and find the intersection of sets.

50. Problem to find intersection of sets

In this Python set program, we will find the intersection of sets i.e. common books between two sets with the help of the below-given steps.

What is set?
Sets are used to store multiple items in a single variable.
The set is one of 4 built-in data types in Python used to store collections of data.
It is an unordered collection data type that is iterable, mutable and has no duplicate elements.

Intersection of sets:

Steps to solve the program

1. Create two sets having books name in it.
2. Use a for loop to iterate over books in the first set.
3. Use an if statement to check whether the book is present in the second set i.e. intersection of sets.
4. If yes then print that book.

				
					Set1 = {"Lord of the Rings","Harry Potter and the Sorcerer's Stone","The Magic Tree","Tower To The Stars"}
Set2 = {"Wizards of Ice","Call of the Forest","Lord of the Rings"}
print("Original Set1: ",Set1)
print("Original Set2: ",Set2)
print("Common books: ")
for book_name in Set1:
    if book_name in Set2:
        print(book_name)
				
			

Output :

				
					Original Set1:  {'Lord of the Rings', 'Tower To The Stars', "Harry Potter and the Sorcerer's Stone", 'The Magic Tree'}
Original Set2:  {'Lord of the Rings', 'Call of the Forest', 'Wizards of Ice'}
Common books: 
Lord of the Rings
				
			

Related Articles

create a set of your favorite movies.

find the longest word in a set.

49. Problem to create a set of favorite movies

In this Python set program, we will create a set of favorite movies with the help of the below-given steps.

What is set?
Sets are used to store multiple items in a single variable.
The set is one of 4 built-in data types in Python used to store collections of data.
It is an unordered collection data type that is iterable, mutable and has no duplicate elements.

Set of favorite movies:

Steps to solve the program

1. Create a set using {}.
2. Add name of your favorite movies in the set.
3. Print the set to see the output.

				
					Set = {"Avengers: Endgame","John wick","The Matrix"}
print("Set of movies: ",Set)
				
			

Output :

				
					Set of movies:  {'John wick', 'The Matrix', 'Avengers: Endgame'}
				
			

Related Articles

create a set of your favorite actors.

create two sets of books and find the intersection of sets.