0% found this document useful (0 votes)
4 views1 page

Pythonhehe

The document outlines various Python programming experiments, covering topics such as print statements, loops, conditional statements, operators, functions, and data structures like lists, tuples, sets, and dictionaries. It also includes advanced concepts like class inheritance, method overloading, and the use of modules. Each experiment demonstrates specific functionalities and coding practices in Python.

Uploaded by

aditipatwa20
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views1 page

Pythonhehe

The document outlines various Python programming experiments, covering topics such as print statements, loops, conditional statements, operators, functions, and data structures like lists, tuples, sets, and dictionaries. It also includes advanced concepts like class inheritance, method overloading, and the use of modules. Each experiment demonstrates specific functionalities and coding practices in Python.

Uploaded by

aditipatwa20
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

Experiment 1: Basic Python Print Statement print("Left Shift:", a << 1) Experiment 6: Loop Control Statement Experiment 8: List Functions

l Statement Experiment 8: List Functions (append, insert, remove, Experiment 9: Tuple Operations print("Intersection of Set1 and Set2:",
pop) intersection_set)
print("Hello World!"); print("Right Shift:", a >> 1) # Demonstrating 'continue' statement my_tuple = (10, 20, 30, 40, 50)
# Creating a list difference_set = set1.difference(set2)
Experiment 2: Taking Input from User Experiment 4: Conditional Statements (Grade using print("Using 'continue' statement:") print("Created tuple:", my_tuple)
if-elif-else) my_list = [10, 20, 30, 40, 50] print("Difference of Set1 and Set2:", difference_set)
print("Hello World!") for i in range(1, 6): print("First element:", my_tuple[0])
score = float(input("Enter your score:")) # len() symmetric_difference_set =
name = input("Enter your name:") if i == 3: print("Last element:", my_tuple[-1])
set1.symmetric_difference(set2)
if score >= 90: print("Length of list:", len(my_list))
age = input("Enter your age:") continue print("All elements in tuple:", my_tuple)
print("Symmetric Difference of Set1 and Set2:",
print("Grade: A") # max()
print("My name is:", name) print(i) my_list = list(my_tuple) symmetric_difference_set)
elif score >= 80: print("Maximum value in list:", max(my_list))
print("My age is:", age) # Demonstrating 'pass' statement print("Converted to list:", my_list)
print("Grade: B") # list()
Experiment 3: Operators print("\nUsing 'pass' statement:") my_list.append(60) Experiment 12: Operations on Dictionary
elif score >= 70: string = "hello"
# Arithmetic Operators for i in range(1, 6): print("List after adding an element:", my_list) # Create Dictionary
print("Grade: C") list_from_string = list(string)
a = 10 if i == 3: new_tuple = tuple(my_list) my_dict = {"name": "Aditi", "age": 22, "city":
elif score >= 60: print("\nList from string:", list_from_string) "Mumbai"}
b=5 pass print("Converted back to tuple:", new_tuple)
print("Grade: D") # append() print("Original Dictionary:", my_dict)
print("Arithmetic Operators:") print(i) del my_tuple
else: my_list.append(60) # Access Dictionary
print("Addition:", a + b) # Demonstrating 'break' statement print("Original tuple deleted.")
print("Grade: E") print("\nList after appending 60:", my_list) print("\nAccess name:", my_dict["name"])
print("Subtraction:", a - b) print("\nUsing 'break' statement:") Experiment 10: Set Operations
Experiment 5: Loops # count() # Update Dictionary
print("Multiplication:", a * b) for i in range(1, 6): s = set([1, 2, 3, 4])
# 'while' loop count_20 = my_list.count(20) my_dict["age"] = 23
print("Division:", a / b) if i == 3: print("Set:", s)
print("While Loop:") print("\nCount of 20 in list:", count_20) my_dict["profession"] = "Student"
print("Modulus:", a % b) break for item in s:
count = 1 # extend() print("\nUpdated Dictionary:", my_dict)
print("Exponentiation:", a ** b) print(i) print("Accessing:", item)
while count <= 5: my_list.extend([70, 80]) # Delete from Dictionary
print("Floor Division:", a // b) Experiment 7: List Creation and Accessing Elements s.add(5)
print("Count is:", count) print("\nList after extending with [70, 80]:", my_list) del my_dict["city"]
# Logical Operators # Create List s.update([6, 7])
count += 1 # insert() print("\nDictionary after deletion:", my_dict)
x = True my_list = [1, 2, 3, 4, 5] print("Updated Set:", s)
my_list.insert(2, 25) # Looping through Dictionary
y = False print("Original List:", my_list) s.remove(3)
# 'for' loop print("\nList after inserting 25 at index 2:", my_list) print("\nLooping through Dictionary:")
print("\nLogical Operators:") # Access List s.discard(8)
print("\nFor Loop:") # pop() for key, value in my_dict.items():
print("AND Operator:", x and y) print("\nAccessing element at index 2:", my_list[2]) print("After Deletion:", s)
for i in range(1, 6): popped_element = my_list.pop(4) print(key, ":", value)
print("OR Operator:", x or y) # Update List - Add item s.clear()
print("i is:", i) print("\nList after popping element at index 4:", # Create Dictionary from List
print("NOT Operator:", not x) my_list.append(6) print("Cleared Set:", s)
my_list)
keys = ["id", "name", "marks"]
# Bitwise Operators print("\nList after adding item 6:", my_list)
print("Popped element:", popped_element)
# Nested loop values = [101, "Karan", 88]
a = 10 # Binary: 1010 # Update List - Remove item Experiment 11: Functions on Set
# remove()
print("\nNested Loop:") dict_from_list = dict(zip(keys, values))
b = 4 # Binary: 0100 my_list.remove(4) set1 = {1, 2, 3, 4}
my_list.remove(30)
for i in range(1, 4): print("\nDictionary from List:", dict_from_list)
print("\nBitwise Operators:") print("\nList after removing item 4:", my_list) set2 = {3, 4, 5, 6}
print("\nList after removing 30:", my_list)
for j in range(1, 4):
print("AND Operator:", a & b) # Delete List union_set = set1.union(set2)
print(f"i: {i}, j: {j}")
print("OR Operator:", a | b) del my_list print("Union of Set1 and Set2:", union_set)

print("XOR Operator:", a ^ b) print("\nList has been deleted.") intersection_set = set1.intersection(set2)

Experiment 13: User Define Functions Experiment 15: Advanced Functions Experiment 17: Use of Module class Mahindra: Experiment 21: Use of Constructor Experiment 22: Method Overloading and Method
Overriding
def function_without_argument(): from functools import reduce import math def __init__(self): # Default Constructor
# Method Overloading (simulated using default
print("This is a function without an argument.") square = lambda x: x ** 2 import random self.models=['Scorpio','Bolero','Xylo'] class DefaultConstructor:
arguments in Python)
def function_with_argument(a, b): print("Lambda function result:", square(5)) import os def PModel(self): def __init__(self):
class Calculator:
return a + b numbers = [1, 2, 3, 4, 5] print("Square root of 16:", math.sqrt(16)) print("Models of Mahendra") self.message = "This is a default constructor."
def add(self, a, b=0, c=0):
def function_returning_value(): squared_numbers = list(map(lambda x: x ** 2, print("Factorial of 5:", math.factorial(5)) for model in self.models: def display(self):
return a + b + c
numbers))
return "This function returns a value." print("Value of Pi:", math.pi) print('\t%s ' % model) print(self.message)
# Method Overriding
print("Map function result:", squared_numbers)
function_without_argument() print("Random number between 1 and 10:", # Parameterized Constructor
class Animal:
product = reduce(lambda x, y: x * y, numbers) random.randint(1, 10))
result = function_with_argument(5, 3) 4. Finally we create an init.py file inside the directory, class ParameterizedConstructor:
def sound(self):
print("Reduce function result:", product) print("Random float between 0 and 1:", to let Python know that the directory is a package.
print("Function with argument result:", result) def __init__(self, name, age):
random.random()) print("Animal makes a sound")
Filename= init.py
returned_value = function_returning_value() self.name = name
print("Current working directory:", os.getcwd()) class Dog(Animal):
Experiment 16: User Defined Module from Maruti import Maruti
print("Returned value:", returned_value) self.age = age
os.mkdir('new_directory') def sound(self):
1.Make a new file named calculator and write the from Mahindra import Mahindra
def display(self):
given code. print("Created new directory:", os.listdir()) print("Dog barks")
Experiment 14: Function Features print(f"Name: {self.name}, Age: {self.age}")
def add(a, b): os.rmdir('new_directory') # Create objects and demonstrate Method
5. To access package car, create sample.py file and
def function_positional_required(arg1, arg2): # Constructor Overloading (simulated using default Overloading and Method Overriding
return a + b access classes from directory car
arguments)
print(f"Positional Arguments: {arg1}, {arg2}") calc = Calculator()
def subtract(a, b): Experiment 18: Create and Use a User Defined Filename=sample.py
class ConstructorOverloading:
def function_keyword_argument(arg1, Package print("Method Overloading - Add 2 numbers:",
return a - b from Maruti import Maruti
arg2="default"): def __init__(self, name="Unknown", age=0): calc.add(5, 10))
Creating and accessing a Python Package:
def multiply(a, b): from Mahindra import Mahindra
print(f"Keyword Argument: {arg1}, {arg2}") self.name = name print("Method Overloading - Add 3 numbers:",
Steps to create package in Python
return a * b ModelMaruti=Maruti() calc.add(5, 10, 15))
def function_default_argument(arg1, arg2=10): self.age = age
1.Create a package called car
def divide(a, b): ModelMaruti.PModel() animal = Animal()
print(f"Default Argument: {arg1}, {arg2}") def display(self):
Filename= car
if b != 0: ModelMahindra=Mahindra() animal.sound()
def function_variable_length_argument(*args): print(f"Name: {self.name}, Age: {self.age}")
return a / b ModelMahindra.PModel() dog = Dog()
print("Variable Length Arguments:", args) # Create objects
2.Create a file name it Maruti.py and write following
else: dog.sound()
function_positional_required(5, 10) code default_obj = DefaultConstructor()
return "Division by zero is not allowed" Experiment 20: Class and Object
function_keyword_argument(5, arg2="custom") Filename=Maruti.py default_obj.display()
class Student: Experiment 27: Python GUI using Tkinter
function_default_argument(5) class Maruti: param_obj = ParameterizedConstructor("Alice", 25)
2. Create a new file with any name and write the code def __init__(self, name): import tkinter as tk
function_variable_length_argument(1, 2, 3, 4, 5) def __init__(self): param_obj.display()
given below.
self.name = name root=tk.Tk()
self.models=['800','Alto','WagonR'] overload_obj1 = ConstructorOverloading("Bob", 30)
import calculator
def show(self): root.title("My First GUI Window")
def PModel(self): overload_obj1.display()
num1 = 10
print("Name:", self.name) root.geometry("400x300")
print("Models of Maruti") overload_obj2 = ConstructorOverloading()
num2 = 5
s = Student("Aditi") root.mainloop()
for model in self.models: overload_obj2.display()
print("Addition:", calculator.add(num1, num2))
s.show()
print('\t%s ' % model)
print("Subtraction:", calculator.subtract(num1, num2))

print("Multiplication:", calculator.multiply(num1,
num2)) 3.Create another file Mahindra.py

print("Division:", calculator.divide(num1, num2)) Filename=Mahindra.py

Experiment 24: Inheritance Types child.work()

# Single Inheritance child.play()

class Animal: child2 = Child2()

def sound(self): child2.wisdom()

print("Animal makes a sound") child2.guidance()

class Dog(Animal): child2.study()

def bark(self):

print("Dog barks") Experiment 25: Operations using Pandas

# Multiple Inheritance import pandas as pd

class Mother: import numpy as np

def cooking(self): # 1. Create Series from Array

print("Mother cooks food") array = np.array([10, 20, 30, 40, 50])

class Father: series_from_array = pd.Series(array)

def work(self): print("Series from Array:\n", series_from_array)

print("Father works in office")

class Child(Mother, Father): # 2. Create Series from List

def play(self): list_data = [5, 10, 15, 20, 25]

print("Child plays outside") series_from_list = pd.Series(list_data)

# Multilevel Inheritance print("\nSeries from List:\n", series_from_list)

class Grandparent:

def wisdom(self): # 3. Access element of Series

print("Grandparent shares wisdom") print("\nElement at index 2 in Series from List:",


series_from_list[2])
class Parent(Grandparent):

def guidance(self):
# 4. Create DataFrame using List
print("Parent provides guidance")
data = [['Alice', 25], ['Bob', 30], ['Charlie', 35]]
class Child2(Parent):
df_from_list = pd.DataFrame(data, columns=['Name',
def study(self):
'Age'])
print("Child studies")
print("\nDataFrame from List:\n", df_from_list)
# Create objects and demonstrate inheritance types
# Create DataFrame using Dictionary
dog = Dog()
data_dict = {'Name': ['Alice', 'Bob', 'Charlie'], 'Age':
dog.sound() [25, 30, 35]}

dog.bark() df_from_dict = pd.DataFrame(data_dict)

child = Child() print("\nDataFrame from Dictionary:\n",


df_from_dict)
child.cooking()

You might also like