Python Lab Manual B.Tech. Sem-2
Python Lab Manual B.Tech. Sem-2
LAB MANUAL
For
Approved by:
Prepared by:
Ms. Shabda
Name: Chaitanya Garg
AIML Trainer
Reg. No.: 241302053
1 Python Installation
7 Mini Projects
• Project-1_Chess Board
• Project-2_Quiz on Animal Name
• Project-3_Tic Tac Toe Game
Python Installation
Installing Anaconda on Windows
Experiment No. 1
• Download the Anaconda installer from the following link
https://www.anaconda.com/products/individual#windows
Experiment No. 2
Q. Add Two Numbers with “+” Operator:
Here num1 and num2 are variables and we are going to add both variables
with the + operator in Python.
# printing values
print("Sum of", num1, "and", num2 , "is", sum)
Output:
Sum of 15 and 12 is 27
Experiment No. 3
Q. Add Two Numbers with User Input:
In the below program to add two numbers in Python, the user is first asked to
enter two numbers, and the input is scanned using the Python input()
function and stored in the variables number1 and number2.
Then, the variable’s number1 and number2 are added using the arithmetic
operator +, and the result is stored in the variable sum.
Output:
First number: 13.5 Second number: 1.54
The sum of 13.5 and 1.54 is 15.04
Experiment No. 4
Q. Add Two Numbers Using operator.add() Method:
Initialize two variables num1, and num2. Find sum using the operator.add() by
passing num1, and num2 as arguments and assign to sum. Display num1, num2
and sum.
num1 = 15
num2 = 12
# printing values
print("Sum of {0} and {1} is {2}" .format(num1,
num2, sum))
Output
Sum of 15 and 12 is 27
Python Data Structures
Experiment No. 5
Q. Add Two Numbers in Python Using Function
This program show adding two numbers in Python using function. We can
define a function that accepts two integers and returns their sum.
Output
Sum of 10 and 5 is 15;
Experiment No. 6
Q. Write a program in Python to make a simple calculator.
Experiment No. 7
Q. Create a Python program to find sum of elements in list (using for loop)
total = 0
# creating a list
list1 = [11, 5, 17, 18, 23]
Output
Sum of all elements in given list: 74
Experiment No. 8
Q. Write a Python program to find sum of elements in list (using while loop)
total = 0
ele = 0
# creating a list
list1 = [11, 5, 17, 18, 23]
Output
Sum of all elements in given list: 74
Experiment No. 9
Q. Write a Python Program to count the number of vowels in a string.
string=raw_input("Enter string:")
vowels=0
for i in string:
if(i=='a' or i=='e' or i=='i' or i=='o' or i=='u' or i=='A' or i=='E'
or i=='I' or i=='O' or i=='U'):
vowels=vowels+1
print("Number of vowels are:")
print(vowels)
Output:
Case 1:
Enter string:Hello world
Number of vowels are:
3
Case 2:
Enter string:WELCOME
Number of vowels are:
3
Experiment No. 10
Q. Create a Python program and check how many dimensions the
arrays have
import numpy as np
a = np.array(42)
b = np.array([1, 2, 3, 4, 5])
c = np.array([[1, 2, 3], [4, 5, 6]])
d = np.array([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]])
print(a.ndim)
print(b.ndim)
print(c.ndim)
print(d.ndim)
Output:
0
1
2
3
Experiment No. 11
Q. Create an array with 5 dimensions using ndmin using a vector with
values 1,2,3,4 and verify that last dimension has value 4
import numpy as np
print(arr)
print('shape of array :', arr.shape)
Output:
[[[[[1 2 3 4]]]]]
shape of array : (1, 1, 1, 1, 4)
Experiment No. 12
Q. Convert the following 1-D array with 12 elements into a 2-D array.
newarr = arr.reshape(4, 3)
print(newarr)
Output:
[[ 1 2 3]
[ 4 5 6]
[ 7 8 9]
[10 11 12]]
Experiment No. 13
Q. Write Python code to demonstrate trigonometric function.
import numpy as np
# create an array of angles
angles = np.array([0, 30, 45, 60, 90, 180])
# sine of angles
print('Sine of angles in the array:')
sine_value = np.sin(radians)
print(np.sin(radians))
Output:
Sine of angles in the array:
[0.00000000e+00 5.00000000e-01 7.07106781e-01 8.66025404e-01
1.00000000e+00 1.22464680e-16]
import numpy as np
# construct a weight array
weight = np.array([50.7, 52.5, 50, 58, 55.63, 73.25, 49.5, 45])
# percentile
print('\n Weight below which 70 % student fall: ')
print(np.percentile(weight, 70))
# mean
print('\n Mean weight of the students: ')
print(np.mean(weight))
# median
print('\n Median weight of the students: ')
print(np.median(weight))
# standard deviation
print('\n Standard deviation of weight of the students: ')
print(np.std(weight))
# variance
print('\n Variance of weight of the students: ')
print(np.var(weight))
# average
print('\n Average weight of the students: ')
print(np.average(weight))
Output:
Minimum and maximum weight of the students:
45.0 73.25
Experiment No. 15
Q. (a) creating series from ndarray
data = np.array(['a','b','c','d'])
print(data)
s_arr = pd.Series(data)
print(s_arr)
Output:
['a' 'b' 'c' 'd']
0 a
1 b
2 c
3 d
dtype: object
Output:
a 0.0
bat 1.0
10 2.3
dtype: float64
Output:
bat 1.0
2 NaN
10 2.3
dtype: float64
Experiment No. 16
Q. Create a DataFrame in Python using Pandas:
import pandas as pd
data = {'state':['Ohio', 'Delhi', 'Ohio', 'Nevada','Nevada','Nevada'],
'year':[2000,2003 ,2001 ,2000, 2001, 2002],
'pop':[1.5, 1.6, 5,3.9, 4, 6.7]}
#data
frame = pd.DataFrame(data)
print(frame)
frame = pd.DataFrame(data,[10,11,12,13,14,15],['year','state','pop'])
frame
Output:
state year pop
0 Ohio 2000 1.5
1 Delhi 2003 1.6
2 Ohio 2001 5.0
3 Nevada 2000 3.9
4 Nevada 2001 4.0
5 Nevada 2002 6.7
Experiment No. 17
import pandas as pd
# Create dataframe
info = pd.DataFrame({"P":[4, 7, 1, 8, 9],
"Q":[6, 8, 10, 15, 11],
"R":[17, 13, 12, 16, 14],
"S":[15, 19, 7, 21, 9]},
index =["Parker", "William", "Smith", "Terry", "Phill"])
# Print dataframe
info
Output:
import pandas as pd
import numpy as np
N=5
df = pd.DataFrame({
'A': pd.date_range(start='2016-01-01',periods=N,freq='D'),
'x': np.linspace(0,stop=N-1,num=N),
'y': np.random.rand(N),
'C': np.random.choice(['Low','Medium','High'],N).tolist(),
'D': np.random.normal(100, 10, size=(N)).tolist()
})
Df
Output:
Experiment No. 19
Matplotlib Inline
The output of plotting commands is displayed inline within frontends like the Jupyter
notebook, directly below the code cell that produced it. The resulting plots will then also
be stored in the notebook document. %matplotlib inline should be the first
command before import command
#%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
data = np.arange(10)
print(data)
plt.plot(data)
plt.show()
[0 1 2 3 4 5 6 7 8 9]
x = np.arange(0.0, 6.0, 0.01)
plt.plot(x, [x**2 for x in x]);
#plt.show()
Multiline Plot
plots are reset after each cell is evaluated, so for more complex plots you must put all of
the plotting commands in a single notebook cell
def sinplot(flip=0.5):
x = np.linspace(0, 14, 100)
for i in range(1, 5):
plt.plot(x, np.sin(x + i * .5) * (7 - i) * flip)
sinplot()
plt.show()
import seaborn as sns
sns.set_style("dark")
sinplot()
plt.show()
sns.set_style("white")
sinplot()
sns.despine()
plt.show()
Qualitative or categorical palettes are best suitable to plot the categorical data.
current_palette = sns.color_palette()
sns.palplot(current_palette)
plt.show()
Appending an additional character ‘s’ to the color passed to the color parameter will plot
the Sequential plot.
current_palette = sns.color_palette()
sns.palplot(sns.color_palette("Reds"))
plt.show()
Diverging palettes use two different colors. Each color represents variation in the value
ranging from a common point in either direction.
Assume plotting the data ranging from -1 to 1. The values from -1 to 0 takes one color
and 0 to +1 takes another color.
By default, the values are centered from zero. You can control it with parameter center
by passing a value.
current_palette = sns.color_palette()
sns.palplot(sns.color_palette("BrBG", 7))
plt.show()
Project-1
Create a Chessboard with Python
To create a chessboard with the Python programming language, we will use two
Python libraries; Matplotlib for visualization, and NumPy for building an algorithm
which will help us to create and visualize a chessboard. Let’s see how we can code
to create and visualize a chessboard:
Source Code
Project-2
Create a Quiz Game with Python
We will create a quiz game with Python. I will create an animal quiz here. Even
though the questions are about animals, this quiz can be easily changed to cover
any other topic.
The Quiz game asks the player questions about animals. They have three chances
to answer each question you don’t want to take the quiz too difficult. Each correct
answer will score a point. At the end of the game, the program will reveal the
player’s final score.
This quiz game uses a function; a block of code with a name that performs a
specific task. A function allows you to use the same code several times, without
having to type everything each time. Python has a lot of built-in functions, but it
also allows you to create your functions.
The program should continue to check if there are any questions to ask and if the
player has exhausted all his chances. The score is stored in a variable during the
game. Once all the questions have been answered, the game ends.
Source Code
Here we will introduce an advanced Python project on Tic Tac Toe GUI with
Python. This game is very popular and is quite simple in itself. It is a two-player
game. In this game, there is a board with 3×3 squares.
In this game a player can choose between two symbols with his opponent, the
usual games use “X” and “O”. If the first player chooses “X”, then the second
player must play with “O” and vice versa.
A player marks one of the 3×3 squares with his symbol (perhaps “X” or “O”) and
he aims to create a straight line horizontally or vertically or diagonally with two
intensions:
1. Create a straight line before your opponent to win the game.
2. Prevent his opponent from creating a straight line first.
If no one can logically create a straight line with its symbol, the game ends in a tie.
So there are only three possible outcomes: one player wins, his opponent (human
or computer) wins, or there is a tie.
There are two basic logics in this game; when both players are human, and when
one is a computer.
Output
X---------------------------------------X----------------------------------------X