Python Topics



Mutable vs Immutable Objects in Python

In Python, everything is an object. Every variable in python holds an instance of an object. There are two types of objects in python i.e. Mutable and Immutable objects. Whenever an object is instantiated, it is assigned a unique object id. The type of the object is defined at the runtime. An object whose internal state can be changed is mutable. On the other hand, immutable doesn’t allow any change in the object once it has been created.
  
built-in mutable Objects are:

    Lists
    Sets
    Dictionaries

built-in immutable Objects are:

    Numbers (Integer, Float, Complex & Booleans)
    Strings
    Tuples

Examples of mutable Objects

# lists are mutable fruits = ["apple", "mango", "grapes"] print(fruits) fruits[0] = "watermeleon" fruits[-1] = "bananna" print(fruits) Output: ["apple", "mango", "grapes"] ["watermeleon", "mango", "bananna"]

Examples of immutable Objects

a=111 print("a before change is",a) print("the id of a before change is",id(a)) a=222 print("a after change is",a) print("the id of a after change is",id(a)) Output: a before change is 111 the id of a before change is 9796768 a after change is 222 the id of a after change is 140032307887024 #Example 2 a = "Hello, World!" a[0]='a' print(a) Output: Traceback (most recent call last): File "./prog.py", line 2, in TypeError: 'str' object does not support item assignment #Example 3 # tuples are immutable a = (0, 1, 2, 3) a[0]=8 print(a) Output: Traceback (most recent call last): File "./prog.py", line 2, in TypeError: 'tuple' object does not support item assignment


Write a Python program to read a word and print the number of letters, vowels and percentage of vowels in the word using a dictionary
vowels = 'aeiou'

ip_str = 'Hello,  welcome to python programming'

# casefold converts upper case to lowercase
ip_str = ip_str.casefold()

# make a dictionary with each vowel a key and value 0
count = {}.fromkeys(vowels,0)

# count the vowels
for char in ip_str:
   if char in count:
       count[char] += 1

print(count)


write a python program to find the largest word in a file. get the filename from the user
  def longest_words(filename):
    with open(filename, 'r') as infile:
        words = infile.read().split()
    return(max(words, key=len))
   
a=input("enter filename")
print(longest_words(a))



6. develop a python program to search the string 'laptop' in "sales.txt" file and print its line along with the line number.
 
def search_str(file_path, word):
    with open(file_path, 'r') as file:
        c=0
        # read all content of a file
        x = len(file.readlines())
        print('Total lines:', x)
        file.seek(0,0)
        for index in range(x):
            line = next(file)
            if word in line:
                print("string exist in a file at Line No %d - %s" % (index, line))
                c+=1
        if(c==0):
            print("string doesnot exist in a file")
search_str(r'123.txt', 'laptop')

def search_str(word): file=open("123.txt", 'r') c=0 x = len(file.readlines()) print('Total lines:', x) file.seek(0,0) for index in range(x): line = next(file) if word in line: print("string exist in a file at Line No %d - %s" % (index, line)) c+=1 if(c==0): print("string doesnot exist in a file") search_str('sandeep')



Operator Overloading in Python

Consider that we have two objects which are a physical representation of a class (user-defined data type) and we have to add two objects with binary ‘+’ operator it throws an error, because compiler don’t know how to add two objects. So we define a method for an operator and that process is called operator overloading. We can overload all existing operators but we can’t create a new operator. To perform operator overloading, Python provides some special function or magic function that is automatically invoked when it is associated with that particular operator. For example, when we use + operator, the magic method __add__ is automatically invoked in which the operation for + operator is defined.
  
# Python Program illustrate how
# to overload an binary + operator

class A:
	def __init__(self, a):
		self.a = a

	# adding two objects
	def __add__(self, x):
		return self.a + x.a
ob1 = A(1)
ob2 = A(2)
ob3 = A("Hello")
ob4 = A("World")

print(ob1 + ob2)
print(ob3 + ob4)

  
# Python program to overload
# a comparison operators

class A:
	def __init__(self, a):
		self.a = a
	def __gt__(self, other):
		if(self.a>other.a):
			return True
		else:
			return False
ob1 = A(2)
ob2 = A(3)
if(ob1>ob2):
	print("ob1 is greater than ob2")
else:
	print("ob2 is greater than ob1")

Binary Operators
Operator	Magic Method
+	__add__(self, other)
–	__sub__(self, other)
*	__mul__(self, other)
/	__truediv__(self, other)
//	__floordiv__(self, other)
%	__mod__(self, other)
**	__pow__(self, other)
>>	__rshift__(self, other)
<<	__lshift__(self, other)
&	__and__(self, other)
|	__or__(self, other)
^	__xor__(self, other)

Comparison Operators :
Operator	Magic Method
<	__lt__(self, other)
>	__gt__(self, other)
<=	__le__(self, other)
>=	__ge__(self, other)
==	__eq__(self, other)
!=	__ne__(self, other)

Assignment Operators :
Operator	Magic Method
-=	__isub__(self, other)
+=	__iadd__(self, other)
*=	__imul__(self, other)
/=	__idiv__(self, other)
//=	__ifloordiv__(self, other)
%=	__imod__(self, other)
**=	__ipow__(self, other)
>>=	__irshift__(self, other)
<<=	__ilshift__(self, other)
&=	__iand__(self, other)
|=	__ior__(self, other)
^=	__ixor__(self, other)


 from tkinter import*
import webbrowser
win = Tk()
win.geometry("700x350")

def callback(event):
    webbrowser.open('https://kottesandeep.blogspot.com/',new=0, autoraise=True)
   
lbl = tk.Label(win, text=r"https://kottesandeep.blogspot.com/", fg="blue", cursor="hand2")
lbl.pack()
lbl.bind("<Button-1>", callback)
win.mainloop()

18 comments:

  1. Nice Blog Thanks for sharing this post with a lot of useful information. I would like to get updates from you. Keep blogging..
    Information Technology

    ReplyDelete
  2. I think this is one of the best blog for me because this is really helpful for me. Thanks for sharing this valuable information for free

    JTAG

    ReplyDelete
  3. I think this is one of the best blog for me because this is really helpful for me. Thanks for sharing this valuable information for free

    JTAG

    ReplyDelete
  4. I think this is one of the best blog for me because this is really helpful for me. Thanks for sharing this valuable information for free

    JTAG

    ReplyDelete
  5. I think this is one of the best blog for me because this is really helpful for me. Thanks for sharing this valuable information for free

    JTAG

    ReplyDelete
  6. I think this is one of the best blog for me because this is really helpful for me. Thanks for sharing this valuable information for free

    JTAG

    ReplyDelete
  7. I think this is one of the best blog for me because this is really helpful for me. Thanks for sharing this valuable information for free

    JTAG

    ReplyDelete
  8. Keep sharing such a valuable information. Thanks..

    Information Technology

    ReplyDelete
  9. Great article, I hope that you will going to post another one.

    Information Technology

    ReplyDelete
  10. Great article, I hope that you will going to post another one.

    Information Technology

    ReplyDelete
  11. Great article, I hope that you will going to post another one.

    Information Technology

    ReplyDelete
  12. Great article, I hope that you will going to post another one.

    Information Technology

    ReplyDelete
  13. Great article, I hope that you will going to post another one.

    Information Technology

    ReplyDelete