Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

Rapti Lab Report Python(Nagendra)

This lab report provides an overview of Python programming concepts, including the Python shell, data structures like lists, tuples, and dictionaries, and key programming principles such as functions, inheritance, and exception handling. It includes examples of various Python features like list comprehension, control statements, and file handling. The report is submitted by Nagendra Mahatara to instructor Amrit Bhusal at Rapti Engineering College.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Rapti Lab Report Python(Nagendra)

This lab report provides an overview of Python programming concepts, including the Python shell, data structures like lists, tuples, and dictionaries, and key programming principles such as functions, inheritance, and exception handling. It includes examples of various Python features like list comprehension, control statements, and file handling. The report is submitted by Nagendra Mahatara to instructor Amrit Bhusal at Rapti Engineering College.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 17

An ISO 9001:2015 Certified

Rapti Engineering College


Ghorahi Sub-Metropolitan-16, Saniambapur Sarra, Dang

(Affiliated to Pokhara University)

Lab Report
On
Subject: Python
Lab Report : #1
Title: Python Programming

Submitted By: Submitted To:


Name: - Nagendra Mahatara Instructor: - Amrit Bhusal
Roll No: - 6 Department of BCA
Faculty: - Science and Technology Submission Date: - 2081-9-26
Semester: - 7th

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

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)

We can remove elements from a list using:


 Remove(): Removes the first occurrence of an element.
 Pop(): Removes the element at a specific index or the last
element if no index is specified.
 Del statement: Deletes an element at a specified index.

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]

b = [val ** 2 for val in a]


print(b)

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)

Convert list to tuple


To convert a list into a tuple is by using the built-
in tuple() function.
Example:
a = [1, 2, 3, 4, 5]

# Convert the list into a tuple


t = tuple(a)
print('tuple:', t)

Function
Python Functions is a block of statements that return the specific
task.
Example:
def fun():
print("Welcome to Python")
fun()

we have the following function argument types in Python:


 Default argument
 Keyword arguments (named arguments)
 Positional arguments
 Arbitrary arguments (variable-length arguments *args and
**kwargs)

*args and **kwargs in Python


In Python, *args and **kwargs are used to allow functions to
accept an arbitrary number of arguments.
Example:
def kwargs_value(**kwargs):
for key, value in kwargs.items():
print(f" {key}, {value}")
kwargs_value(name = "Nagendra", location = "Dang")
Yield vs Return
The yield statement suspends a function’s execution and sends a
value back to the caller, but retains enough state to enable the
function to resume where it left off.
Example:
def generator():
for i in range(1,10):
yield i
value = generator()
for values in value:
print(values)

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 )

II. For loop


Example:
a = [1, 2, 3]
for i in a:
print(i)

III. Break statement


Example:
for i in range(10):
if i == 5:
break
print(i)

IV. Continue statement


Example:
for i in range(20):
if i % 2 == 0:
continue
print(i)
Class
Classes are created using class keyword.
An Object is an instance of a Class. It represents a specific
implementation of the class and holds its own data.
Example-1:
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
my_obj = Dog("Rocky", 25)
print(my_obj.name)
print(my_obj.age)

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

Example: simple inheritance


class Animal:
def __init__(self, name):
self.name = name

def speak(self):
pass

class Dog(Animal):
def speak(self):
return f"{self.name} barks!"

dog = Dog("Buddy")
print(dog.speak())

Example: multilevel inheritance


class Dog:
def __init__(self, brand, model):
self.brand = brand
self.model = model

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 Price(Dog, ElectricCar):


def __init__(self, brand, model, battery_size, price):
Dog.__init__(self, brand, model)
ElectricCar.__init__(self, battery_size)
self.price = price

obj = Price("Tesla", "Model S", "85Mkh", "100M")


print(obj.output())
print(obj.display())
print(obj.price)

Example: Hierarchical inheritance


class Car:
def __init__(self, brand, model):
self.brand = brand
self.model = model
def output(self):
return f"{self.brand} {self.model}"

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

# Create an instance of Subclass


obj = Subclass()
# Call the method to display the age
obj.display_age()

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()

# Access the accuracy property


print(predictor.accuracy)

Getter and setter


Example-1:
def __init__(self, age = 0):
self._age = age
def get_age(self):
return self._age
def set_age(self, a):
self._age = 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-2: Writing to a file


file = open("text.txt", "w")
file.write("Hello, World!")
file.close()

Example-3:
file = open("text.txt", "r")
file.close()

You might also like