MNNIT CC 2021-22 Classes

Python Class - II

Python Class - II recording: Here

May 08, 2021

python

Taking input from terminal

a = input("Enter you name:")
print("Hello",a)

a = input("Enter a number.")
print(a, type(a))

a = int(input("Enter a number"))
b = int(input("Enter another number"))
print("Sum of both the numbers is: ", a+b)

Functions (continued)

#keyword argument
def func(n, m):
    print("n = " + str(n))
    print("m = " + str(m))

func(5, 10)
print('\n')

# We can mess with the default order of arguments while calling the funciton if we use keyword arguments
func(m=5, n=10) 
n = 5
m = 10


n = 10
m = 5

Recursion (factorial)

def factorial(num):
    if num == 1:      #base case
        return 1
    return num * factorial(num - 1)

print(factorial(5))
120

args and kwargs

# variable no. of arguments (*args)
def func(*args):
    # args is tuple with the argument
    for i in args:
        print(i)
func('hello', 'to', 'python', 'class', 'for', 'first', 'years')

print()

def my_print(*not_necessarily_args):
    for i in not_necessarily_args:
        print(i)
        
my_print('hello', 'my', 'name', 'is', 'bin'+'bash')
hello
to
python
class
for
first
years

hello
my
name
is
binbash
# variable no. of keyword arguments (**kwargs)
def func(**kwargs):
    for key, values in kwargs.items():
        print(key, values)

func(hello='to', python='class', year='first')

print("-"*40)

def kw_args_func(**not_necessarily_kwargs):
    for key, value in not_necessarily_kwargs.items():
        print('key:', key, ' ', 'value:', value)
        
kw_args_func(sep='/', end='*', name='bin')
hello to
python class
year first
----------------------------------------
key: sep   value: /
key: end   value: *
key: name   value: bin
# This will give a error
def ff(*args, **kwargs, name):
    for arg in args:
        print(args)
    for key,value in kwargs.items():
        print(key, ": ", value)
    print("Name: ", name)
    
ff(10, "Hello", ran=20, "Foo Bar")
  File "<ipython-input-39-938320840b18>", line 2
    def ff(*args, **kwargs, name):
                               ^
SyntaxError: invalid syntax

Lambda Function

lambda arguments: expression

# Program to show the use of lambda functions

double = lambda x: x * 2

# Output: 10
print(double(5))
10
# Program to filter out only the even items from a list using filter()

my_list = [1, 5, 4, 6, 8, 11, 3, 12]

new_list = list(filter(lambda x: (x%2 == 0) , my_list))

# Output: [4, 6, 8, 12]
print(new_list)
[4, 6, 8, 12]
# Program to double each item in a list using map()

my_list = [1, 5, 4, 6, 8, 11, 3, 12]

new_list = list(map(lambda x: x * 2 , my_list))

# Output: [2, 10, 8, 12, 16, 22, 6, 24]
print(new_list)
[2, 10, 8, 12, 16, 22, 6, 24]


Modules and Packages in Python


import and from keywords

# Program to generate a random number between 0 and 9
# importing the random module
import random

print(random.randint(0,9))


Classes and Instances


	### Minimal Example Class
	class Car:
		pass

	c1 = Car()

	c1.name = "Model 3"
	c1.company = "Tesla"

	print(c1)
	print(c1.name)
	print(c1.company)
	class Car:
  		def __init__(self, car_model, car_company, car_color):
			# Initialising Propertis Specific to the object.
			self.model = car_model
			self.company = car_company
			self.color = car_color
		
		def get_color(self):
			# Instance Method
			return self.color

		def set_color(self, new_color):
			# Instance Method
			self.color = new_color

	# Instantiating an Object or Creating an Object
	my_car = Car("Model S", "Tesla", "Maroon") # my_car is an instance/object of Car Class.

Instance Variables and Class Variables

class Car:
	wheels = 4 # Class Variable/attribute
	def _init_(self, company): # Constructor method
		self.company = company

	def get_company(self): # Instance Method
		return self.company
 
	def get_wheels(self): # Instance methods
		return Car.wheels

my_car = Car("Tesla")
my_car = Car("Tesla")
print(my_car._dict_) # Print the Properties associated with an object as a dictionary

print(my_car.get_company()) # Actually Treated as:- print(Car.get_company(my_car))
print(my_car.get_wheels())

Three Types of methods defined inside a Class.

1. Instance Methods/Regular Methods:

2. Class Methods:

### Car Class Example
class Car:
	wheels = 4 # Class Variable/attribute
	def _init_(self, company): # Constructor method
		self.company = company

	def get_company(self): # Instance Method
		return self.company
 
	def get_wheels(self): # Instance methods
		return Car.wheels

	@classmethod
	def about(cls): # Class Method
		return "This is the Blue-Print of a Car having " + str(cls.wheels) + " wheels."
print(Car.about()) 
# You can call a class-method using an instance but as an instance never stores a classmethod. So, Car.about() is called.
print(my_car.about()) 

3. Static Methods:

# Static Methods
class Car:
	wheels = 4 # Class Variable/attribute
	def _init_(self, company):
		print(self)
		self.company = company

	def get_company(self): # Instance Method
		return self.company
 
	def get_wheels(self): # Instance methods
		return Car.wheels

	@classmethod
	def about(cls):
		return "This is the Blue-Print of a Car having " + str(cls.wheels) + " wheels."

	@staticmethod
	def calculate_fuel_amount(cost_per_litre, amount_paid):
		# A uitility Function.
		return amount_paid/cost_per_litre


my_car = Car("Tesla")
fuel_amount = Car.calculate_fuel_amount(90, 900)
# fuel_amount = my_car.calculate_fuel_amount(90, 900)
print(fuel_amount, "Litres")

File Handling

In this, we will talk about files that store data.

There are two types of data files:

File Object/Handle

File Object Attributes

Attribute Description
file.closed Returns true if file is closed, false otherwise.
file.mode Returns access mode with which file was opened.
file.name Returns name of the file.

Opening Files

To open a file in our program we have a function named open().

  <file_objectname> = open(<filename>)
  <file_objectname> = open(<filename>, <mode>)
    a = open("myFile.txt", "r") # File Opened in read mode
    b = open("list.txt", "w") # File opened in the write mode

File Access Modes

Text Files Binary Files Function Description
‘r’ ‘rb’ read File must exist, else error
‘w’ ‘wb’ write If file exist overwrite, else create new file
‘r+’ ‘r+b’ or ‘rb+’ read and write File must exist, else error. Both read and write works
‘w+’ ‘w+b’ or ‘wb+’ write and read If file exist overwrite, else not create new file. Both read and write works
‘a’ ‘ab’ append Same as ‘write’, data is not overwritten. It’s appended.
‘a+’ ‘a+b’ or ‘ab+’ append and read Same as ‘write’ data is not overwritten. It’s appended. Both read and write works

Reading a file

f = open("list.txt") # file is opened
result = f.read()
print(result) # will print the whole file.
result = f.read(10)
print(result) # will print only the first 10 bytes i.e 10 characters of the file.
  f = open("list.txt") # file is opened
  result = f.readline()
  print(result) # will print the first line
  result = f.realine(3)
  print(result) # will print first 3 characters of second line.
  result = f.readline()
  print(result) # will print the remaining part of second line.
  f = open("list.txt")
  result = f.readlines()
  print(result) # will print list of lines

There’s an alternate way to read line by line

  f = open("list.txt)
  for i in f:
    print(i) # i iterates till "\n", which was the delimiter.
  
  # It's same as:
  s = f.readline()
  while s:
    print(s)
    s = f.readline()
with open("file.txt", 'w') as f:
  f.write("Hello World!!)

What’s special about the with keyword?

When you open a file python creates an file object i.e some memory has been allocated to the file object if we forgot to clean this memory it can cause memory leak (we clean this memory by calling close() method i.e f.close()). But in case of with keyword when the code comes out the block scope of the with keyword it will automatically close the file object i.e clean the memory which was allocated to the file

Writing in a file

  1. The write() function:

writes string in the file associated with file object.

  f = open("list.txt", 'w')
  f.write("Hello World!")
  1. The writelines() function:

writes all string from the list in the file associated with file object.

  f = open("list.txt", 'w')
  todo = ["Coding", "Binge Watching", "Football"]
  f.writelines(todo)

File Pointers

A file pointer tells the current position in the file where reading or writing will take place.

Exception Handling

What is Exception?

Exception Handling

try:
   # Runs first
   < code >
except:
  # If there is exception, then execute this block.
   < code >
else:
  # If there is no exception then execute this block.
  <code>
finally:
  # This code always executes
  < code >
def divide(a,b):
	try:
		ans = a / b
	except ZeroDivisionError:
		print("Trying to divide by zero")
		ans = float("Inf")
	finally:
		print("Division successful")
	return ans

Content Contributors

Materials