0% found this document useful (0 votes)
23 views

Adarsh Harpude - Python

Python coding

Uploaded by

The RockyFF
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

Adarsh Harpude - Python

Python coding

Uploaded by

The RockyFF
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 39

AMITY INSTITUTE OF

INFORMATION TECHNOLOGY
(AIIT)

NAFIS PARWEZ
Enrolment No. A710145023050
Python Programming Lab Journal
MCA Semester – 1

1
Name :- NAFIS PARWEZ

Enrollment No :- A710145023050

Course :- MCA SEM I

Subject :- Python Lab Manual

AMITY UNIVERSITY MAHARASHTRA


Established vide Maharashtra Act No. 13 of 20 14, of Government of Maharashtra, and
recogized under Section 2(t) of UGC Act 1956

CERTIFICATE
This is to certify that Mr. NAFIS PARWEZ Enrollment No. A710145023050 of class MCA, Semester I has
satisfactorily completed the Python Lab Practical lab Manual prescribed by Amity University
Maharashtra during the academic year 2023-2024.

Sign of Faculty Sign of Dept. Coordinator

Name: Mrs. Nirali Verma Name:

2
INDEX
Sr. Topics Page Sign

1. Python Basic Programs 5-15


1) Python program for Accepting input from user and print it
2) Printing addition, subtraction, multiplication and division of two numbers
using user input
3) Finding data type of value assigned to a variable
4)Write a Python program to find if the number entered by user is even or odd
5)Write a python program to find the number entered by user is positive or not
6)Write a python program to find the largest among three numbers
7)Write a python program to find if the person is eligible for voting or not.
8)Write a python program to find if the number is divisible by 12 or not
9)Write a python program to calculate the electricity bill according to
10)Write a python program to print the last two digit of a number
11)Write a python program to display the grade based on student's percentage
12)Multiplication table of aa given number
13)sum of all odd and even number in a given range 14)to
accept a word from user and reverse it
15)to find if a number is amrmstrong number or not
16)to print all the nnumber in a given range
17)Python progam to unpack tuple in variables
18)Since tuple is immutable that means we cannot add an elements in a tuple ..
Write a program to create a new tuple by merging of tuple with the + operator.
19)Write a python program to convert tuple into string
20)Write a program to check whether element exist in tuple or not
21)Write a program to reverse a tuple
22)Write a program to multiply all the elements of tuple 23)Python
program to add ed at the end of a given verb string 24)Python
program for check if the string is pangram.
25)Python program to takes two list as inputs and prints common Output in third
list.
26)Python program to find the number is perfect number or not.
27)Fibonacci series

2. Functions in Python 15-18


• Python Programs on functions
• Programs on recursion to find the factorial of a number
• Python Programs on lambda function
• Programs on _init_function
• Create a class which has init function and normal def function for
displaying the details
• Program to print star pattern
3. Program on matplotlib 18-21

3
4. Program on pandas 22

5. Program on Web scrapping using beautifulsoup 22

6. Programs on scipy 23

7. Django 24-35
Installation of django
Hello world program in django
Program to print date and time using django
Program to print time after 10hrs through dynamic URL’s using django
Program to demonstrate Template in django
Creating Django admin interface
Creating Django Models
CRUD operations on models

8. Kivy 36-41
Kivy Installation
Kivy Programs
Creating simple hello world program
Kivy Program to display Image widget
Kivy Program to create Button
Kivy Program to display Label and checkboxes

4
1)Python program for Accepting input from user and print it
user_input = input("Enter something: ") print("You entered:",

user_input)

2)Printing addition, subtraction, multiplication and division of two


numbers using user input
num1 = float(input("Enter first number: "))

num2 = float(input("Enter second number: "))

addition = num1 + num2 subtraction = num1 -

num2 multiplication = num1 * num2 division

= num1 / num2 print(f"Addition:

{addition}") print(f"Subtraction:

{subtraction}") print(f"Multiplication:

{multiplication}") print(f"Division:

{division}")

3)Finding data type of value assigned to a variable


variable = 10 print(f"Data type of the variable:

{type(variable)}")

4)Write a Python program to find if the number entered by user is even or


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

5
if number % 2 == 0:

print("Even") else:

print("Odd")

5)Write a python program to find the number entered by user is positive


or not
number = float(input("Enter a number: "))

if number > 0:

print("Positive") elif

number == 0:

print("Zero") else:

print("Negative")

6)Write a python program to find the largest among three numbers


num1 = float(input("Enter first number: ")) num2 =

float(input("Enter second number: ")) num3 =

float(input("Enter third number: "))

largest = max(num1, num2, num3)

print(f"The largest number is: {largest}")

6
7)Write a python program to find if the person is eligible for voting or not.
age = int(input("Enter your age: "))

if age >= 18: print("You are eligible

to vote.") else: print("You are not

eligible to vote.")

8)Write a python program to find if the number is divisible by 12 or not


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

if number % 12 == 0: print(f"{number} is

divisible by 12.") else: print(f"{number} is

not divisible by 12.")

9)Write a python program to calculate the electricity bill according to


units = float(input("Enter the number of units consumed: "))

if units <= 50:

cost = units * 0.50 elif units

<= 150:

cost = 50 + (units - 50) * 0.75 elif units <=

250: cost = 50 + 100 + (units - 150) * 1.20

else: cost = 50 + 100 + 100 + (units - 250)

* 1.50

total_cost = cost + cost * 0.20 # Adding 20% surcharge

7
print(f"The electricity bill is: {total_cost}")

10)Write a python program to print the last two digit of a number


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

= number % 100 print(f"The last two digits are:

{last_two_digits}")

11)Write a python program to display the grade based on student's


percentage
percentage = float(input("Enter the student's percentage: "))

if percentage >= 90: grade = 'A' elif percentage >= 80:

grade = 'B' elif percentage >= 70:

grade = 'C' elif


percentage >= 60:
grade = 'D' else:

grade = 'F'

print(f"Grade: {grade}")

12)Multiplication table of a given number


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

for i in range(1, 11):

print(f"{number} x {i} = {number * i}")


8
13)sum of all odd and even number in a given range
start_range = int(input("Enter the start of the range: ")) end_range

= int(input("Enter the end of the range: "))

sum_odd = sum(i for i in range(start_range, end_range + 1) if i % 2 != 0) sum_even

= sum(i for i in range(start_range, end_range + 1) if i % 2 == 0)

print(f"Sum of odd numbers: {sum_odd}") print(f"Sum


of even numbers: {sum_even}")

14)to accept a word from user and reverse it


word = input("Enter a word: ") reversed_word

= word[::-1] print(f"Reversed word:

{reversed_word}")

9
15)to find if a number is amrmstrong number or not
number = int(input("Enter a number: "))

num_str = str(number) order = len(num_str)

sum_digits = sum(int(digit) ** order for digit in num_str)

if sum_digits == number:

print(f"{number} is an Armstrong number") else:

print(f"{number} is not an Armstrong

number")

16)to print all the number in a given range


start_range = int(input("Enter the start of the range: "))
end_range = int(input("Enter the end of the range: ")) for i in
range(start_range, end_range + 1):

print(i)

10
17)Python progam to unpack tuple in variables
my_tuple = (1, 2, 3) a, b, c =

my_tuple print(f"a: {a},

b: {b}, c: {c}")

18)Write a program to create a new tuple by merging of tuple with the +


operator.
tuple1 = (1, 2, 3) tuple2

= (4, 5, 6)

merged_tuple = tuple1 + tuple2 print(f"Merged

Tuple: {merged_tuple}")

19)Write a python program to convert tuple into string


my_tuple = ('H', 'e', 'l', 'l', 'o') result_string

= ''.join(my_tuple) print(f"Resulting

String: {result_string}")

20)Write a program to check whether element exist in tuple or not


my_tuple = (1, 2, 3, 4, 5) element_to_check =

int(input("Enter an element to check: "))

if element_to_check in my_tuple:

print(f"{element_to_check} exists in the tuple") else:

print(f"{element_to_check} does not exist in the tuple")

11
21)Write a program to reverse a tuple
my_tuple = (1, 2, 3, 4, 5) reversed_tuple =

tuple(reversed(my_tuple)) print(f"Reversed

Tuple: {reversed_tuple}")

22)Write a program to multiply all the elements of tuple


my_tuple = (2, 3, 4, 5)

product = 1 for element

in my_tuple: product

*= element

print(f"Product of all elements: {product}")

23)Python program to add ed at the end of a given verb string


verb = input("Enter a verb: ")

if verb.endswith("e"): result

= verb + "d" else: result =

verb + "ed"

print(f"Resulting string: {result}")

24)Python program for check if the string is pangram.


12
import string

def is_pangram(sentence):

alphabet = set(string.ascii_lowercase) return

set(sentence.lower()) >= alphabet

user_input = input("Enter a sentence: ")

if is_pangram(user_input): print("The

string is a pangram.") else: print("The

string is not a pangram.")

25)Python program to takes two list as inputs and prints common Output
in third list.
list1 = [1, 2, 3, 4, 5] list2

= [3, 4, 5, 6, 7] common_elements = list(set(list1) &

set(list2)) print(f"Common elements: {common_elements}")

26)Python program to find the number is perfect number or not.


def is_perfect_number(number):

divisors = [i for i in range(1, number) if number % i == 0]

return sum(divisors) == number

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

is_perfect_number(num): print(f"{num}

is a perfect number.") else:

print(f"{num} is not a perfect number.")

13
27)Fibonacci series
def fibonacci(n): fib_series = [0, 1] while

len(fib_series) < n:

fib_series.append(fib_series[-1] + fib_series[-2])

return fib_series

terms = int(input("Enter the number of terms for Fibonacci series: ")) result

= fibonacci(terms) print(f"Fibonacci Series: {result}")

14
a) Python Programs on functions
# Function to add two numbers def add_numbers(a,

b):

return a + b

# Function to find the square of a number def

square_number(x):

return x ** 2 # Example usage

result = add_numbers(5, 3)

print("Sum:", result) result_square

= square_number(4) print("Square:",

result_square)

Output:

b) Programs on recursion to find the factorial of a number


# Recursive function to calculate factorial

def factorial(n): if n == 0 or n == 1:

return 1 else:

return n * factorial(n - 1)

# Example usage num = int(input("Enter

a number"))

print(f"Factorial of {num} is {factorial(num)}")

Output:

a) Python Programs on lambda function


# Lambda function to calculate the square of a number square =

lambda x: x ** 2

15
# Lambda function to check if a number is even is_even

= lambda x: x % 2 == 0

# Example usage

print("Square:", square(3))

print("Is 4 even?", is_even(4))

b) Programs on _init_function
# Class with __init__ function class

Person: def __init__(self, name,

age): self.name =

name

self.age = age

def display_details(self):

print(f"Name: {self.name}") print(f"Age:

{self.age}")

# Example usage person1 =

Person("John", 25)

person1.display_details() Output:

a) Create a class which has init function and normal def function for
displaying the details
class Student: def __init__(self, name, roll_number):

self.name = name

self.roll_number = roll_number

16
def display_details(self): print(f"Name: {self.name}, Roll

Number: {self.roll_number}")

# Example usage student1 =

Student("Alice", 101)

student1.display_details() Output:

b) Program to print star pattern


# Function to print a star pattern

def print_star_pattern(rows): for

i in range(1, rows + 1):

print("* " * i)

# Example usage print_star_pattern(5)

Output

Program on matplotlib 1) Simple plot


import matplotlib.pyplot as plt

# Simple plot x

= [1, 2, 3, 4, 5] y

= [2, 4, 6, 8, 10]

plt.plot(x, y) plt.xlabel('X-axis')

plt.ylabel('Y-axis')

17
plt.title('Simple Plot') plt.show()

Output:

2) Bar graph import


matplotlib.pyplot as plt

# Data categories = ['Category A', 'Category B', 'Category C',

'Category D'] values = [30, 50, 25, 40]

# Creating a bar graph plt.bar(categories, values,

color='skyblue')

# Adding labels and title plt.xlabel('Categories')

plt.ylabel('Values') plt.title('Bar

Graph Example')
18
# Display the bar graph

plt.show() Output:

3)Scatter Plot
import matplotlib.pyplot as plt import numpy

as np

# Generating random data for demonstration np.random.seed(42) x =

np.random.rand(20) y = 2 * x + 1 + 0.1 * np.random.randn(20) # Linear relationship

with some noise

# Creating a scatter plot plt.scatter(x, y, color='blue',

marker='o')

# Adding labels and title plt.xlabel('X-axis')

plt.ylabel('Yaxis') plt.title('Simple Scatter

Plot')

19
# Display the scatter plot

plt.show() Output:

Program on pandas
import pandas as pd

# Creating a DataFrame data =

{'Name': ['John', 'Alice', 'Bob'],

'Age': [25, 22, 30],

'City': ['New York', 'Los Angeles', 'Chicago']}

df = pd.DataFrame(data)

print(df) Output:

Program on Web scrapping using beautifulsoup


import requests from bs4

import BeautifulSoup url =

20
'https://example.com' response

= requests.get(url)

if response.status_code == 200:

soup = BeautifulSoup(response.text, 'html.parser')

# Extract information from the HTML using BeautifulSoup functions

# ...

print(response.text) else:

print(f"Error accessing the website. Status code: {response.status_code}")

Output :

Programs on scipy
import numpy as np from

scipy.linalg import solve

# Coefficient matrix

A = np.array([[2, 1], [1, -3]])


21
# Right-hand side vector b

= np.array([8, -3])

# Solve the system of linear equations

solution = solve(A, b) # Print the solution

print("Solution:", solution) Output:

Django
Installation of Django

Hello world program in Django


# hello_world_app/urls.py from django.urls import path from .views import hello_world
urlpatterns = [ path('', hello_world, name='hello_world'),
]

# hello_world_project/urls.py
from django.contrib import admin
from django.urls import include,
path urlpatterns = [
path('admin/', admin.site.urls),
path('hello/', include('hello_world_app.urls')), ]

22
Program to print date and time using Django
from django.shortcuts import render
from datetime import datetime def
current_datetime(request):
now = datetime.now() return render(request,
'myapp/current_datetime.html', {'now': now})

# myapp/urls.py from django.urls import path from .views import current_datetime


urlpatterns = [ path('current_datetime/', current_datetime,
name='current_datetime'), ]

# myproject/urls.py from django.contrib import admin from django.urls import path, include
urlpatterns = [ path('admin/', admin.site.urls), path('myapp/', include('myapp.urls
')),
]

23
Program to print time after 10hrs through dynamic URL’s using Django
from django.http import HttpResponse
from datetime import datetime, timedelta
def time_after_10_hours(request, hours):
try:
hours = int(hours)
except ValueError:
return HttpResponse("Invalid input. Please provide a valid integer.")
current_time = datetime.now() time_after_10_hours = current_time +
timedelta(hours=hours) return HttpResponse(f"Current Time:
{current_time}<br>Time After {hours} Hours: {time_after_10_hours}")

from django.urls import path from


.views import time_after_10_hours

urlpatterns = [ path('time_after_10_hours/<int:hours>/', time_after_10_hours,


name='time_after_10_hours'), ]

from django.contrib import admin from django.urls import include, path urlpatterns =
[ path('admin/', admin.site.urls), path('time_display/',
include('time_display_app.urls')), ]

24
Program to demonstrate Template in Django
from django.shortcuts import
render def hello(request):
context = {
'name': 'Vedant',
'age': 21,
} return render(request, 'myapp/hello.html',
context)

<!DOCTYPE html>
<html>
<head>
<title>Hello Template</title>
</head>
<body>
<h1>Hello, {{ name }}!</h1>
<p>You are {{ age }} years old.</p>
</body>
</html>

from django.contrib import admin from django.urls import path from myapp.views import
hello urlpatterns = [ path('admin/', admin.site.urls), path('hello/', hello,
name='hello'),
]
# http://127.0.0.1:8000/hello/

25
Creating Django admin interface
# models.py from
django.db import
models class
YourModel(models.Model): field1 =
models.CharField(max_length=100) field2
= models.IntegerField() def
__str__(self):
return self.field1

# admin.py from django.contrib


import admin from .models
import YourModel
admin.site.register(YourModel)
from django.contrib import
admin from django.urls import
path urlpatterns =
[ path('admin/', admin.site.urls),
]

26
python manage.py createsuperuser

27
Creating Django Models
# myapp/views.py from
django.shortcuts import
render from .models import
Book def book_list(request):
books = Book.objects.all() return render(request,
'myapp/book_list.html', {'books': books})

# myapp/urls.py from
django.urls import path
from .views import
book_list urlpatterns
=
[ path('books/', book_list,
name='book_list'), ]

28
# myproject/urls.py from django.contrib import admin from django.urls import path, include
urlpatterns = [ path('admin/',
admin.site.urls), path('',
include('myapp.urls')),
]

29
CRUD operations on models
from django.shortcuts import render, redirect
from employee.forms import EmployeeForm
from employee.models import Employee #
Create your views here. def emp(request):
if request.method == "POST":
form =
EmployeeForm(request.POST) if
form.is_valid(): try:
form.save() return
redirect('/show') except:
pass else:
form = EmployeeForm() return
render(request,'index.html',{'form':form}) def
show(request):
employees = Employee.objects.all() return
render(request,"show.html",{'employees':employees}) def
edit(request, id):
employee = Employee.objects.get(id=id) return
render(request,'edit.html', {'employee':employee}) def
update(request, id):
employee = Employee.objects.get(id=id) form =
EmployeeForm(request.POST, instance = employee) if
form.is_valid():
form.save() return redirect("/show")
return render(request, 'edit.html', {'employee': employee})
def destroy(request, id):
employee =
Employee.objects.get(id=id)
employee.delete() return
redirect("/show")

from django.db import models


class Employee(models.Model):
eid =
models.CharField(max_length=20)
ename =
models.CharField(max_length=100) eemail
= models.EmailField() econtact =
models.CharField(max_length=15)
class Meta: db_table =
"employee"

from django import forms from


employee.models import Employee
class
EmployeeForm(forms.ModelForm):
class Meta:
30
model = Employee fields
= "__all__"

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Index</title>
{% load static %}
<link rel="stylesheet" href="{% static 'css/style.css %}"/>
</head>
<body>
<form method="POST" class="post-form" action="/emp">
{% csrf_token %}
<div class="container">
<br>
<div class="form-group row">
<label class="col-sm-1 col-form-label"></label>
<div class="col-sm-4">
<h3>Enter Details</h3>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Employee Id:</label>
<div class="col-sm-4">
{{ form.eid }}
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Employee Name:</label>
<div class="col-sm-4">
{{ form.ename }}
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Employee Email:</label>
<div class="col-sm-4">
{{ form.eemail }}
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Employee Contact:</label>
<div class="col-sm-4">
{{ form.econtact }}
</div>
</div>
<div class="form-group row">
<label class="col-sm-1 col-form-label"></label>
<div class="col-sm-4">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</div>
</form>
</body>
31
</html>

from django.contrib import admin from django.urls import path from employee import views
urlpatterns = [ path('admin/', admin.site.urls), path('emp', views.emp) ,
path('show',views.show), path('edit/<int:id>', views.edit), path('update/<int:id>',
views.update), path('delete/<int:id>', views.destroy), ]

32
Kivy
Step 1: Update the pip and wheel before installing kivy

by entering this command in cmd

Step 2: Install the dependencies

33
Kivy Installation

Kivy Programs Creating simple hello world program


from kivy.app import App from kivy.uix.button import Button class MyApp(App): def
build(self): return Button(text='Hello Adarh!') if __name__ == '__main__':
MyApp().run()

34
Kivy Program to display Image widget
from kivy.app import App from
kivy.uix.image import Image class
ImageApp(App): def build(self):
img = Image(source='Adarsh logo.png')
return img if __name__ == '__main__':
ImageApp().run()

35
Kivy Program to create Button
from kivy.app import App from
kivy.uix.button import Button
class
ButtonApp(App):
def build(self):
button = Button(text='Click
Me!',
size_hint=(None, None),
size=(200, 100),
pos=(300, 200),
on_press=self.on_button_press) return
button

36
def on_button_press(self, instance):
print("Button
Pressed!") if __name__ ==
'__main__':
ButtonApp().run()

37
Kivy Program to display Label and checkboxes
from kivy.app import App from kivy.uix.boxlayout import BoxLayout from
kivy.uix.label import Label from kivy.uix.checkbox import CheckBox

38
class CheckBoxApp(App):
def build(self):
# Create a BoxLayout to hold the widgets vertically
layout = BoxLayout(orientation='vertical', spacing=10, padding=10)
# Create a Label widget label
= Label(text='This is a Label')

# Create two CheckBox widgets checkbox1 =


CheckBox(active=False, on_active=self.on_checkbox_active) checkbox2
= CheckBox(active=True, on_active=self.on_checkbox_active)
# Add the widgets to the layout
layout.add_widget(label)
layout.add_widget(checkbox1)
layout.add_widget(checkbox2) return layout
def on_checkbox_active(self, instance, value):
checkbox_text = "Checkbox 1" if instance == checkbox1 else "Checkbox 2"
checkbox_state = "activated" if value else "deactivated" print(f"{checkbox_text}
is {checkbox_state}") if __name__ == '__main__':
CheckBoxApp().run()

39

You might also like