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

Python_Assignment_Full

Uploaded by

malegaon vv
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Python_Assignment_Full

Uploaded by

malegaon vv
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16

Python Programming Practical

Assignment

1. Python installation and configuration with windows and


Linux

Step 1: Download Python

1. Visit the official Python website: https://www.python.org/downloads/


2. Click on the "Download Python" button for the latest version.

Step 2: Run the Installer

1. Once the Python installer is downloaded, run the installer.


2. Important: Check the box that says "Add Python to PATH" before clicking "Install
Now". This will make Python available from the command line.
3. Click "Install Now" to proceed with the installation.

Step 3: Verify Installation

1. Open Command Prompt (search for cmd in the Start menu).


2. Type python --version or python -V to check if Python is installed correctly. It
should display the version of Python installed.

Step 4: Install pip (if necessary)

 Pip (Python's package installer) is usually installed by default. You can check by
typing pip --version in the command prompt. If it's not installed, download get-
pip.py from here, and run python get-pip.py from the command prompt.

2. Python Installation on Linux (Ubuntu/Debian-based)

Step 1: Update Package List

1. Open the terminal.


2. Run the following command to update the package list:

Copy code
sudo apt update

Step 2: Install Python

1. To install the latest version of Python 3 (Python 3.x), use the following command:
Copy code
sudo apt install python3

2. To install pip for Python 3, run:

Copy code
sudo apt install python3-pip

Step 3: Verify Installation

1. After installation, verify that Python is installed by running:

Copy code
python3 --version

2. To check if pip was installed, run:

bash
Copy code
pip3 --version

Step 4: Configure Virtual Environment (Optional but recommended)

1. Install venv (a tool to create virtual environments):

Copy code
sudo apt install python3-venv

2. Create a new virtual environment:

Copy code
python3 -m venv myenv

3. Activate the virtual environment:

Copy code
source myenv/bin/activate

4. To deactivate, simply type deactivate in the terminal.

3. Configuration on Both Systems

Configure PATH (if needed):

 On Windows, the Python installer automatically adds Python to the PATH. If it's not
added, manually add the Python directory to the PATH.
 On Linux, the Python binaries are usually located in /usr/bin by default, so they
should be in the PATH automatically. If not, you may need to add
/usr/local/bin/python3 to your PATH variable in the .bashrc or .zshrc file.
Install Additional Libraries with pip:

 To install Python libraries, use pip (Python's package manager). Example:

bash
Copy code
pip install numpy

2. Write a python program accept number from user to check


user entered number is even or odd using if-else statement
number = int(input("Enter a number: "))
if number % 2 == 0:
print(f"{number} is Even.")
else:
print(f"{number} is Odd.")

Input:
Enter a number: 7
Output:
7 is Odd.

3. Write a python program to find a greater number


between two numbers using Nested if-else statement

num1 = int(input("Enter first number: "))


num2 = int(input("Enter second number: "))
if num1 > num2:
print(f"The greater number is {num1}")
else:
print(f"The greater number is {num2}")
Input:
Enter first number: 5
Enter second number: 10
Output:
The greater number is 10.

4. Write a program to accept student roll no, name and five


subject marks. print student result like roll no, name, five
subject marks, subject total, percentage and grade using
if else elif statement.

roll_no = input("Enter Roll Number: ")


name = input("Enter Name: ")
marks = []
total_subjects = 5

for i in range(total_subjects):
mark = float(input(f"Enter marks for subject {i + 1}: "))
marks.append(mark)
total_marks = sum(marks)
percentage = (total_marks / (total_subjects * 100)) * 100

if percentage >= 90:


grade = "A"
elif percentage >= 75:
grade = "B"
elif percentage >= 50:
grade = "C"
else:
grade = "D"

print(f"Roll No: {roll_no}, Name: {name}")


print(f"Marks: {marks}")
print(f"Total Marks: {total_marks}")
print(f"Percentage: {percentage:.2f}%")
print(f"Grade: {grade}")

INPUT-
Enter Roll Number: 61
Enter Name: Rakesh Thakare
Enter marks for subject 1: 80
Enter marks for subject 2: 75
Enter marks for subject 3: 60
Enter marks for subject 4: 82
Enter marks for subject 5: 90
OUTPUT-
Roll No: 61, Name: Rakesh Thakare
Marks: [80.0, 75.0, 60.0, 82.0, 90.0]
Total Marks: 387.0
Percentage: 77.40%
Grade: B

5. Write a python program to check whether given number


is Armstrong or not using while loop. Accept number from
user.

num = int(input("Enter a number: "))


sum = 0
temp = num

while temp > 0:


digit = temp % 10
sum += digit ** 3
temp //= 10

if num == sum:
print(f"{num} is an Armstrong number.")
else:
print(f"{num} is not an Armstrong number.")
Input:
Enter a number: 153
Output:
153 is an Armstrong number.

6. Print the following pattern


****
***
**
*
*
rows = 5
for i in range(rows, 0, -1):
print("* " * i)

7. Write a function that takes single character and print


“Given character is Vowel”. If it is vowel, “Given
character is not vowel” otherwise

char = input("Enter a single character: ").lower()


if char in 'aeiou':
print("Given character is Vowel.")
else:
print("Given character is not Vowel.")

Input:
Enter a single character: a
Output:
Given character is Vowel.

8. Write a python program to calculate factorial of a given


user accepted number using recursive function.

def factorial(n):
if n == 0 or n == 1:
return 1
return n * factorial(n - 1)

number = int(input("Enter a number: "))


if number < 0:
print("Factorial is not defined for negative numbers.")
else:
print(f"The factorial of {number} is {factorial(number)}.")

Input:
Enter a number: 5
Output:
The factorial of 5 is 120.

9. Write a python program to generate the Fibonacci series


using recursive function.

def fibonacci(n):
if n <= 1:
return n
return fibonacci(n - 1) + fibonacci(n - 2)

terms = int(input("Enter number of terms: "))


print("Fibonacci series:")
for i in range(terms):
print(fibonacci(i), end=" ")

Input:
Enter number of terms: 10
Output:
Fibonacci series: 0 1 1 2 3 5 8 13 21 34

10. WritePython code to illustrate anonymous function


lambda in Python.
square = lambda x: x * x
number = int(input("Enter a number to find its square: "))
print(f"The square of {number} is {square(number)}.")

Input:
Enter a number to find its square: 4
Output:
The square of 4 is 16.

11. Python code to illustrate Decorators with


parameters in Python.

def decorator_with_args(greeting):
def decorator(func):
def wrapper(name):
print(f"{greeting}, {name}!")
func(name)
return wrapper
return decorator

@decorator_with_args("Hello")
def say_name(name):
print(f"My name is {name}.")
name = input("Enter your name: ")
say_name(name)

INPUT-
Enter your name: Rakesh Thakare
OUTPUT-
Hello, Rakesh Thakare!
My name is Rakesh Thakare.

12. Python code to illustrate Generator in Python

def generate_numbers(n):
for i in range(n):
yield i
num = int(input("Enter the range for generating numbers: "))
for value in generate_numbers(num):
print(value, end=" ")
Input:
Enter the range for generating numbers: 5
Output:
01234

13. Program to check for Zero Division Error


Exception.
try:
numerator = int(input("Enter numerator: "))
denominator = int(input("Enter denominator: "))
result = numerator / denominator
print(f"The result is {result}.")
except ZeroDivisionError:
print("Error: Division by zero is not allowed.").
Input:
Enter numerator: 10
Enter denominator: 0
Output:
Error: Division by zero is not allowed.

14. Program to check for ValueError Exception.


try:
number = int(input("Enter an integer: "))
print(f"You entered: {number}.")
except ValueError:
print("Error: That is not a valid integer.")
Input:
Enter an integer: hello
Output:
Error: That is not a valid integer.
15. Write a python program to raise a user defined
exception if age is less than

class AgeError(Exception):
pass

try:
age = int(input("Enter your age: "))
if age < 18:
raise AgeError("Age must be 18 or above.")
print("Access granted.")
except AgeError as e:
print(e)

Input:
Enter your age: 16
Output:
Age must be 18 or above.

16. Write a python program to raise a user defined


exception for bank exception like AttemptError,
BalanceError consider following requirements
* Withdraw money from bank.
* Balance in bank should not be less than1000.
* User account will be blocked for an hour if user put 3 times
wrong pin.4

class BalanceError(Exception):
pass

class AttemptError(Exception):
pass

balance = 5000
attempts = 0
pin = "1234"

while True:
try:
entered_pin = input("Enter your PIN: ")
if entered_pin != pin:
attempts += 1
if attempts >= 3:
raise AttemptError("Your account is blocked for an hour due to 3
incorrect PIN attempts.")
print("Incorrect PIN. Try again.")
continue

print(f"Your balance is {balance}.")


amount = int(input("Enter the amount to withdraw: "))
if balance - amount < 1000:
raise BalanceError("Insufficient balance. Minimum balance of 1000
must be maintained.")
balance -= amount
print(f"Withdrawal successful! Remaining balance: {balance}.")
break
except BalanceError as e:
print(e)
break
except AttemptError as e:
print(e)
break

Input:
Enter your PIN: 1234
Enter the amount to withdraw: 4500
Output:
Insufficient balance. Minimum balance of 1000 must be maintained.

17. Write a program to return a random item from a list,


tuple and string using
random module.

import random

my_list = [1, 2, 3, 4, 5]
my_tuple = ('a', 'b', 'c', 'd', 'e')
my_string = "hello"

print(f"Random item from list: {random.choice(my_list)}")


print(f"Random item from tuple: {random.choice(my_tuple)}")
print(f"Random character from string: {random.choice(my_string)}")

OUTPUT-
Random item from list: 3
Random item from tuple: a
Random character from string: e

18. Write a python program to display current date and


time.

from datetime import datetime


current_time = datetime.now()
print("Current date and time:", current_time)

OUTPUT-
Current date and time: 2024-12-18 21:52:49.112320

19. Create a User define module arithmetic


Operation. The module having functions like sum,
average, power, division, multiplication and return a
result. Import this module and execute module
functions.

def sum(a, b):


return a + b

def average(a, b):


return (a + b) / 2

def power(a, b):


return a ** b

def division(a, b):


if b != 0:
return a / b
return "Division by zero is not allowed."

def multiplication(a, b):


return a * b
import arithmaticsOperation as ao

a, b = 10, 5
print(f"Sum: {ao.sum(a, b)}")
print(f"Average: {ao.average(a, b)}")
print(f"Power: {ao.power(a, b)}")
print(f"Division: {ao.division(a, b)}")
print(f"Multiplication: {ao.multiplication(a, b)}")

Output:
makefile
Copy code
Sum: 15
Average: 7.5
Power: 100000
Division: 2.0
Multiplication: 50
20. Create a package MyPackageDemo. Define two
modules like message.py and calculation.py within a
package. Import given package and show desirable
output.

Package Structure:

MyPackageDemo/
├── __init__.py
├── message.py
├── calculation.py

Module: message.py
def greeting(name):
print(f"Hello, {name}!")

Module: calculation.py
def add(a, b):
return a + b

def subtract(a, b):


return a – b

Main Program:
from MyPackageDemo import message, calculation

message.greeting("Rakesh")
print(f"Addition: {calculation.add(10, 5)}")
print(f"Subtraction: {calculat
ion.subtract(10, 5)}")

OUTPUT-
Hello, Rakesh!
Addition: 15
Subtraction: 5

21. Define a class Student having members roll_no,


name, age, gender .Create a subclass called _Test with
member marks of 3 subjects. Create three objects of the
Test class and display all the details of the student with
total Marks

class Student:
def __init__(self, roll_no, name, age, gender):
self.roll_no = roll_no
self.name = name
self.age = age
self.gender = gender

class Test(Student):
def __init__(self, roll_no, name, age, gender, marks):
super().__init__(roll_no, name, age, gender)
self.marks = marks

def total_marks(self):
return sum(self.marks)

students = [
Test(1, "Pooja", 20, "Female", [85, 90, 78]),
Test(2, "Amol", 22, "Male", [88, 76, 95]),
Test(3, "Rakesh", 19, "Male", [80, 85, 88])
]

for student in students:


print(f"Roll No: {student.roll_no}, Name: {student.name}, Total
Marks: {student.total_marks()}")

OUTPUT-

Roll No: 1, Name: Pooja, Total Marks: 253


Roll No: 2, Name: Amol, Total Marks: 259
Roll No: 3, Name: Rakesh, Total Marks: 253

22. Write a program to implement the overloading


operator

class ComplexNumber:
def __init__(self, real, imag):
self.real = real
self.imag = imag

def __add__(self, other):


return ComplexNumber(self.real + other.real, self.imag +
other.imag)
def __str__(self):
return f"{self.real} + {self.imag}i"

num1 = ComplexNumber(3, 5)
num2 = ComplexNumber(2, 4)
result = num1 + num2
print(f"Addition of complex numbers: {result}")

Output:
Addition of complex numbers: 5 + 9i

23. Write a program to check if an URL is valid or not


using regular expression

import re
def is_valid_url(url):
pattern = re.compile(
r"^(https?://)?(www\.)?([a-zA-Z0-9-]+\.)+[a-zA-Z]{2,}(/[a-zA-Z0-9#]
+/?)?$" )
return bool(pattern.match(url))

url = input("Enter a URL: ")


if is_valid_url(url):
print(f"{url} is a valid URL.")
else:
print(f"{url} is not a valid URL.")

Input:
Enter a URL: https://www.GOOGLE.com
Output:
https://www.GOOGLE.com is a valid URL.

24. Write a python program to check if the string is a


valid email address or
not.

import re

def is_valid_email(email):
pattern = re.compile(r"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]
+$")
return bool(pattern.match(email))

email = input("Enter an email address: ")


if is_valid_email(email):
print(f"{email} is a valid email address.")
else:
print(f"{email} is not a valid email address.")

Input:
Enter an email address: rbthakare2000@gmail.com
Output:
rbthakare2000@gmail.com is a valid email address.

25. Write a program to illustrate creation of thread with


different states.
import threading

import time

def print_numbers():
for i in range(5):
print(f"Number: {i}")
time.sleep(1)

thread = threading.Thread(target=print_numbers)
print("Thread State: NEW")
thread.start()
print("Thread State: RUNNING")
thread.join()
print("Thread State: TERMINATED")

Output:
mathematica
Copy code
Thread State: NEW
Thread State: RUNNING
Number: 0
Number: 1
Number: 2
Number: 3
Number: 4
Thread State: TERMINATED

26. Write the steps for installing MongoDB on windows.

 Go to the official MongoDB website:


https://www.mongodb.com/try/download/community.
 Run the installer and follow the installation wizard.
 Configure MongoDB as a service or run it manually.
 Set up the data directory for MongoDB (default is C:\data\db).
 Start the MongoDB server using the mongod command.
 Use the MongoDB shell (mongo) or a GUI tool like Compass to interact
with the database

27. Write a python Program for performing CRUD


operation with MongoDB and Python

from pymongo import MongoClient

client = MongoClient("mongodb://localhost:27017/")
db = client["testdb"]
collection = db["testcollection"]

data = {"name": "Rakesh", "age": 24, "city": "Malegaon"}


collection.insert_one(data)
print("Data inserted.")
print("Data from database:")
for doc in collection.find():
print(doc)

collection.update_one({"name": "Rakesh"}, {"$set": {"age": 25}})


print("Data updated.")

collection.delete_one({"name": "Rakesh"})
print("Data deleted.")

Output:
Data inserted.
Data from database:
{'_id': ObjectId('...'), 'name': 'Rakesh', 'age': 24, 'city': 'Malegaon'}
Data updated.
Data deleted.

28. Write Django Web development process, project


structure and Models.

 Install Django using pip install django.


 Create a Django project: django-admin startproject myproject.
 Navigate to the project folder: cd myproject.
 Create an app: python manage.py startapp myapp.
 Define models in myapp/models.py.
 Register the app in myproject/settings.py.
 Run migrations to create the database: python manage.py migrate.
 Create views in myapp/views.py.
 Define URLs in myapp/urls.py and link them to the project’s urls.py.
 Start the server: python manage.py runserver.
 Open the application in the browser using http://127.0.0.1:8000

You might also like