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.

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.

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.

48. Problem to create a set of favorite actors

In this Python set program, we will create a set of favorite actors 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 actors:

Steps to solve the program

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

				
					Set = {"Shan Rukh Khan","Akshay Kumar","Tom Hardy","Robert Pattinson"}
print("Set of actors: ",Set)
				
			

Output :

				
					Set of actors:  {'Shan Rukh Khan', 'Akshay Kumar', 'Robert Pattinson', 'Tom Hardy'}
				
			

Related Articles

create a set of odd numbers from 1 to 20.

create a set of your favorite movies.

47. Problem to create a set of odd numbers

In this Python set program, we will create a set of odd numbers from 1 to 20 with the help of the below-given steps.

Odd number:
Odd numbers are those numbers that cannot be divided into two equal parts.

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 odd numbers:

Steps to solve the program

1. Create a set using the set() function.
2. Use a for loop to iterate over numbers from 1 to 20.
3. Use an if statement to check whether the number is a odd number or not.
4. If yes then add it to the set using the add() function.
5. Print the set to see the output.

				
					Set = set()
for num in range(1,21):
    if num%2 != 0:
        Set.add(num)
print("Set of odd number: ",Set)
				
			

Output :

				
					Set of odd number:  {1, 3, 5, 7, 9, 11, 13, 15, 17, 19}
				
			

Related Articles

create a set of even numbers from 1 to 20.

create a set of your favorite actors.

46. Problem to create a set of even numbers

In this Python set program, we will create a set of even numbers from 1 to 20 with the help of the below-given steps.

Even number:
even numbers are those numbers that can be divided into two equal parts.

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 even numbers:

Steps to solve the program

1. Create a set using the set() function.
2. Use a for loop to iterate over numbers from 1 to 20.
3. Use an if statement to check whether the number is a even number or not.
4. If yes then add it to the set using the add() function.
5. Print the set to see the output.

				
					Set = set()
for num in range(1,21):
    if num%2 == 0:
        Set.add(num)
print("Set of even number: ",Set)
				
			

Output :

				
					Set of even number:  {2, 4, 6, 8, 10, 12, 14, 16, 18, 20}
				
			

Related Articles

convert a set to a dictionary with each element as key and value to an empty set.

create a set of odd numbers from 1 to 20.

45. Problem to convert set to dictionary with the help of Python

In this Python set program, we will convert set to dictionary 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.

Convert set to dictionary:

Steps to solve the program

1. Create a set using {}.
2. Add some elements in the set.
3. Create an empty dictionary.
4. Use a for loop to iterate over elements in the set.
5. During iteration add the element as key and an empty set ({}) as its value to the dictionary.
6. Print the dictionary.

				
					a = {1,2,4,6}
print("Original set: ",Set)
Dict = {}
for ele in a:
    Dict[ele] = {}
print("Dictionary: ",Dict)
				
			

Output :

				
					Original set:  {1, 2, 4, 6}
Dictionary:  {1: {}, 2: {}, 4: {}, 6: {}}
				
			

Related Articles

find the index of an element in a set.

create a set of even numbers from 1 to 20.