[go: up one dir, main page]

0% found this document useful (0 votes)
8 views18 pages

Labmanual

The document contains a series of programming tasks, including creating a dictionary from a list and tuple, generating a Fibonacci series, implementing basic arithmetic operations in a module, demonstrating multilevel inheritance, validating strong passwords, handling exceptions, using threads, performing file operations, interacting with MongoDB, and creating a Django login page. Each task is accompanied by code snippets that illustrate the implementation. The document serves as a comprehensive guide for various programming concepts and practices.

Uploaded by

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

Labmanual

The document contains a series of programming tasks, including creating a dictionary from a list and tuple, generating a Fibonacci series, implementing basic arithmetic operations in a module, demonstrating multilevel inheritance, validating strong passwords, handling exceptions, using threads, performing file operations, interacting with MongoDB, and creating a Django login page. Each task is accompanied by code snippets that illustrate the implementation. The document serves as a comprehensive guide for various programming concepts and practices.

Uploaded by

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

Q.1. Write a program to create dictionary from list and tuple.

names = ["ajay", "sneha", "vivek", "pooja", "sagar", "riddhi"]

roll_nos = (101, 102, 103, 104, 105, 106)

student_dict = {}

for i in range(len(names)):

student_dict[names[i]] = roll_nos[i]

print(student_dict)

Output:
Q.2. Write a program to print the Fibonacci series using function.

def fibonacci_series(n):

a, b = 0, 1

print("Fibonacci Series:")

for _ in range(n):

print(a, end=' ')

a, b = b, a + b

num_terms = int(input("Enter the number of terms in the Fibonacci series: "))

fibonacci_series(num_terms)

Output:
Q.3. Create a module name ‘Calculate’ and add 4 methods in it
add(),substract(),multiply(), and divide(), create another module named as
‘operations’ and import ‘Calculate’ module in it and use its function.

calculate.py

def add(a, b):

return a + b

def subtract(a, b):

return a - b

def multiply(a, b):

return a * b

def divide(a, b):

if b == 0:

raise ValueError("Cannot divide by zero.")

return a / b

calculations.py

import calculate

def perform_operations():

a = 10

b=5

print("Addition:", calculate.add(a, b))

print("Subtraction:", calculate.subtract(a, b))

print("Multiplication:", calculate.multiply(a, b))


print("Division:", calculate.divide(a, b))

if __name__ == "__main__":

perform_operations()

Output:
Q.4. Write a program to demonstrate the use of Multilevel inheritance?

class Animal:

def __init__(self, name):

self.name = name

def speak(self):

print(f"{self.name} makes a sound")

class Dog(Animal):

def speak(self):

print(f"{self.name} barks")

class Labrador(Dog):

def color(self):

print(f"{self.name} is brown")

animal = Animal("Generic Animal")

dog = Dog("Buddy")

labrador = Labrador("Max")

animal.speak()

dog.speak()

labrador.speak()

labrador.color()
Output:
Q.5 Write a program to validate strong password using regular expression ?

import re

def is_strong_password(password):

pattern = re.compile(r'''

(?=.*[a-z])

(?=.*[A-Z])

(?=.*\d)

(?=.*[@$!%*?&])

.{8,}

''', re.VERBOSE)

return bool(pattern.match(password))

password = input("Enter a password to validate: ")

if is_strong_password(password):

print("The password is strong.")

else:

print("The password is weak. Please ensure it meets the criteria.")


Output:
Q.6. Write a program to demonstrate the exception handling mechanism in
python?

def divide_numbers():

try:

numerator = int(input("Enter the numerator: "))

denominator = int(input("Enter the denominator: "))

result = numerator / denominator

except ZeroDivisionError:

print("Error: Division by zero is not allowed.")

except ValueError:

print("Error: Please enter valid integers.")

else:

print(f"Result: {result}")

finally:

print("Execution complete.")

divide_numbers()

Output:
Q.7. Write a program and create 2 threads in python , one should print square of
a numbers (1-10) while other should print the cube of the numbers. ( 1-10)

import threading

def print_squares():

for i in range(1, 11):

print(f"Square of {i}: {i ** 2}")

def print_cubes():

for i in range(1, 11):

print(f"Cube of {i}: {i ** 3}")

thread1 = threading.Thread(target=print_squares)

thread2 = threading.Thread(target=print_cubes)

thread1.start()

thread2.start()

thread1.join()

thread2.join()

print("Execution complete.")
Output:
Q.8. Write Programs to perform searching, adding, updating the content from
the file.

def add_content(file_name, content):

with open(file_name, 'a') as file:

file.write(content + '\n')

print("Content added successfully.")

def search_content(file_name, search_term):

with open(file_name, 'r') as file:

lines = file.readlines()

found = False

for line in lines:

if search_term in line:

print(f"Found: {line.strip()}")

found = True

if not found:

print("Search term not found.")

def update_content(file_name, old_content, new_content):

with open(file_name, 'r') as file:

lines = file.readlines()

with open(file_name, 'w') as file:

for line in lines:

if old_content in line:

file.write(line.replace(old_content, new_content))
print("Content updated successfully.")

else:

file.write(line)

def main():

file_name = 'sample_file.txt'

add_content(file_name, "Hello, this is a test.")

add_content(file_name, "This is another line.")

search_content(file_name, "test")

update_content(file_name, "test", "sample")

print("\nUpdated file content:")

with open(file_name, 'r') as file:

print(file.read())

if name == "main ":

main()

Output:
After Adding Content:

Content added

successfully. Content

added successfully.

Searching for "test":

Found: Hello, this is a test.


After Updating Content:

Content updated successfully.


Updated file content:

Hello, this is a

sample. This is

another line.
Q.9. Write a pythan program to perform following operations. on MongoDB

import pymongo

client = pymongo.MongoClient("mongodb://localhost:27017/") db

= client["CompanyDB"]

emp_collection = db["EMP"]

employees = [

{"Emp-name": "John", "Emp-mobile": "9876543210", "Emp-sal": 8000, "Age": 30},


{"Emp-name": "Riddhi", "Emp-mobile": "9988776655", "Emp-sal": 6000, "Age": 25},

{"Emp-name": "Saurabh", "Emp-mobile": "9123456789", "Emp-sal": 12000, "Age": 35},

{"Emp-name": "Amit", "Emp-mobile": "9156781234", "Emp-sal": 9500, "Age": 28},

{"Emp-name": "Neha", "Emp-mobile": "9801234567", "Emp-sal": 5000, "Age": 26}

emp_collection.insert_many(employees) print("5

documents inserted.")

print("\nEmployees with salary between 5000 and 10000:") query

= {"Emp-sal": {"$gte": 5000, "$lte": 10000}} employees_in_range =

emp_collection.find(query)

for emp in employees_in_range: print(emp)


new_mobile = "9912345678"

emp_collection.update_one({"Emp-name": "Riddhi"}, {"$set": {"Emp-mobile": new_mobile}})

print("\nUpdated mobile number for Riddhi.")

print("\nEmployees ordered by age:") employees_ordered =

emp_collection.find().sort("Age") for emp in

employees_ordered:

print(emp)

client.close()

Output:
5 documents inserted.
Employees with salary between 5000 and 10000:

{'_id': ObjectId('...'), 'Emp-name': 'John', 'Emp-mobile': '9876543210', 'Emp-sal': 8000, 'Age': 30}

{'_id': ObjectId('...'), 'Emp-name': 'Riddhi', 'Emp-mobile': '9988776655', 'Emp-sal': 6000, 'Age':


25}

{'_id': ObjectId('...'), 'Emp-name': 'Amit', 'Emp-mobile': '9156781234', 'Emp-sal': 9500, 'Age':


28}

{'_id': ObjectId('...'), 'Emp-name': 'Neha', 'Emp-mobile': '9801234567', 'Emp-sal': 5000, 'Age':


26}

Updated mobile number for Riddhi.


Employees ordered by age:

{'_id': ObjectId('...'), 'Emp-name': 'Riddhi', 'Emp-mobile': '9912345678', 'Emp-sal': 6000, 'Age':


25}

{'_id': ObjectId('...'), 'Emp-name': 'Neha', 'Emp-mobile': '9801234567', 'Emp-sal': 5000, 'Age':


26}

{'_id': ObjectId('...'), 'Emp-name': 'Amit', 'Emp-mobile': '9156781234', 'Emp-sal': 9500, 'Age':


28}

{'_id': ObjectId('...'), 'Emp-name': 'John', 'Emp-mobile': '9876543210', 'Emp-sal': 8000, 'Age': 30}

{'_id': ObjectId('...'), 'Emp-name': 'Saurabh', 'Emp-mobile': '9123456789', 'Emp-sal': 12000,


'Age': 35
Q.10. Create a django project which contain login page and if user enters
username=”iims” and password=”python” then redirect user to dashboard
which having welcome message.

INSTALLED_APPS = [

'userlogin',

from django.urls import path

from . import views

urlpatterns = [

path('', views.login_view, name='login'),

path('dashboard/', views.dashboard_view, name='dashboard'),

from django.contrib import admin from

django.urls import path, include

urlpatterns = [

path('admin/', admin.site.urls),

path('userlogin/', include('userlogin.urls')),

from django.shortcuts import render, redirect

from django.http import HttpResponse


def login_view(request):

if request.method == "POST":

username = request.POST.get('username') password =

request.POST.get('password')

if username == "iims" and password == "python":

return redirect('dashboard')

else:

return HttpResponse("Invalid credentials")


return render(request, 'userlogin/login.html')
def dashboard_view(request):

return HttpResponse("Welcome to the Dashboard!")

<!-- userlogin/templates/userlogin/login.html -->

<!DOCTYPE html>

<html>

<head>

<title>Login</title>

</head>

<body>

<h2>Login</h2>

<form method="POST">

{% csrf_token %}

<label for="username">Username:</label>

<input type="text" name="username" required>


<br>

<label for="password">Password:</label>

<input type="password" name="password" required>

<br><br>

<button type="submit">Login</button>

</form>

</body>

</html>

You might also like