Rapti Lab Report Python(Nagendra)
Rapti Lab Report Python(Nagendra)
Lab Report
On
Subject: Python
Lab Report : #1
Title: Python Programming
Shell
The Python Shell gives you a command line interface you can use
to specify commands directly to the Python interpreter in an
interactive manner.
To start the Python shell, type ‘python’ and hit Enter in the
terminal:
Eg. PS C:\Python\pythonprogram> python
Python 3.13.0 (tags/v3.13.0:60403a5, Oct 7 2024, 09:38:07) [MSC v.1941
64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
Executing Shell Commands with Python using the os module
The os module in Python includes functionality to communicate
with the operating system.
using the system() method to execute shell commands
of echo.
import os
os.system('echo "I am learning python"')
we are using the system() method to execute the ‘pwd’ shell
script using Python.
import os
os.system('pwd')
print('Hello, world!')
List
Lists are used to store multiple items in a single variable.
We can add elements to a list using the following methods:
append(): Adds an element at the end of the list.
Extend(): Adds multiple elements to the end of the list.
Insert(): Adds an element at a specific position.
Example:
a = []
a.append(10)
Example:
a = [10, 20, 30, 40, 50]
a.remove(30)
print("After remove(30):", a)
List comprehension
List comprehension is a way to create lists using a concise syntax.
It allows us to generate a new list by applying an expression to
each item in an existing list
Example:
a = [2,3,4,6,7]
Tuple
Python Tuple is a collection of objects separated by commas. A
tuple is similar to a Python list in terms of indexing, nested
objects, and repetition but the main difference between both is
Python tuple is immutable, unlike the Python list which is
mutable.
Example:
a = (1, 2, 3)
print(a)
Dictionary
A Python dictionary is a data structure that stores the value in key:
value pairs.
Example:
a= {1: 'Nepal', 2: 'Uk', 3: 'Japan'}
print(a)
Function
Python Functions is a block of statements that return the specific
task.
Example:
def fun():
print("Welcome to Python")
fun()
Scope of variable
On the basis of scope, the Python variables are classified in three
categories −
Local Variables
Global Variables
Nonlocal Variables
Local Variables
A local variable is defined within a specific function or
block of code. It can only be accessed by the function or
block where it was defined.
Global Variables
A global variable can be accessed from any part of the
program, and it is defined outside any function or block of
code. It is not specific to any block or function.
Nonlocal Variables
The Python variables that are not defined in either local or
global scope are called nonlocal variables. They are used in
nested functions.
Control statement
I. If…Else
1 a=5 2 b=8
if a>b:
print( a is greater than b )
if b>a: 8
print( b is greater than a ) =
if a==b:
print( a is equal to b )
Example-2:
class Dog:
def __init__(self,name,age):
self.name = name
self.age = age
def full_details(self):
return f"Dog name is {self.name} and age is {self.age}"
my_obj = Dog("Rocky", 10)
print(my_obj.full_details())
Inheritance
Inheritance is the process of creating new classes from existing
classes.
Types of inheritance in python
1. Simple inheritance
2. Multilevel inheritance
3. Hierarchical inheritance
4. Multiple inheritance
5. Hybrid inheritance
def speak(self):
pass
class Dog(Animal):
def speak(self):
return f"{self.name} barks!"
dog = Dog("Buddy")
print(dog.speak())
def output(self):
return f"{self.brand} {self.model}"
class ElectricCar:
def __init__(self, battery_size):
self.battery_size = battery_size
def display(self):
return f"{self.battery_size}"
class ElectricCar(Car):
def __init__(self, brand, model, battery_size):
super().__init__(brand, model)
self.battery_size = battery_size
class Price(Car):
def __init__(self, brand, model, price):
super().__init__(brand, model )
self.price = price
obj1 = ElectricCar("tesla", "Model S", "85kmh")
obj2 = Price("tesla", "model S", "100M")
#print(obj1.output())
print(obj1.battery_size)
#print(obj2.output())
print(obj2.price)
Encapsulation
Example-1:
class Private:
def __init__(self):
self.__salary = 50000 # Private attribute
def salary(self):
return self.__salary # Access through public method
obj = Private()
print(obj.salary()) # Works
#print(obj.__salary) # Raises AttributeError
Example-2:
class Protected:
def __init__(self):
self._age = 30 # Protected attribute
class Subclass(Protected):
def display_age(self):
print(self._age) # Accessible in subclass
Polymorphism
Example-1:
#Polymorphism in function
def add(a, b):
return a+b
print(add(3,3))
print(add("Nagendra","Mahatara"))
Example-2:
# Polymorphism in operators
print(3 + 3)
print("Nagendra" + "Mahatara")
print([1,2] + [5,10])
Example-3:
# method overloading
class area:
def find_area(self, a, b = None):
if b!= None:
print(a*b)
else:
print(a*a)
obj = area()
obj.find_area(10,20)
obj.find_area(10)
Static method
A static method is a method which is bound to the class and not
the object of the class.
Example-1:
class A:
@staticmethod
def display(name):
return name
A()
print(A.display("Nagendra"))
Example-2:
class Rectangular:
@staticmethod
def display(dis):
return dis
Rectangular
print(Rectangular.display("This is rectangular class:"))
class Rectangular:
@staticmethod
def display():
print("I am in rectangular class")
Rectangular
Rectangular.display()
Property decorates
property decorator is a built-in decorator in Python which is
helpful in defining the properties effortlessly without manually
calling the inbuilt function property().
Example-1:
class A:
def __init__(self):
self._accuracy = 0.95
@property
def accuracy(self):
return self._accuracy
predictor = A()
John = Javatpoint()
John.set_age(19)
print(John.get_age())
print(John._age)
Exception Handling
Python Exception Handling handles errors that occur during the
execution of a program.
Example-1:
# Example of an exception
n = 10
try:
res = n / 0
except ZeroDivisionError:
print(“Can’t be divided by zero!”)
try:
n=0
res = 100 / n
except ZeroDivisionError:
print(“You can’t divide by zero!”)
Example-2:
except ValueError:
print(“Enter a valid number!”)
else:
print(“Result is”, res)
finally:
print(“Execution complete.”)
File handling
File handling refers to the process of performing operations on a
file such as creating, opening, reading, writing and closing it.
Example-1:Reading file
file = open("text.txt", "r")
content = file.read()
print(content)
file.close()
Example-3:
file = open("text.txt", "r")
file.close()