0% found this document useful (0 votes)
2 views22 pages

Data science lab

The document provides a comprehensive overview of Python programming concepts, including operators, conditional statements, loops, data structures (lists, sets, tuples, dictionaries), and data manipulation using pandas. It includes code snippets and their outputs to demonstrate the functionality of various Python features. Additionally, it covers the use of standard mathematical, time, and random functions.

Uploaded by

rslh.1990.rocky
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views22 pages

Data science lab

The document provides a comprehensive overview of Python programming concepts, including operators, conditional statements, loops, data structures (lists, sets, tuples, dictionaries), and data manipulation using pandas. It includes code snippets and their outputs to demonstrate the functionality of various Python features. Additionally, it covers the use of standard mathematical, time, and random functions.

Uploaded by

rslh.1990.rocky
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

DATA SCIENCE

1. Implement python script to show the usage of various operators available in


python language.
x = 20
y = 10
z=5
# arithmetic operators
print(x+y) #additon
print(x-y) #subtraction
print(x*y) #multiplication
print(x/y) #division
print(x%y) #modulus
print(x//y) #floor division
print(x**y) # exponential
# comparision operators
print(x>y)
print(x<y)
print(x==y)
print(x!=y)
print(x>=y)
print(x<=y)
# logical operators
print(x and y)
print(x or y)
print(not x)
print((x>y) and (x>z))
print((x>y) or (x>z))
print(not(x>y))
# assignment operators
x+=2
print(x)
x-=3
print(x)
x*=3
print(x)
x/=2
print(x)
x%=2
print(x)
x//=3
print(x)
x**=3
print(x)
x = 20
# bitwise operators
print(x&y) #bitwise AND
print(x|y) #bitwise OR
print(~x) #bitwise NOT
print(x^y) #bitwise XOR
print(y>>2) #RIGHT SHIFT
print(x<<2) #LEFT SHIFT
# identity operators
print(x is not y)
print(x is z)
# membership operators
s= [x, y, z]
print(10 in s)
print(5 not in s)
print(15 not in s)
print(20 in s)
# relational operators
print(x<y)
print(x==y)
print(x!=y)
print(x>y)
print(x>=y)
print(x<=y)

OUTPUT:

30

10

200

2.0

10240000000000
True

False

False

True

True

False

10

20

False

True

True

False

22

19

57

28.5

0.5

0.0

0.0

30

-21

30

80

True

False

True
False

True

True

False

False

True

True

True

False

2.Implement python scripts using conditional statements.


a = 15
b = 30
# if statement
if(a<b):
print("a is less than b")
# if - else statement
if (a > b):
print("a is greater than b")
else:
print("a is not greater than b")
# if elif - else statement
if a==b:
print("a is equal to b")
elif a < b :
print("a is less than b")
else:
print("a is greater than b")
# nested if statement
if a < b:
if a < 16:
print("a is less than 16 and less than b")
# ternary operator
result = "a is less than b" if a<b else "a is not less than b"
print(result)
OUTPUT:

a is less than b

a is not greater than b

a is less than b

a is less than 16 and less than b

a is less than b

3. Implement python scripts using iterative statements.


# for loop
print ("For loop:")
for i in range(5):
print(i)
# while loop
print("\nWhile loop:")
count = 0
while count < 5:
print(count)
count+=1
# nested loops
print("\nNested loops:")
for i in range(3):
for j in range(2):
print(f"i:{i}, j:{j}")

OUTPUT:

For loop:

4
While loop:

Nested loops:

i:0, j:0

i:0, j:1

i:1, j:0

i:1, j:1

i:2, j:0

i:2, j:1

4. Implement python scripts break and continue statements.


#Break statement
print("\nBreak statement")
for i in range(6):
if i == 3:
break
print(i)
# Continue statement
print("\nContinue statement")
for i in range(6):
if i == 3:
continue
print(i)

OUTPUT:

Break statement

1
2

Continue statement

5. Implement lists, sets, tuples and dictionaries.


#LISTS
#Creating a list
fruits = ["apple", "banana", "cherry"]
print("original list:",fruits)
#accessing elements
print("first element:",fruits[0])
print("last element:",fruits[2])
#modify elements
fruits[1] = "mango"
print("modified list:",fruits)
#adding elements
fruits.append("date")
print("list after append:",fruits)
# inserting elements
fruits.insert(1,"banana")
print("list after insert:", fruits)
# removing elements
fruits.remove("banana")
print("list after remove:",fruits)
# popping elements
popped_fruit = fruits.pop(3)
print("popped element:",popped_fruit)
print("list after pop:",fruits)
# list slicing
print("sliced list:",fruits[1:3])
#list comprehension
squares = [x**2 for x in range(5)]
print("list comprehension:", squares)
#reversing a list
fruits.reverse()
print("reversed list:", fruits)
# iterating through lists
print("iterating through lists:")
for fruit in fruits:
print(fruit)
# checking membership
print("is 'apple' present in the list? ", "apple" in fruits)
print("is 'banana' present in the list? ", "banana" in fruits)
# list length
print("length of the list:", len(fruits))

# sorting a list
fruits.sort()
print("sorted list:",fruits)

OUTPUT:

original list: ['apple', 'banana', 'cherry']

first element: apple

last element: cherry

modified list: ['apple', 'mango', 'cherry']

list after append: ['apple', 'mango', 'cherry', 'date']

list after insert: ['apple', 'banana', 'mango', 'cherry', 'date']

list after remove: ['apple', 'mango', 'cherry', 'date']

popped element: date

list after pop: ['apple', 'mango', 'cherry']

sliced list: ['mango', 'cherry']

list comprehension: [0, 1, 4, 9, 16]

reversed list: ['cherry', 'mango', 'apple']

iterating through lists:

cherry
mango

apple

is 'apple' present in the list? True

is 'banana' present in the list? False

length of the list: 3

sorted list: ['apple', 'cherry', 'mango']

#TUPLES
#Creating a tuple
fruits = ("apple", "banana", "cherry")
print("original tuple:",fruits)
#accessing elements
print("first element:",fruits[0])
print("last element:",fruits[2])
# slicing a tuple
print("sliced tuple:",fruits[1:3])
# iterating through a tuple
print("iterating through a tuple:")
for fruit in fruits:
print(fruit)
# checking membership
print("is 'apple' present in the tuple? ", "apple" in fruits)
print("is 'banana' present in the tuple? ", "banana" in fruits)
# tuple length
print("length of the tuple:", len(fruits))
#concatenating tuples
vegetable = ("tomato", "potato")
combined_tuple = fruits + vegetable
print("concatenated tuple:", combined_tuple)
# repeating tuples
repeated = fruit*2
print("repeated tuple:", repeated)
#nested tuples
nested = (fruits,vegetable)
print("nested tuple:", nested)
# tuple unpacking
fruit1, fruit2, fruit3 = fruits
print("unpacked elements:", fruit1, fruit2, fruit3)
#converting a list to a tuple
fruit_list = ["apple", "banana", "cherry"]
fruit_tuple = tuple(fruit_list)
print("converted tuple:", fruit_tuple)

OUPUT:

original tuple: ('apple', 'banana', 'cherry')

first element: apple

last element: cherry

sliced tuple: ('banana', 'cherry')

iterating through a tuple:

apple

banana

cherry

is 'apple' present in the tuple? True

is 'banana' present in the tuple? True

length of the tuple: 3

concatenated tuple: ('apple', 'banana', 'cherry', 'tomato', 'potato')

repeated tuple: cherrycherry

nested tuple: (('apple', 'banana', 'cherry'), ('tomato', 'potato'))

unpacked elements: apple banana cherry

converted tuple: ('apple', 'banana', 'cherry')

#SETS
#Creating a set
fruits = {"apple", "banana", "cherry"}
print("original set:",fruits)
#adding elements
fruits.add("date")
print("set after add:",fruits)
#adding multiple elements
fruits.update(["mango", "grapes","orange"])
print("set after update:",fruits)
#removing elements
fruits.remove("banana")
print("set after remove:",fruits)
#discarding elements(no error if element is not found)
fruits.discard("banana")
print("set after discard:",fruits)
#popping an element(removes a random element)
popped_fruit = fruits.pop()
print("popped element:",popped_fruit)
print("set after pop:",fruits)

OUTPUT:

original set: {'apple', 'banana', 'cherry'}

set after add: {'date', 'apple', 'banana', 'cherry'}

set after update: {'banana', 'cherry', 'orange', 'mango', 'date', 'apple', 'grapes'}

set after remove: {'cherry', 'orange', 'mango', 'date', 'apple', 'grapes'}

set after discard: {'cherry', 'orange', 'mango', 'date', 'apple', 'grapes'}

popped element: cherry

set after pop: {'orange', 'mango', 'date', 'apple', 'grapes'}

#DICTIONARY
#Creating a dictionary
student = {"name": "John", "age":20,"courses":["maths","science"]}
print("original dictionary:", student)
#accessing elements
print("name:",student["name"])
print("courses:",student["courses"])
#modify elements
student["age"] = 21
print("modified dictionary:",student)
#adding elements
student["grade"] = "A"
print("dictionary after adding an element:",student)
# removing elements
del student["age"]
print("dictionary after removing an element:",student)
# popping elements
grade = student.pop("grade")
print("popped element:",grade)
print("dictionary after pop:",student)
# iterating through dictionary
print("iterating through dictionary:")
for key, value in student.items():
print(f"{key}:{value}")
# dictionary length
print("length of the dictionary:", len(student))
#nested dictinaries
students = {"student1":{"name": "John", "age":20},"student2":{"name": "Johny", "age":21}}
print("nested dictionary:", students)
#dictionary comprehension
squares = {x:x**2 for x in range(5)}
print("dictionary comprehension:",squares)

OUTPUT:

original dictionary: {'name': 'John', 'age': 20, 'courses': ['maths', 'science']}

name: John

courses: ['maths', 'science']

modified dictionary: {'name': 'John', 'age': 21, 'courses': ['maths', 'science']}

dictionary after adding an element: {'name': 'John', 'age': 21, 'courses': ['maths', 'science'],
'grade': 'A'}

dictionary after removing an element: {'name': 'John', 'courses': ['maths', 'science'], 'grade':
'A'}

popped element: A

dictionary after pop: {'name': 'John', 'courses': ['maths', 'science']}

iterating through dictionary:

name:John

courses:['maths', 'science']

length of the dictionary: 2

nested dictionary: {'student1': {'name': 'John', 'age': 20}, 'student2': {'name': 'Johny', 'age':
21}}

dictionary comprehension: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

6. Implement python script for creating and accessing tables.


import pandas as pd

# ceating a data frame(table)


data = {"name":["Alice","Bob","Charlie"],"age":[25,30,35],"city":["new
york","texas","chicago"]

df = pd.DataFrame(data)

print("original dataframe:")

print(df)

#accessing elements

print("\n accessing a single column:")

print(df["name"])

#accessing multiple columns

print("\n accessing multiple columns:")

print(df[["name", "city"]])

#accessing a single row by index

print("\n accessing a single row by index:")

print(df.iloc[1])

#accessing a multiple rows by index

print("\n accessing multiple rows by index:")

print(df.iloc[0:2])

#accessing a single element by row and column index

print("\n accessing a single element by row and column index:")

print(df.iloc[1,2])

#accessing a single element by row and column labels

print("\n accessing a single element by row and column labels:")

print(df.at[1,"city"])

#adding a new column

df["salary"] = [70000, 80000, 90000]

print("\n dataframe after adding a new column:")

print(df)
#removing a column

df = df.drop(columns = ["salary"])

print("\n dataframe after removing a column:")

print(df)

#filtered dataframe

filtered_df = df[df["age"]>25]

print("\n filtered dataframe:")

print(filtered_df)

OUTPUT:
original dataframe:
name age city
0 Alice 25 new york
1 Bob 30 texas
2 Charlie 35 chicago

accessing a single column:


0 Alice
1 Bob
2 Charlie
#Name: name, dtype: object

accessing multiple columns:


name city
0 Alice new york
1 Bob texas
2 Charlie chicago

accessing a single row by index:


name Bob
age 30
city texas
#Name: 1, dtype: object

accessing multiple rows by index:


name age city
0 Alice 25 new york
1 Bob 30 texas

accessing a single element by row and column index:


texas

accessing a single element by row and column labels:


texas

dataframe after adding a new column:


name age city salary
0 Alice 25 new york 70000
1 Bob 30 texas 80000
2 Charlie 35 chicago 90000

dataframe after removing a column:


name age city
0 Alice 25 new york
1 Bob 30 texas
2 Charlie 35 chicago

filtered dataframe:
name age city
1 Bob 30 texas
2 Charlie 35 chicago

7. Implement python scripts using standard mathematical, time, random


functions.
import math
import time
import random
#mathematical functions
print("mathematical functions:")
print("square root of 16:", math.sqrt(16))
print("factorial of 5:",math.factorial(5))
print("cosine of 0:",math.cos(0))
print("logarithm base 10 of 100:",math.log10(100))
#time functions
print("\n time functions")
current_time = time.time()
print("current time(in seconds in epoch):",current_time)
local_time = time.localtime(current_time)
print("local time:", time.strftime("%Y-%m-%d %H:%M:%S", local_time))
print("sleeping for 2 seconds...")
time.sleep(2)
print("awake now!")
#random functions
print("\n random functions:")
print("random integer between 1 and 10:",random.randint(1,10))
print("random float between 0 and 1:", random.random())
print("random choice from a list:",random.choice(['apple','banana','cherry']))
print("random sample of 2 elements from a list:", random.sample([1,2,3,4,5],2))
OUTPUT:
mathematical functions:
square root of 16: 4.0
factorial of 5: 120
cosine of 0: 1.0
logarithm base 10 of 100: 2.0

time functions
current time(in seconds in epoch): 1748810608.4571116
local time: 2025-06-01 20:43:28
sleeping for 2 seconds...
awake now!

random functions:
random integer between 1 and 10: 1
random float between 0 and 1: 0.8157975325119621
random choice from a list: banana
random sample of 2 elements from a list: [3, 2]

8. Implement user defined functions.


#defining a simple function
def greet(name):
return f"Hello {name}!"
#calling the function
print(greet("Alice"))
print(greet("Sita"))
#defining a function with multiple parameters
def add(a,b):
return a+b
print(add(5,3))
#defining a function with default parameters
def multiply(a,b=2):
return a*b
print(multiply(5,3))
#defining a function with variable length arguments
def sum_all(*args):
return sum(args)
print(sum_all(1,2,3,4,5))
#defining a function with keyword arguments
def introduce(name,age,city):
return f"My name is {name}, Iam {age} years old, and I live in {city}."
print(introduce(name = "Joe", age = 26, city ="Pune"))
#defining a function with return value
def square(x):
return x*x
result = square(4)
print(result)
#defining a function with a docstring
def factorial(n):
""" calculating the factorial of a number
args:
n(int): the number to calculate the factorial of
returns:
int: the factorial of a number. """
if n == 0:
return 1
else:
return n * factorial(n-1)
n=5
print(f"factorial of {n} is:",factorial(n))

OUTPUT:
Hello Alice!
Hello Sita!
8
15
15
My name is Joe, Iam 26 years old, and I live in Pune.
16
factorial of 5 is: 120
9. Create a module with two functions one for finding Armstrong number, and
second is for testing whether the given string is palindrome or not. Write a
python application to import the above module some other application.
module.py file
# module.py

def armstrong(num):
sum = 0
temp = num
# Calculate the sum of cubes of digits
while temp > 0:
digit = temp % 10
sum += digit ** 3
temp //= 10
# Check if the sum is equal to the original number
if num == sum:
print(f"{num} is an Armstrong number")
else:
print(f"{num} is NOT an Armstrong number")

def palindrome(st):
j = -1
flag = 0
# Loop to compare each character from start and end
for i in st:
if i != st[j]:
flag = 1
break
j -= 1 # Decrement j to check reverse position
if flag == 1:
print(f"{st} is NOT a palindrome")
else:
print(f"{st} is a palindrome")
main.py file
#create another file which imports the above module, let it be main.py
from module import *
num=int(input("enter the number to check it is Armstrong or not:"))
st=input("enter a string to check whether it is palindrome or not:")
armstrong(num)
palindrome(st)
#note: keep both these files in same directory and run main.py file to get the output.
OUTPUT:
enter the number to check it is Armstrong or not:153
enter a string to check whether it is palindrome or not:radar
153 is an Armstrong number
radar is a palindrome
#Other output:
enter the number to check it is Armstrong or not:141
enter a string to check whether it is palindrome or not: hello
141 is NOT an Armstrong number
hello is NOT a palindrome

10. Implement python script to display file contents.


#function to read and display file contents
def display_file_contents(file_path):
try:
with open(file_path, 'r') as file:
contents = file.read()
print(contents)
except FileNotFoundError:
print(f"the file at {file_path} was not found")
except Exception as e:
print(f"an error occurred:{e}")
#example usage (create a separate text file example.txt and write contents) ,if there is no
#such file you will get file not found in the output
file_path = "example.txt"
display_file_contents(file_path)
example.txt file
Hello!
How are you
OUTPUT:
Hello!
How are you
#in case if file is not created or not present
the file at example.txt was not found

12. Implement python script for performing basic statistical operations.


import statistics
#sample data
data = [10,20,30,40,50,60,70,80,90,100]
# mean
mean_value = statistics.mean(data)
print("mean:",mean_value)
# median
median_value = statistics.median(data)
print("median:",median_value)
# mode
data_with_mode = [1,2,2,3,4,4,4,5,6]
mode_value = statistics.mode(data_with_mode)
print("mode:",mode_value)
#standard deviation
stdev_value = statistics.stdev(data)
print("standard deviation:",stdev_value)
#variance
variance_value = statistics.variance(data)
print("variance:",variance_value)
#minimum
min_value = min(data)
print("minimum:",min_value)
#maximum
max_value = max(data)
print("maximum:",max_value)
#range
range_value = max_value - min_value
print("range:",range_value)
OUTPUT:
mean: 55
median: 55.0
mode: 4
standard deviation: 30.276503540974918
variance: 916.6666666666666
minimum: 10
maximum: 100
range: 90

13. Implement python script for creating and accessing tables.


Same as 6th program

11. Implement python script to copy file contents from one file to another.
Read the file names using command line arguments.

You might also like