Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
6 views

Python

The document provides code snippets and output for 10 Python programming practical assignments. The practicals cover basic Python concepts like data types, operators, conditional statements, loops, functions, file handling and data structures. They also cover NumPy and Pandas libraries for array operations and data manipulation.

Uploaded by

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

Python

The document provides code snippets and output for 10 Python programming practical assignments. The practicals cover basic Python concepts like data types, operators, conditional statements, loops, functions, file handling and data structures. They also cover NumPy and Pandas libraries for array operations and data manipulation.

Uploaded by

Nikita Gamit
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

PDS(3150713)

PRACTICAL:-1
AIM:- Implement the program “Hello World” in Python Language.
Code:-
print("Hello World")

output:-

1
VIEAT/BE/SEM-5/210940107006
PDS(3150713)

PRACTICAL:-2
AIM:- Implement the Program of Primary Data types (Strings, Integer,
Float, Complex, Boolean ) in Python.
Integers – This value is represented by int class. It contains positive or negative whole
numbers (without fractions or decimals). In Python, there is no limit to how long an integer
value can be.
Float – This value is represented by the float class. It is a real number with a floating-point
representation. It is specified by a decimal point. Optionally, the character e or E followed
by a positive or negative integer may be appended to specify scientific notation.
Complex Numbers – Complex number is represented by a complex class. It is specified
as (real part) + (imaginary part)j. For example – 2+3j
Boolean - Data type with one of the two built-in values, True or False. Boolean objects that
are equal to True are truthy (true), and those equal to False are falsy (false).
String- A string is a collection of one or more characters put in a single quote, double-
quote, or triple-quote.
Code:-
def primary_data_types():
# Strings
print("\nString Data Type")
string = "Hello, World!"
print(string)

# Integers
print("\nInteger Data Type")
integer = 123
print(integer)

# Floats
print("\nFloat Data Type")
float_num = 3.14
print(float_num)

# Complex Numbers
print("\nComplex Number Data Type")

2
VIEAT/BE/SEM-5/210940107006
PDS(3150713)

complex_num = 2 + 3j
print(complex_num)

# Booleans
print("\nBoolean Data Type")
boolean = True
print(boolean)

primary_data_types()
output:-

3
VIEAT/BE/SEM-5/210940107006
PDS(3150713)

PRACTICAL:-3
AIM:- Implement the below program using the input function in Python.
i. Write a Python Program to perform the addition of two numbers.
ii. Write a Python Program to find the square root of any number.
Code:-
# Part 1: Implement the addition program

# Take input for the first number


num1 = int(input("Enter the first number: "))

# Take input for the second number


num2 = int(input("Enter the second number: "))

# Perform the addition


sum = num1 + num2

# Print the result


print("The sum of the two numbers is: ", sum)

# Part 2: Implement the square root program

# Take input for the number


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

# Check if the number is positive


if num >= 0:
# Perform the square root calculation
square_root = num ** 0.5

# Print the result

4
VIEAT/BE/SEM-5/210940107006
PDS(3150713)

print("The square root of the number is: ", square_root)


else:
print("Sorry, negative numbers do not have a real square root.")
output:-

5
VIEAT/BE/SEM-5/210940107006
PDS(3150713)

PRACTICAL:-4
AIM:- Implement Conditional Statements in Python.
If statements- If the simple code of block is to be performed if the condition holds true then
the if statement is used.
If…else statements- In conditional if Statement the additional block of code is merged as
else statement which is performed when if condition is false.
Nested if statements- if statement can also be checked inside other if statement. This
conditional statement is called a nested if statement.

Code:-
#program to find the number is even or odd
num = int(input("Enter a number to find the following number is even or odd :"))
if num%2==0 :
print("Entered number is EVEN")
else:
print("Entered number is ODD")
output:-

6
VIEAT/BE/SEM-5/210940107006
PDS(3150713)

PRACTICAL:-5
AIM:- Implement “for loop” and “while loop” in Python.
The while loop:- with the while loop we can execute a set of statements as long as a condition
is true.
The for loop:- The loop will execute a bloke of statements for each item in the sequence.
Code:-
1. For loop:-
for number in range(1, 6):
print(number)
2. while loop:-
counter = 1
while counter <= 5:
print(counter)
counter += 1
output:-
for loop:-

While loop:-

7
VIEAT/BE/SEM-5/210940107006
PDS(3150713)

PRACTICAL:-6
AIM:- Implement the user-defined function to find the factorial of any
number.
Code:-
# Python program to find the factorial of a number provided by the user
# using recursion

def factorial(x):
"""This is a recursive function
to find the factorial of an integer"""

if x == 1:
return 1
else:
# recursive call to the function
return (x * factorial(x-1))

# change the value for a different result


num = 7

# to take input from the user


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

# call the factorial function


result = factorial(num)
print("The factorial of", num, "is", result)
Output:-

8
VIEAT/BE/SEM-5/210940107006
PDS(3150713)

PRACTICAL:-7
AIM:-Implement the function to find the Area of Geometric Shapes
(Square, Rectangle, Circle, and Triangle).
Code:-
def area(sel,*inp):
a=1
if sel=="s":
for i in inp:
a= a * i
print("area is : ",a)
elif sel=="r":
for i in inp:
a=a * i
print("area is : ",a)
elif sel=="c":
for i in inp:
a= a * i
a = a *3.14
print("area is : ",a)
elif sel=="t":
for i in inp:
a= a * i
a = a/2
print("area is : ",a)
else:
print("Wrong input")
print("Enter \"s\" for square \"r\" for rectangle" )
print("Enter \"c\" for circle \"t\" for triangle : " )
sel = input("")

9
VIEAT/BE/SEM-5/210940107006
PDS(3150713)

if sel=="s":
side = int(input("enter side lenght "))
area(sel,side)
elif sel=="r":
len=int(input("Enter lenght"))
hei=int(input("Enter height"))
area(sel,len,hei)
elif sel=="c":
r=int(input("Enter radius"))
area(sel,r)
elif sel=="t":
b=int(input("Enter base"))
h=int(input("Enter height"))
area(sel,b,h)
else:
print("Wrong input")
output:

10
VIEAT/BE/SEM-5/210940107006
PDS(3150713)

PRACTICAL:-8
AIM:- Implement Data Structures(list, dictionary, tuple, set) in Python.
List- python lists are just like dynamic-sized arrays, declared in other languages.
Tuple- A tuple is a collection of Python objects separated by commas.
Set – A set is an unordered collection data type that is iterable, mutable.
Code:-
1. list:-
list_obj = [1, 2, 3, 4, 5]
2. Dictionary:-
dict_obj = {
'key1': 'value1',
'key2': 'value2',
'key3': 'value3'
}
3. Tuple:-
tuple_obj = (1, 2, 3, 4, 5)
4. Set:-
set_obj = {1, 2, 3, 4, 5}

11
VIEAT/BE/SEM-5/210940107006
PDS(3150713)

PRACTICAL:-9
AIM:- Implement the Python Program which performs basic data
manipulations(delete empty, rows, and columns, remove outliners) in a .csv
file using pandas on Jupyter Notebook in Python.
Code:-
# import module
import pandas as pd
# assign dataset
df = pd.read_csv("country_code.csv")
# display print("Type-", type(df))
df df.head(10)
df.shape
df1 = pd.read_csv("country_code.csv")
merged_col = pd.merge(df, df1, on='Name')
merged_col
output:

12
VIEAT/BE/SEM-5/210940107006
PDS(3150713)

13
VIEAT/BE/SEM-5/210940107006
PDS(3150713)

PRACTICAL:-10
AIM:- Implement the program to perform in the following
i. Basic numpy operation:- Create One, two, multi-dimensional Array.
ii. Perform addition, subtraction, multiplication, and division
operations on two matrices.
iii. Perform below function of m=nnumpy:- range(), arrange(),
linespace(), reshape(), zeroes(), ones(), min(), max(), sum(),sqrt()
functions in Python.
Code:-
1) Source :
import numpy as np
#creating one dimention array
print("creating one dimention array")
arr = np.array([10,28,35,32,11,37])
print(type(arr))
print(arr.shape)
print(arr.ndim)
#creating two dimention array
print("creating two dimention array")
arr2 = np.array([[10,20,30],[40,50,60]])
print(arr2)
print(arr2.ndim)
#creating multi dimention array
arr3 = np.array([[[1,2,3],[5,6,7]],[[10,20,30],[40,50,60]]])
print(arr3)
print(arr3.ndim)
output:

2) Source:
a = np.array([[3,4,5],[1,2,3]])
b= np.array([[6,7,8],[6,4,8]])
print("matrix A")
print(a)
14
VIEAT/BE/SEM-5/210940107006
PDS(3150713)

print("matrix B")
print(b)
print("matrix addition")
sum = np.add(a,b)
print(sum)
print("matrix subtraction")
sub = np.subtract(a,b)
print(sub)
print("matrix multipication")
mul =a*b
print(mul)
print("matrix division")
div =np.divide(a,b)
print(div)
output:

3) Source :
#Numpy arange is useful when you want to create a numpy array, having a range of
elements spaced out over a specified interval.
arr = np.arange(10)
print(arr)
#Numpy Linspace is used to create a numpy array whose elements are equally spaced
between start and end.
np.linspace(5,25)
#Numpy Linspace is used to create a numpy array whose elements are equally
#spaced between start and end on logarithmic scale.
np.logspace(5,20)\
arr = np.array([10,2,3,5,22,77,2])
print(arr)
print(arr.max())
print(arr.min())
print(arr.sum())

15
VIEAT/BE/SEM-5/210940107006
PDS(3150713)

output:

16
VIEAT/BE/SEM-5/210940107006
PDS(3150713)

PRACTICAL:-11
AIM:- Implement data visualization on a .csv file by the use of matplotib in
Python.
Code:-
import matplotlib.pyplot as plt
import csv
x = []
y = []
with open('biostats.csv','r') as csvfile:
plots = csv.reader(csvfile, delimiter = ',')
for row in plots:
x.append(row[0])
y.append(int(row[2]))
plt.bar(x, y, color = 'g', width = 0.72, label = "Age")
plt.xlabel('Names')
plt.ylabel('Ages')
plt.title('Ages of different persons')
plt.legend()
plt.show()
output:

17
VIEAT/BE/SEM-5/210940107006

You might also like