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

Kshitij Python

The document contains code snippets from multiple Python programs and experiments. Some key points: 1. There are examples of Python data types like integers, floats, strings, lists, tuples, sets and dictionaries being initialized and printed. 2. String operations like concatenation, repetition and slicing are demonstrated. List, tuple, set and dictionary operations are also shown. 3. Classes and objects are defined to represent employees and students with methods to display data. 4. Functions are defined to calculate factorials and demonstrate parameter passing in classes. 5. Modules like NumPy, Pandas, Tkinter and socket are imported and used for tasks like generating random data, creating DataFrames and building a basic GUI and client

Uploaded by

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

Kshitij Python

The document contains code snippets from multiple Python programs and experiments. Some key points: 1. There are examples of Python data types like integers, floats, strings, lists, tuples, sets and dictionaries being initialized and printed. 2. String operations like concatenation, repetition and slicing are demonstrated. List, tuple, set and dictionary operations are also shown. 3. Classes and objects are defined to represent employees and students with methods to display data. 4. Functions are defined to calculate factorials and demonstrate parameter passing in classes. 5. Modules like NumPy, Pandas, Tkinter and socket are imported and used for tasks like generating random data, creating DataFrames and building a basic GUI and client

Uploaded by

Dhruv Shah
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 23

EXP – 1 a)

Program:
a = 20
b = 3.456
c = 'Hello'
d = 3+5j
list1 = [10, 20, 30, 40, 'KSK', '@%#&']
tup = (10, 20, 'ksk')
set1 = {10, 20, 30, 40, 50}
dict = {
'rollno': 7,
'Name': 'Kshitij'
}
print(type(a))
print(type(b))
print(type(c))
print(type(d))
print(type(list1))
print(type(tup))
print(type(set1))
print(type(dict))
print("Integer Number : ", a)
print("Float Number : ", b)
print("String value is : ", c)
print("Complex number is : ", d)
print("List is : ", list1)
print("Tuple is : ", tup)
print("Set is : ", set1)
print("Dictionary is : ", dict)
print("\n")
#String
x = 'Kshitij'
y = 'Karkera'
print(x + y) #Concatination
print(1 * x) #Repeation
print(x[0])
print(list1[3])
print(tup[2]) #Indexing
print(tup[-2])
print(x[1:4])
print(x[1:])
print(list1[1:3]) #Slicing
print(tup[1:3])
print("\n")

#Set operations
set2 = {10, 20, 30, 40, 50}
print(set2)
s = set("Kshitij") #Set function used to create set
s.update([80, 90])
print(s)
s.remove(90)
print(s)
fs = frozenset(set2)
print(fs)
print("\n")
#List operations
L1 = list(range(10, 60, 10))
print(L1)
print("Length of the list : ", len(L1))
list1.append(9)
print(list1)
list1.remove(40)
print(list1)
list1.reverse()
print(list1)
print(L1 + list1)
print(list1 * 2)
i = 10
print(i in list1)
#Dictionary operartions
dict1 = {
'Rollno': 7,
'Name': "Kshitij Karkera"
}
print(type(dict1))
print(len(dict1))
dict1['marks'] = 95
print(dict1)
del dict1['marks']
print(dict1)

Output:
EXP – 1 b)
Program:
num = int(input('Enter a number : '))
fact = 1
i=1
if num < 0:
print("Factorial of negative number does bot exist")
elif num == 0:
print("The factorial of 0 is 1")
else:
for i in range(i, num + 1):
fact = fact * i
print("The factorial of ", num, " is ", fact)

Output:
EXP – 2 a)
Program:
class Employee:
empCount = 0
def __init__(self, name, salary):
self.name = name
self.salary = salary
Employee.empCount += 1
def displayCount(self):
print('Total employee : ', Employee.empCount)
def displayEmployee(self):
print("Name : ", self.name, "\nSalary : ", self.salary, "\n")
emp1 = Employee("Kshitij", 100000)
emp2 = Employee("Ketan", 200000)
emp1.displayEmployee()
emp2.displayEmployee()
print("Total number of employees are ", Employee.empCount)

Output:
EXP – 2 b)
Program:
class Person:
def __init__(self, fname,lname):
self.firstname=fname
self.lastname=lname

def printname(self):
print(self.firstname,self.lastname)

class Student(Person):
def __init__(self, fname, lname):
Person.__init__(self,fname,lname)

x = Student("Kshitij", "Karkera")
x.printname()

Output:
EXP – 3
Program:
import os
f = open("abc.txt", "x")
f = open("abc.txt", "w")
f.write("KSHITIJ\nRoll No 7\nSubject Python Lab\nSE DSE")
f.close()
f = open("abc.txt","r")
print(f.read())
f = open("abc.txt", "r")
lines = len(f.readlines())
print("Total Number of Lines: ", lines)
f = open("abc.txt", "r")
read_data = f.read()
words = read_data.split()
print("Total Number of Words: ", len(words))
f = open("abc.txt", "r")
no_of_char = len(read_data)
print("Total Number of Charaters: ", no_of_char)
search_word_count = "Python"
word_count = read_data.count(search_word_count)
print(f"The word {search_word_count} appeared {word_count} times")
path = "C://Users//Kshitij//OneDrive//Desktop"
dir_list = os.listdir(path)
print("Files & Directories in ", path,":")
print(dir_list)
Output:
EXP – 4
Program:
class Node:
def __init__(self, data):
self.data = data
self.next = None
class Stack:
def __init__(self):
self.head = None
def push (self, data):
if self.head is None:
self.head = Node (data)
else:
new_node = Node(data)
new_node.next = self.head
self.head = new_node
def pop (self):
if self.head is None:
return None
else:
popped = self.head.data
self.head = self.head.next
return popped

a_stack = Stack()
while True:
print('Push <Values>')
print('Pop')
print('Quit')
do = input('Mention operation: ').split()
print()
operation = do[0].strip().lower()
if operation == 'push' or operation == 'Push' or operation == 'PUSH':
a_stack.push(int(do[1]))
elif operation =='pop' or operation == 'Pop' or operation == 'POP':
popped = a_stack.pop()
if popped is None:
print ('Stack is empty.')
print()
else:
print('Popped value: ', int(popped))
print()
elif operation == 'quit' or operation == 'Quit' or operation == 'QUIT':
break
Output:
EXP – 5/6
Program:
import numpy as np
x = np.random.randint(high =100,low=12,size=(15,))
print(x)
x.sort
print(x)
arr=np.array([10,15,20,25,50,16])
x=arr.view()
c=arr.copy()
print("ID of arr",id(arr))
print("ID of x",id(x))
arr[0]=12
print("Original array:",arr)
print("View:",x)
print("Copy:",c)
print(c.base)
c=arr.copy()
print(x.base)

Output:
EXP – 7
Program:
import random
import pandas as pd
import numpy as np
a = ["RollNo", "Name", "IEN", "Dept", "Year"]
series = pd.Series(a)
print(series)
Name = np.random.choice(["Name1", "Name2", "Name3", "Name4", "Name5",
"Name6", "Name7",
"Name8", "Name9", "Name10"], 20)
Age = np.random.randint(low = 16, high = 20, size = [20,])
Dept = np.random.choice(["COMP", "AIDS","CSD"],20)
Year = np.random.choice(["SE","TE","BE"],20)
Div = np.random.choice(["a","b","c"],20)
studentdata = list(zip(Dept, Name, Age, Year, Div))
print(studentdata)
df = pd.DataFrame(studentdata,
columns=["COMP","KSHITIJ","7","SE","C"])
df.shape
df.head()
df.columns
df.dtypes
df.info()
df1 = df.iloc[3:7, 1:5]
df1
Output:
EXP – 8
Program:
import tkinter as tk
root=tk.Tk()
root.geometry("400x300")
root.title('KSHITIJ')
L1=tk.Label(root,text='Click at different location in frame')
L1.pack()
def callback(event):
print('Clicked at x:', event.x,"y:",event.y)
F1=tk.Frame(root,bg='red',width=250,height=100)
F1.bind("<Button-1>", callback )
F1.pack()
B1=tk.Button(root,text='Exit',width=25,command=root.destroy)
B1.pack(side='right')
root.mainloop()

Output:
EXP – 9
Program:
import socket
s = socket.socket()
print ("Socket successfully created")
port = 12345
s.bind(('', port))
print ("socket binded to %s" %(port))
s.listen(5)
print ("socket is listening")
while True:
c, addr = s.accept()
print ('Got connection from', addr)
c.send('Thank you for connecting'.encode())
c.close()
break

Output:
EXP – 10
Program:
Urls.py –
from django.contrib import admin
from django.urls import path, include
from main import views as user_view
from django.contrib.auth import views as auth

urlpatterns = [
path('admin/', admin.site.urls),
path('', include('main.urls')),
path('login/', user_view.Login, name ='login'),
path('logout/', auth.LogoutView.as_view(template_name
='user/index.html'), name ='logout'),
path('register/', user_view.register, name ='register')
]

Views.py –
import smtplib
from django.shortcuts import render, redirect
from django.contrib import messages
from django.contrib.auth import authenticate, login
from django.contrib.auth.decorators import login_required
from django.contrib.auth.forms import AuthenticationForm,
UserCreationForm
from django.core.mail import send_mail
from django.core.mail import EmailMultiAlternatives
from django.template.loader import get_template
from django.template import Context
from django.contrib.auth.models import User
from django import forms

def index(request):
return render(request, 'user/index.html', {'title':'index'})

def register(request):
if request.method == 'POST':
form = UserRegisterForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
email = form.cleaned_data.get('email')
htmly = get_template('user/Email.html')
d = { 'username': username }
subject, from_email, to = 'welcome',
'[email protected]', email
html_content = htmly.render(d)
msg = EmailMultiAlternatives(subject, html_content,
from_email, [to])
msg.attach_alternative(html_content, "text/html")
msg.send()
messages.success(request, f'Your account has been
created ! You are now able to log in')
return redirect('login')
else:
form = UserRegisterForm()
return render(request, 'user/register.html', {'form': form,
'title':'register here'})

def Login(request):
form = ''
username = ''
password = ''

if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
user = authenticate(request, username = username, password
= password)
if user is not None:
form = login(request, user)
messages.success(request, f' welcome {username} !!')
return redirect('index')
else:
messages.info(request, f'account done not exit plz sign in')
form = AuthenticationForm()
return render(request, 'main/index.html', {'form':form,
'title':'log in'})

class UserRegisterForm(UserCreationForm):
email = forms.EmailField()
phone_no = forms.CharField(max_length = 20)
first_name = forms.CharField(max_length = 20)
last_name = forms.CharField(max_length = 20)

class Meta:
model = User
fields = ['username', 'email', 'phone_no', 'password1',
'password2']

Output:
EXP – 11
Program:
import smtplib, ssl
port = 465
smtp_server = "smtp.gmail.com"
sender_email = "[email protected]"
receiver_email = "[email protected]"
password = input("Type your password and press enter: ")
message = "Subject: Hi there, This message is sent from Python."
context = ssl.create_default_context()
with smtplib.SMTP_SSL(smtp_server, port, context=context) as server:
server.login(sender_email, password)
server.sendmail(sender_email, receiver_email, message)

Output:
EXP – 12
Program:
import threading

def cube(edge):
print("Surface Area of the Cube: {}".format(6*edge*edge))

def square(side):
print("\nThe area of the Square: {}".format(side*side))

if __name__ == "__main__":
t1 = threading.Thread(target=square, args = (int(input("Enter the Side of the
Square: ")),))
t2 = threading.Thread(target=cube, args = (int(input("Enter the Edge of the
Cube: ")),))

t1.start()
t2.start()
t1.join()
t2.join()

Output:

You might also like