DE With Python
DE With Python
INDEX
[Link]. Name of the program [Link].
1. Installing Anaconda Python Distribution
3 Conditional Statements
A) Write A Program To Find The Largest Of Three Integers Using
If-Else
B) Write A Python Program To Receive A Series Of Positive Numbers
And DisplayThe Numbers In Order And Display Their Sum
4 Control Structures
A) Write A Python Program To Print The Elements Of The List Using For
Loop.
B) Write A Python Program To Find Sum Of Numbers Entered By User.
8 Binary Files
1
DE with Python MCA I Year II Semester
11 Web Scraping
Web Scraping Using Regular Expressions
12 Data Wrangling Using Pandas
14 Data Visualizations
A. Scatter Plot
B. Line Chart
C. Bar Chart
D. Histogram
FIGURE 1.5
Welcome screen of Anaconda installation.
3
DE with Python MCA I Year II Semester
Step 4: You will get a License Agreement Screen, read the licensing terms
and click on I Agree button.
Step 5: Assuming that you are the only user on your system, select
Just Me radio button (FIGURE 1.6). Click on Next button.
FIGURE 1.6
Selection of installation type.
FIGURE 1.7
Choosing the destination folder.
4
DE with Python MCA I Year II Semester
Step 7: In the Advanced Installation Options screen, select all the check
boxes. Ignore the warnings and click on Install button (FIGURE 1.8).
FIGURE 1.8
Selecting Advanced Installation Options.
Step 8: This starts the installation of Anaconda Python Distribution and
once the installation is complete, click on Next button.
Step 9: Finish the setup by clicking on Finish button.
Step 10: To check whether the installation is working properly or not, go
to the com mand prompt and type python. You should see a series of
lines and a prompt as shown in FIGURE 1.9. This is Python Interactive
mode. Here, the three greaterthan signs “>>>” is the primary prompt of
the interactive mode.
FIGURE 1.9
Python interactive shell.
5
DE with Python MCA I Year II Semester
FIGURE 1.10
Installation options for PyCharm.
6
DE with Python MCA I Year II Semester
Step 5: Go with the default Start Menu Folder as shown on the screen
and click on Install button. It will take some time for the installation to
finish. Once the installation is done click on the Finish button.
Step 6: You will be asked whether you want to import previous
PyCharm settings. Since we are starting on a clean slate, let’s select the
second radio button as shown in FIGURE 1.11 and click on OK button.
FIGURE 1.11
Importing PyCharm settings.
FIGURE 1.12
Customization of PyCharm.
7
DE with Python MCA I Year II Semester
Step 8: In the next screen, click on Configure pull down list and select Settings option as
shown in FIGURE 1.13.
FIGURE 1.13
Welcome screen for PyCharm.
Step 9: In the Default Settings screen, on the left pane, click on Project Interpreter as
shown in FIGURE 1.14.
FIGURE 1.14
Default settings of PyCharm.
On the right pane, in the Project Interpreter option, click on the button having toothed
wheel icon and select Add. In the Add Python Interpreter screen, on the left pane, click
on System Interpreter and select the Python interpreter path from the Interpreter pull
down list as shown in FIGURE 1.15. Click on OK button.
14
DE with Python MCA I Year II Semester
FIGURE 1.15
Adding Python Interpreter.
Step 10: It will take some time to list all the packages. Once done click on OK button.
Step 11: You will be again presented with the Welcome screen as shown in FIGURE
1.13. Now, to work with PyCharm IDE, click on Create New Project option. In the next section,
steps to create and execute Python program are discussed in detail.
15
DE with Python MCA I Year II Semester
Python Features:
Easy-to-learn: Python is clearly defined and easily readable. The structure of the program is
very simple. It uses few keywords.
Portable: Python can run on a wide variety of hardware platforms and has the same interface
on all platforms.
Interpreted: Python is processed at runtime by the interpreter. So, there is no need to compile
a program before executing it. You can simply run the program.
Extensible: Programmers can embed python within their C,C++,Java script ,ActiveX, etc.
Free and Open Source: Anyone can freely distribute it, read the source code, and edit it.
High Level Language: When writing programs, programmers concentrate on solutions of the
current problem, no need to worry about the low level details.
Scalable: Python provides a better structure and support for large programs than shell scripting.
Applications:
• Bit Torrent file sharing
• Google search engine
• Youtube
• Intel, Cisco, HP, IBM
• i-Robot
• NASA
• Facebook
• Dropbox
Python Interpreter is a program that reads and executes Python code. It uses 2 modes of Execution.
1. Interactive mode
2. Script mode
16
DE with Python MCA I Year II Semester
1. Interactive mode: Interactive Mode, as the name suggests, allows us to interact with OS.
When we type Python statement, interpreter displays the result immediately. In interactive
mode, you type Python programs and the interpreter displays the result:
>>> 1 + 1
2
>>>
We cannot save the statements and have to retype all the statements once again to re- run
them.
The chevron, >>>, is the prompt the interpreter uses to indicate that it is ready for you to
enter code.
2. Script mode: In script mode, we type python program in a file and then use interpreter
to execute the content of the file. Scripts can be saved to disk for future use.
Python scripts have the extension .py, meaning that the filename ends with .py. Save the code
with [Link] and run the interpreter in script mode to execute the script.
Indentation:
Indentation refers to the spaces at the beginning of a code line.
Python uses indentation to indicate a block of code
The print() function prints the specified message to the screen, or other standard output device.
DATA TYPES IN PYTHON
17
DE With Python MCA I Year II Semester
Python has the following data types built-in by default, in these categories
18
DE With Python MCA I Year II Semester
Interactive Mode:
Source Code:
print(type(a)) print(type(b))
print(type(c))))
Output:
19
DE With Python MCA I Year II Semester
2.b. Write a program to purposefully raise Indentation Error and correct it.
20
DE With Python MCA I Year II Semester
2. c. Write a program to compute distance between two points taking input from the
user.
Source Code:
import math
print(x)
print(y)
d=[Link](((int(x[0])-int(y[0]))**2)+((int(x[1])-int(y[1]))**2))
Output:
21
DE With Python MCA I Year II Semester
2.d. Write a program [Link] that takes 2 numbers as command line arguments and
prints the sum.
Source Code:
#Program to accept two numbers as command line arguments and prints the sum.
sum=num1+num2
Output:
22
DE With Python MCA I Year II Semester
Source Code:
Output:
23
DE With Python MCA I Year II Semester
2.f. Write a program for checking whether the given number is even number or not.
Source Code:
if(a%2==0):
print("Given number is even")
else:
print("Given number is odd")
Output:
24
DE With Python MCA I Year II Semester
3 CONDITIONAL STATEMENTS
Source Code:
# Python program to find the largest number among the three input numbers
Output:
25
DE With Python MCA I Year II Semester
3.b. Write a Python program to receive a series of positive numbers and display the
numbers in order and display their sum.
Source Code:
import random
num1=[Link](100,500)
num2=[Link](100,500)
sum=num1+num2
print("First random number is ", num1)
print("Second random number is ", num2)
Output:
26
DE With Python MCA I Year II Semester
4 CONTROL STRUCTURES
4.a. Write a python program to print the elements of the list using for loop.
Source Code:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
27
DE With Python MCA I Year II Semester
Source Code:
# program to calculate the sum of numbers until the user enters zero total = 0
Output:
28
DE With Python MCA I Year II Semester
Source Code:
29
DE With Python MCA I Year II Semester
Source Code:
#Recursive function to find the GCD of two numbers
def gcd(a, b):
if a == b:
return a elif
a < b:
return gcd(b, a)
else:
return gcd(b, a - b)
30
DE With Python MCA I Year II Semester
5.c. Write recursive functions to find the factorial of the given number.
Source code:
# Driver Code
num = eval(input("Enter the number to find the factorial: "))
print("Factorial of",num,"is",factorial(num))
Output:
31
DE With Python MCA I Year II Semester
Output:
32
DE With Python MCA I Year II Semester
Source Code:
Output:
33
DE With Python MCA I Year II Semester
6 EXCEPTION HANDLING
finally:
# this block is always executed
# regardless of exception generation.
print('This is always executed')
Output:
34
DE With Python MCA I Year II Semester
try:
raise NameError("Hi there") # Raise Error
except NameError:
print ("An exception")
raise # To determine whether the exception was raised or not
35
DE With Python MCA I Year II Semester
Source Code:
36
DE With Python MCA I Year II Semester
Source Code:
#Polymorphism
class India():
def capital(self):
print("New Delhi is the capital of India.")
def language(self):
print("Hindi is the most widely spoken language of India.") def
type(self):
print("India is a developing country.")
class USA():
def capital(self):
print("Washington, D.C. is the capital of USA.") def
language(self):
print("English is the primary language of USA.") def
type(self):
print("USA is a developed country.")
def func(obj):
[Link]()
[Link]()
[Link]()
obj_ind = India()
obj_usa = USA()
func(obj_ind)
func(obj_usa)
Output:
37
DE With Python MCA I Year II Semester
Program to create a binary file and write the data into it using Pickle Module Source
Code:
import pickle
s={ } #declare empty dictionary
file2 = open("E:/[Link]" , "wb") #open file
R = int (input ('Enter roll number=' ) )
N = input ('Enter name =' )
M = float(input ('Enter marks =' )) #
add read data into dictionary
s['Rollno'] = R
s['Name'] = N
s['Marks'] = M
# now write into the file
[Link] (s ,file2)
[Link]( )
Output:
38
DE With Python MCA I Year II Semester
import pickle
Stu = {} #Empty dictionary object to stored records read from [Link] Studentfile =
open('E:/[Link]', 'rb') #open binary file in read mode
try:
while True : # It will become False upon EOF
Stu = [Link](Studentfile) #Read record in Emp dictionary from file handle Empfile
print (Stu) # print the record
except EOFError :
[Link]()
Output:
39
DE With Python MCA I Year II Semester
Program to create a text file, write into the text file, append the data to the text file and
read from text file.
[Link]()
[Link]()
data=[Link]()
print(data) [Link]()
40
DE With Python MCA I Year II Semester
Output:
41
DE With Python MCA I Year II Semester
[Link] FILES
import csv
headernames=["id","name"]
writer=[Link](csvfile,headernames) [Link]()
[Link]({"id":"101","name":"Avinash"})
42
DE With Python MCA I Year II Semester
b=[Link](a)
for x in b:
print(x)
43
DE With Python MCA I Year II Semester
import codecs
f = open('F:\NewFolder\Python Programs\[Link]', 'w') html_template =
"""<html>
<head>
<title>Title</title>
</head>
<body>
<h2>Welcome To Python Class</h2>
<p>Default code has been loaded into the Editor.</p>
</body>
</html>
"""
# writing the code into the file
[Link](html_template) [Link]()
# viewing html files
file = [Link]("F:\ NewFolder \Python Programs\[Link]", 'r', "utf-8") # using .read
method to view the html code from our object
print([Link]())
Output:
44
DE With Python MCA I Year II Semester
45
DE With Python MCA I Year II Semester
JSON to Python
import json
# JSON string
"company":"WIPRO"}'
conversion") print(employee_dict)
print(employee_dict['department'])
print("\nType of data")
print(type(employee_dict))
Output:
46
DE With Python MCA I Year II Semester
import json
# Data to be written
dictionary = {
"name": "Sunil",
"department": "HR",
"Company": 'Infosys'
# Serializing json
json_object = [Link](dictionary)
print(json_object)
Output:
47
DE With Python MCA I Year II Semester
import json
# Data to be written
dictionary ={
: 420,
"cgpa" : 10.10,
"phonenumber" : "1234567890"
[Link](dictionary, outfile)
Output:
48
DE With Python MCA I Year II Semester
49
DE With Python MCA I Year II Semester
50
DE With Python MCA I Year II Semester
Source Code:
Output:
51
DE With Python MCA I Year II Semester
52
DE With Python MCA I Year II Semester
10 REGULAR EXPRESSIONS
Program for searching, splitting, and replacing strings based on pattern matching using
regular expressions
Source Code:
import re
txt = "The rain in Spain"
print("Given Data...",txt)
#Find all lower case characters alphabetically between "a" and "m": x =
[Link]("[a-m]", txt)
print(x)
y=[Link]("[abc]",txt) if
y:
print("Match found")
else:
print("Match not found")
Output:
53
DE With Python MCA I Year II Semester
11 WEB SCRAPING
Source Code:
re
[Link](url)
html = [Link]()
htmlStr = [Link]()
item in pdata:
print(item)
Output:
54
DE With Python MCA I Year II Semester
import pandas as pd
Assign data
df = [Link](data)
# Display data
print(df)
Compute average
c = avg = 0
if str(ele).isnumeric():
c += 1
avg += ele
avg /= c
55
DE With Python MCA I Year II Semester
df = [Link](to_replace="NaN",value=avg)
# Display data
print(df)
Categorize gender
# Display data
print(df)
# Display data
print(df)
56
DE With Python MCA I Year II Semester
Import module
import pandas as pd
# Creating Dataframe
details = [Link]({
# Creating Dataframe
fees_status = [Link](
# Merging Dataframe
57
DE With Python MCA I Year II Semester
#Grouping
# Import module
import pandas as pd
# Creating Data
'Ford'],
'Sold': [6, 7, 9, 8, 3, 5,
2, 8, 7, 2, 4, 2]}
= [Link](car_selling_data)
= [Link]('Year')
print(grouped.get_group(2010))
Output:
58
DE With Python MCA I Year II Semester
59
DE With Python MCA I Year II Semester
60
DE With Python MCA I Year II Semester
Code:
import [Link]
#Creating a connection
mydb = [Link](
host="[Link]",
user="root",
password="appy1723",
database="dataanalytics"
print(mydb)
#Creating a table
mycursor = [Link]()
val = [
61
DE With Python MCA I Year II Semester
[Link](sql, val)
[Link]()
myresult = [Link]()
for x in myresult:
print(x)
[Link]()
#Update a record
sql = "UPDATE customers SET address = 'Canyon 123' WHERE address = 'Valley 345'"
[Link](sql)
[Link]()
62
DE With Python MCA I Year II Semester
Output:
63
DE With Python MCA I Year II Semester
14 DATA VISUALIZATIONS
SCATTER PLOT
#Scatter Plot
import pandas as pd
Output:
64
DE With Python MCA I Year II Semester
LINE CHART
import pandas as pd
import [Link] as plt
# reading the database
data = pd.read_csv("[Link]")
[Link]()
Output:
65
DE With Python MCA I Year II Semester
BAR CHART
import pandas as pd
data = pd.read_csv("[Link]") #
[Link](data['day'], data['tip'])
[Link]("Bar Chart")
[Link]('Day')
[Link]('Tip')
[Link]()
66
DE With Python MCA I Year II Semester
HISTOGRAM
import pandas as pd
data = pd.read_csv("[Link]") #
histogram of total_bills
[Link](data['total_bill'])
[Link]("Histogram")
[Link]()
67
DE With Python MCA I Year II Semester
x = [5,7,8,7,2,17,2,9,4,11,12,9,6]
y = [99,86,87,88,111,86,103,87,94,78,77,85,86]
myfunc(x):
[Link](x, y)
[Link](x, mymodel)
[Link]()
print(r)
speed = myfunc(10)
print(speed)
if(r<=5):
else:
68
DE With Python MCA I Year II Semester
69
DE With Python MCA I Year II Semester
y = [21, 19, 24, 17, 16, 25, 24, 22, 21, 21]
inertias = []
for i in range(1,11):
kmeans = KMeans(n_clusters=i)
[Link](data)
[Link]([Link])
of clusters') [Link]('Inertia')
[Link]()
kmeans = KMeans(n_clusters=2)
[Link](data)
[Link](x, y, c=kmeans.labels_)
[Link]()
70
DE With Python MCA I Year II Semester
71
DE With Python MCA I Year II Semester
72