Practical 1: AIM: Installation of Configuration of Python. Along With Its All Major Editors
Practical 1: AIM: Installation of Configuration of Python. Along With Its All Major Editors
PRACTICAL 1
AIM: Installation of Configuration of Python. Along with its all major editors
Installing Python
Run the installer, and let it install to the default location: in this
case, C:\Python32\.
1
CE376: PROGRAMMING IN PYTHON (Elective-II) 16CE068
Lastly, you'll need a text editor. There are many good options, but I
suggest Sublime Text: it's very powerful and useful, and it has an
unlimited free trial. Please note that Microsoft Word is a word processor,
not a text editor: you cannot use Microsoft Word for writing computer
programs.
2
CE376: PROGRAMMING IN PYTHON (Elective-II) 16CE068
but you can try it for as long as you like before you buy it. If you end up
writing many programs using Sublime Text, I encourage you to buy a
license.
Now that you're all set up, let's verify that everything is working properly!
The first program that any programmer writes is called "Hello, World!",
and all it does is write that text out to the terminal. So, let's write "Hello,
World!" in Python! If your computer is set up properly, this should work
properly:
3
CE376: PROGRAMMING IN PYTHON (Elective-II) 16CE068
PRACTICAL 2
a) Create a program that asks the user to enter their name and their
age. Print out a message addressed to them that tells them the year
that they will turn 100 years old.
Code:
from datetime import datetime
class user:
def __init__(self,name,age):
self.name=name
self.age=age
Output:
4
CE376: PROGRAMMING IN PYTHON (Elective-II) 16CE068
Code:
x=input("enter a number")
if int(x)%2==0:
print("the number is even")
else:
print("number is odd")
Output:
c) Take a list, say for example this one: a = [1, 1, 2, 3, 5, 8, 13, 21, 34,
55, 89] and write a program that prints out all the elements of the list
that are less
than 5.
Code:
a=[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
for i in a:
if(i<5):
print(i)
Output:
5
CE376: PROGRAMMING IN PYTHON (Elective-II) 16CE068
PRACTICAL 3
a) Create a program that asks the user for a number and then prints
out a list of all the divisors of that number. (If you don’t know what a
divisor is, it is a number that divides evenly into another number. For
example, 13 is a divisor of 26 because 26 / 13 has no remainder.)
Code:
x=int(input("enter a number:"))
for i in range(1,int(x/2)+1):
if(x%i==0):
print(i)
print(x)
Output:
6
CE376: PROGRAMMING IN PYTHON (Elective-II) 16CE068
Output:
c) Ask the user for a string and print out whether this string is a
palindrome or not. (A palindrome is a string that reads the same
forwards and backwards.)
Code:
x=input("enter a string:")
y=x[::-1]
if(x==y):
print("the given string is palindrome")
else:
print("not a palindrome")
Output:
7
CE376: PROGRAMMING IN PYTHON (Elective-II) 16CE068
d) Let’s say I give you a list saved in a variable: a = [1, 4, 9, 16, 25, 36,
49, 64, 81, 100]. Write one line of Python that takes this list a and
makes a new list that has only the even elements of this list in it.
Code:
a = [1, 4, 9, 16, 25, 36, 49, 64,81, 100]
b = [x for x in a if x%2==0]
print(b)
Output:
8
CE376: PROGRAMMING IN PYTHON (Elective-II) 16CE068
PRACTICAL 4
a) Make a two-player Rock-Paper-Scissors game. (Hint: Ask for
player plays (using input), compare them, print out a message of
congratulations to the winner, and ask if the players want to start a
new game)
Code:
def func (k,l):
if(k=="ROCK" and l=="SCISSOR")or(k==("SCISSOR")and
l==("PAPER"))or(k==("PAPER")and l==("ROCK")):
return True
else:
return False
a=x.upper()
b=y.upper()
elif a==b:
print("it's a tie")
elif func(a,b):
9
CE376: PROGRAMMING IN PYTHON (Elective-II) 16CE068
print("Player A wins")
else:
print("Player B wins")
Output:
10
CE376: PROGRAMMING IN PYTHON (Elective-II) 16CE068
Code:
import random
x=random.randrange(1,10)
i=0;
flag=True
while(flag and (i<10)):
print(str(10-i)+" chances remaining")
i=i+1
y=input("enter a number:")
if (int(y)==x):
flag=False;
print("you made correct guess CONGRATULATION")
elif(int(y)>x):
print("you have guessed too high, try lower
number")
else:
print("you have guessed too low, try greater
number")
Output:
11
CE376: PROGRAMMING IN PYTHON (Elective-II) 16CE068
PRACTICAL 5
a) This week’s exercise is going to be revisiting an old exercise (see
Practical 2), except require the solution in a different way.
Take two lists, say for example these two: a = [1, 1, 2, 3, 5, 8, 13, 21,
34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
and write a program that returns a list that contains only the
elements that are common between the lists (without duplicates).
Make sure your program works on two lists of different sizes. Write
this in one line of Python using at least one list comprehension
Code:
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
print(set(i for i in a for j in b if i==j))
"""LIST COMPREHENSIVE """
Output:
12
CE376: PROGRAMMING IN PYTHON (Elective-II) 16CE068
b) Ask the user for a number and determine whether the number is
prime or not. (For those who have forgotten, a prime number is a
number that has no divisors.). You can (and should!) use your
answer to Practical 2 to help you.
Take this opportunity to practice using functions, described below.
Code:
x=input("enter a number")
flag=True
if flag==True:
print("x is a prime number")
else:
print("x is not a prime number")
Output:
13
CE376: PROGRAMMING IN PYTHON (Elective-II) 16CE068
Code:
def firstandlast(x):
return([x[0],x[len(x)-1]])
a = [5, 10, 15, 20,25]
print(firstandlast(a))
Output:
14
CE376: PROGRAMMING IN PYTHON (Elective-II) 16CE068
PRACTICAL 6
a) Write a program that asks the user how many Fibonnaci numbers
to generate and then generates them. Take this opportunity to think
about how you can use functions. Make sure to ask the user to enter
the number of numbers in the sequence to generate.(Hint: The
Fibonnaci seqence is a sequence of numbers where the next
number in the sequence is the sum of the previous two numbers in
the sequence. The sequence looks like this: 1, 1, 2, 3, 5, 8, 13, …)
Code:
def fib(a,b,n):
c=a+b
print(c,end=" ")
if(n>0):
fib(b,c,n-1)
Output:
15
CE376: PROGRAMMING IN PYTHON (Elective-II) 16CE068
b) Write a program (function!) that takes a list and returns a new list
that contains all the elements of the first list minus all the
duplicates.
Code:
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
customlist = set(i for i in a for j in b if i==j)
print(customlist)
Output:
c) Write a program (using functions!) that asks the user for a long
string containing multiple words. Print back to the user the same
string, except with the words in backwards order. For example, say
I type the string:
My name is Michele
Then I would see the string:
Michele is name My shown back to me.
Code:
def reverse(s):
y=s.split()
k=""
for i in reversed(y):
k=k+(i+" ")
return k
16
CE376: PROGRAMMING IN PYTHON (Elective-II) 16CE068
Output:
Code:
import string
from random import *
characters = string.ascii_letters + string.punctuation
+ string.digits
password = "".join(choice(characters) for x in
range(randint(8, 16)))
print(password)
Output:
17
CE376: PROGRAMMING IN PYTHON (Elective-II) 16CE068
Code:
result=requests.get("http://www.charusat.ac.in")
print(result.status_code)
print(result)
c=result.content
soup=BeautifulSoup(c,features="lxml")
#print (soup.prettify())
for link in soup.find_all('a'):
print(link.get('href'))
Output:
18
CE376: PROGRAMMING IN PYTHON (Elective-II) 16CE068
PRACTICAL 7
a) Create a program that will play the “cows and bulls” game with
the user. The game works like this:
19
CE376: PROGRAMMING IN PYTHON (Elective-II) 16CE068
count=0
if(firstdigit==firstdigitguessed):
count+=1
if(seconddigit==seconddigitguessed):
count+=1
if(thirddigit==thirddigitguessed):
count+=1
if(fourthdigit==fourthdigitguessed):
count+=1
return count
flag=True
while flag:
x=int(input("enter a guess of four digit "))
c=numberofmatch(randomnumber,x)
print("{} cows,{} bulls".format(c,4-c))
if(c==4):
flag=False
print("congratulation you guessed correctly.")
Output:
20
CE376: PROGRAMMING IN PYTHON (Elective-II) 16CE068
PRACTICAL 8
a) Using the requests and BeautifulSoup Python libraries, print to
the screen the full text of the article on this website:
http://www.vanityfair. com/society/2014/06/monica-lewinsky-
humiliation-culture.
Code:
import requests
from bs4 import BeautifulSoup
import codecs
import textwrap
def get_web_page(url):
r = requests.get(url)
return r.text
url =
'http://www.vanityfair.com/society/2014/06/monica-
lewinsky-humiliation-culture'
21
CE376: PROGRAMMING IN PYTHON (Elective-II) 16CE068
fileName = 'VanityFair.txt'
html_fileName = 'VanityFair_html.txt'
FormattedFileName = 'VanityFair_Formatted.txt'
html = get_web_page(url)
soup = BeautifulSoup(html, 'html.parser',
from_encoding='utf-8')
article = soup.find_all(class_="content-section")
Output:
22
CE376: PROGRAMMING IN PYTHON (Elective-II) 16CE068
Code:
def contains(x,y):
for i in x:
if(i==y):
return True
return False
Output:
23
CE376: PROGRAMMING IN PYTHON (Elective-II) 16CE068
PRACTICAL 9
a) Take the code from the How To Decode A Website exercise , and
instead of printing the results to a screen, write the results to a txt
file. In your code, just make up a name for the file you are saving to.
Code:
from bs4 import BeautifulSoup as soup
import requests
import re
my_url = 'https://www.nytimes.com'
# html parsing
page_soup = soup(page_html, 'html.parser')
open_file.close()
24
CE376: PROGRAMMING IN PYTHON (Elective-II) 16CE068
Output:
b) Given a .txt file that has a list of a bunch of names, count how
many of each name there are in the file, and print out the results to
the screen.
Code:
count=dict()
with open("jainil",'r') as f:
x=f.read()
y=x.split()
for i in y:
count[i]=0
for i in y:
count[i]+=1
print(count)
Output:
25
CE376: PROGRAMMING IN PYTHON (Elective-II) 16CE068
PRACTICAL 10
a) Develop programs to understand the control structures of python
Code:
for i in range(10):
print(i)
if(i==2):
continue
if(i==8):
break
else:
pass
print("loop complete")
print()
print()
k=0
while True:
k+=1
print(k)
if(k==3):
continue
elif(k==5):
pass
elif(k==9):
break
print("loop complete")
Output:
26
CE376: PROGRAMMING IN PYTHON (Elective-II) 16CE068
27
CE376: PROGRAMMING IN PYTHON (Elective-II) 16CE068
if "apple" in thistuple:
print("Yes, 'apple' is in the fruits tuple")
print(len(thistuple))
thistuple = tuple(("apple", "banana", "cherry")) # note
the double round-brackets
print(thistuple)
thisset = {"apple", "banana", "cherry"}
print(thisset)
for x in thisset:
print(x)
thisset = {"apple", "banana", "cherry"}
print("banana" in thisset)
thisset.add("orange")
print(thisset)
thisset.update(["orange", "mango", "grapes"])
print(thisset)
print(len(thisset))
thisset.remove("banana")
print(thisset)
thisset.discard("banana")
print(thisset)
thisset = {"apple", "banana", "cherry"}
x = thisset.pop()
print(x)
print(thisset)
thisset.clear()
print(thisset)
thisset = set(("apple", "banana", "cherry")) # note the
double round-brackets
print(thisset)
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
x = thisdict["model"]
28
CE376: PROGRAMMING IN PYTHON (Elective-II) 16CE068
thisdict["year"] = 2018
for x in thisdict:
print(x)
for x in thisdict:
print(thisdict[x])
for x in thisdict.values():
print(x)
for x, y in thisdict.items():
print(x, y)
if "model" in thisdict:
print("Yes, 'model' is one of the keys in the
thisdict dictionary")
print(len(thisdict))
thisdict["color"] = "red"
print(thisdict)
thisdict.pop("model")
print(thisdict)
Output:
29
CE376: PROGRAMMING IN PYTHON (Elective-II) 16CE068
l.append(n)
n+=1
a(n)
return l
else:
return
print(a(1))
30
CE376: PROGRAMMING IN PYTHON (Elective-II) 16CE068
Output:
31
CE376: PROGRAMMING IN PYTHON (Elective-II) 16CE068
PRACTICAL 11
a) Develop programs to understand working of exception handling
and assertions.
Code:
try:
fh = open("testfile", "r")
fh.write("This is my test file for
exception handling!!")
except IOError:
print("\nError: can\'t find file or read
data")
else:
print("Written content in the file
successfully")
def KelvinToFahrenheit(Temperature):
assert (Temperature >= 0), "Colder than
absolute zero!"
return ((Temperature - 273) * 1.8) + 32
print(KelvinToFahrenheit(273))
print(int((KelvinToFahrenheit(505.78))))
print(KelvinToFahrenheit(-5))
32
CE376: PROGRAMMING IN PYTHON (Elective-II) 16CE068
Output:
return search_res
33
CE376: PROGRAMMING IN PYTHON (Elective-II) 16CE068
# SORTING
def mergeSort(arr):
if len(arr) > 1:
mid = len(arr) // 2 # Finding the mid
of the array
L = arr[:mid] # Dividing the array
elements
R = arr[mid:] # into 2 halves
i = j = k = 0
34
CE376: PROGRAMMING IN PYTHON (Elective-II) 16CE068
arr[k] = L[i]
i += 1
k += 1
# HASHTABLE
hash_table = [[] for _ in range(10)]
print(hash_table)
def hashing_func(key):
return key % len(hash_table)
35
CE376: PROGRAMMING IN PYTHON (Elective-II) 16CE068
print("1.insert")
print("2.view")
while (True):
choice = int(input())
if (choice == 1):
print("enter data")
data = int(input())
key = hashing_func(data)
insert(hash_table, key, data)
if (choice == 2):
print(hash_table)
Output:
36
CE376: PROGRAMMING IN PYTHON (Elective-II) 16CE068
def get_book(url):
# Sends a http request to get the text from
project Gutenberg
raw = requests.get(url).text
# Discards the metadata from the beginning
of the book
start = re.search(r"\*\*\* START OF THIS
PROJECT GUTENBERG EBOOK .* \*\*\*",raw ).end()
# Discards the metadata from the end of the
book
stop = re.search(r"II", raw).start()
# Keeps the relevant text
text = raw[start:stop]
return text
def preprocess(sentence):
return re.sub('[^A-Za-z0-9.]+' , ' ',
sentence).lower()
book = get_book(the_idiot_url)
processed_book = preprocess(book)
print("our book")
print(processed_book)
processed_book)
print(processed_book)
print("words with -- in the middle")
print(re.findall(r'[a-zA-Z0-9]*--[a-zA-Z0-9]*',
book))
print("counting no of words")
print(len(re.split(" ",processed_book)))
Output:
38
CE376: PROGRAMMING IN PYTHON (Elective-II) 16CE068
PRACTICAL 12
a) Learn to plot different types of graphs using PyPlot.
Code:
import pandas as pd
import matplotlib.pyplot as plt
# show plot
plt.show()
df.plot.bar()
df.plot.box()
40
CE376: PROGRAMMING IN PYTHON (Elective-II) 16CE068
41
CE376: PROGRAMMING IN PYTHON (Elective-II) 16CE068
Output:
42
CE376: PROGRAMMING IN PYTHON (Elective-II) 16CE068
Output:
CONCLUSION :
In this practical we learned different ciphers and how to encrypt them.
43
CE376: PROGRAMMING IN PYTHON (Elective-II) 16CE068
PRACTICAL 13
a) Draw graphics using Turtle.
Code:
import turtle
ninja = turtle.Turtle()
ninja.speed(10)
for i in range(180):
ninja.forward(100)
ninja.right(30)
ninja.forward(20)
ninja.left(60)
ninja.forward(50)
ninja.right(30)
ninja.penup()
ninja.setposition(0, 0)
ninja.pendown()
ninja.right(2)
turtle.done()
44
CE376: PROGRAMMING IN PYTHON (Elective-II) 16CE068
Output:
def register():
global register_screen
register_screen = Toplevel(main_screen)
register_screen.title("Register")
register_screen.geometry("300x250")
45
CE376: PROGRAMMING IN PYTHON (Elective-II) 16CE068
global username
global password
global username_entry
global password_entry
username = StringVar()
password = StringVar()
def login():
global login_screen
login_screen = Toplevel(main_screen)
login_screen.title("Login")
46
CE376: PROGRAMMING IN PYTHON (Elective-II) 16CE068
login_screen.geometry("300x250")
Label(login_screen, text="Please enter
details below to login").pack()
Label(login_screen, text="").pack()
global username_verify
global password_verify
username_verify = StringVar()
password_verify = StringVar()
global username_login_entry
global password_login_entry
Label(login_screen, text="Username *
").pack()
username_login_entry = Entry(login_screen,
textvariable=username_verify)
username_login_entry.pack()
Label(login_screen, text="").pack()
Label(login_screen, text="Password *
").pack()
password_login_entry = Entry(login_screen,
textvariable=password_verify, show='*')
password_login_entry.pack()
Label(login_screen, text="").pack()
Button(login_screen, text="Login",
width=10, height=1,
command=login_verify).pack()
def register_user():
47
CE376: PROGRAMMING IN PYTHON (Elective-II) 16CE068
username_info = username.get()
password_info = password.get()
username_entry.delete(0, END)
password_entry.delete(0, END)
Label(register_screen, text="Registration
Success", fg="green", font=("calibri",
11)).pack()
def login_verify():
username1 = username_verify.get()
password1 = password_verify.get()
username_login_entry.delete(0, END)
password_login_entry.delete(0, END)
list_of_files = os.listdir()
if username1 in list_of_files:
file1 = open(username1, "r")
verify = file1.read().splitlines()
if password1 in verify:
login_sucess()
else:
password_not_recognised()
48
CE376: PROGRAMMING IN PYTHON (Elective-II) 16CE068
else:
user_not_found()
def login_sucess():
global login_success_screen
login_success_screen =
Toplevel(login_screen)
login_success_screen.title("Success")
login_success_screen.geometry("150x100")
Label(login_success_screen, text="Login
Success").pack()
Button(login_success_screen, text="OK",
command=delete_login_success).pack()
def password_not_recognised():
global password_not_recog_screen
password_not_recog_screen =
Toplevel(login_screen)
password_not_recog_screen.title("Success")
password_not_recog_screen.geometry("150x100")
Label(password_not_recog_screen,
text="Invalid Password ").pack()
Button(password_not_recog_screen,
text="OK",
command=delete_password_not_recognised).pack()
49
CE376: PROGRAMMING IN PYTHON (Elective-II) 16CE068
def user_not_found():
global user_not_found_screen
user_not_found_screen =
Toplevel(login_screen)
user_not_found_screen.title("Success")
user_not_found_screen.geometry("150x100")
Label(user_not_found_screen, text="User Not
Found").pack()
Button(user_not_found_screen, text="OK",
command=delete_user_not_found_screen).pack()
# Deleting popups
def delete_login_success():
login_success_screen.destroy()
def delete_password_not_recognised():
password_not_recog_screen.destroy()
def delete_user_not_found_screen():
user_not_found_screen.destroy()
def main_account_screen():
global main_screen
main_screen = Tk()
main_screen.geometry("300x250")
50
CE376: PROGRAMMING IN PYTHON (Elective-II) 16CE068
main_screen.title("Account Login")
Label(text="Select Your Choice", bg="blue",
width="300", height="2", font=("Calibri",
13)).pack()
Label(text="").pack()
Button(text="Login", height="2",
width="30", command=login).pack()
Label(text="").pack()
Button(text="Register", height="2",
width="30", command=register).pack()
main_screen.mainloop()
main_account_screen()
Output:
51
CE376: PROGRAMMING IN PYTHON (Elective-II) 16CE068
CONCLUSION :
In this practical we learned different concepts about tkinter and turtle.
52
CE376: PROGRAMMING IN PYTHON (Elective-II) 16CE068
PRACTICAL 14
Implement the following : Django Framework
WHAT IS DJANGO?
Django is a free and open source web application framework written in Python. A
framework is nothing more than a collection of modules that make development easier.
They are grouped together, and allow you to create applications or websites from an
existing source, instead of from scratch. Django offers a big collection of modules which you
can use in your own projects. Primarily, frameworks exist to save developers a lot of
wasted time and headaches and Django is no different.
WHY DJANGO?
Django is a Web framework written in Python.A Web framework is a software that
supports the development of dynamic Web sites, applications, and services. It provides a
set of tools and functionalities that solves many common problems associated with Web
development, such as security features, database access, sessions, template processing,
URL routing, internationalization, localization, and much more.
INSTALLATION
The basic setup consists of installing Python, Virtualenv, and Django.In the Command
Prompt, execute the command below:
pip install virtualenv
mkdir myproject
cd myproject
virtualenv venv
Our virtual environment is created. Now before we start using it, we need to activate:
venv\Scripts\activate
venv\Scripts\deactivate.bat
53
CE376: PROGRAMMING IN PYTHON (Elective-II) 16CE068
INSTALLNG VIRTUALENV
In the Command Prompt, execute the command below:
pip install virtualenv
INSTALLING DJANGO
pip install django
54