0% found this document useful (0 votes)
6 views11 pages

Python Practical Question & Answer

The document provides practical exercises for learning Python, covering topics such as basic input, arithmetic operations, conditional statements, loops, functions, data structures (lists, tuples, dictionaries), and user-defined modules. It also includes NumPy and Pandas practicals for array manipulation, data handling, and visualization using Matplotlib and Seaborn. Each section contains code examples and explanations to facilitate understanding of Python programming and data analysis.

Uploaded by

shubham20011130
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)
6 views11 pages

Python Practical Question & Answer

The document provides practical exercises for learning Python, covering topics such as basic input, arithmetic operations, conditional statements, loops, functions, data structures (lists, tuples, dictionaries), and user-defined modules. It also includes NumPy and Pandas practicals for array manipulation, data handling, and visualization using Matplotlib and Seaborn. Each section contains code examples and explanations to facilitate understanding of Python programming and data analysis.

Uploaded by

shubham20011130
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

Python Practical

Subject: Analytics/Computing with Python.


1. Basic input, variables and arithmetic

# Practical 1: Basic input and arithmetic

name = input("Enter your name: ")


a = float(input("Enter first number: "))
b = float(input("Enter second number: "))

print("\nHello", name)
print("Sum =", a + b)
print("Difference=", a - b)
print("Product =", a * b)
print("Quotient =", a / b if b != 0 else "Division by zero not allowed")

2. Conditional statements (grading system)

# Practical 2: Grade using if-elif-else

marks = float(input("Enter marks (0–100): "))

if marks >= 90:


grade = "A+"
elif marks >= 80:
grade = "A"
elif marks >= 70:
grade = "B"
elif marks >= 60:
grade = "C"
else:
grade = "D"

print("Grade:", grade)

3. Loops (sum of first N natural numbers)

# Practical 3: Sum of first N natural numbers

n = int(input("Enter N: "))
total = 0
for i in range(1, n + 1):
total += i

print("Sum of first", n, "natural numbers is:", total)

4. Functions (factorial of a number)

# Practical 4: Factorial using function

def factorial(n):
result = 1
for i in range(2, n + 1):
result *= i
return result

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


print("Factorial of", num, "is", factorial(num))

5. Lists, tuples, dictionaries – basic operations

# Practical 5: List, tuple, dict examples

# List
numbers = [10, 20, 30, 40]
[Link](50)
print("List:", numbers)

# Tuple
coords = (5, 10, 15)
print("Tuple:", coords)

# Dictionary
student = {"name": "Pawan", "age": 25, "course": "Data Science"}
student["age"] = 26
print("Dictionary:", student)

6. User-defined module usage (simple)

# [Link]
def add(a, b):
return a + b
def square(x):
return x * x

Then use it in another file / cell:

# Using user-defined module

import mymath

print("Addition:", [Link](3, 4))


print("Square:", [Link](5))

NumPy Practical

7. Create 1D and 2D arrays, basic properties

import numpy as np

arr1 = [Link]([1, 2, 3, 4, 5])


arr2 = [Link]([[1, 2, 3],
[4, 5, 6]])

print("1D Array:", arr1)


print("2D Array:\n", arr2)

print("arr1 dtype:", [Link])


print("arr2 shape:", [Link])

8. Array indexing, slicing, and broadcasting

import numpy as np

arr = [Link]([10, 20, 30, 40, 50])

print("Original:", arr)
print("First element:", arr[0])
print("Slice [1:4]:", arr[1:4])

# Broadcasting: add 5 to all elements


print("After adding 5:", arr + 5)

9. Vectorized operations and basic statistics


import numpy as np

data = [Link]([12, 15, 20, 22, 25, 30])

print("Data:", data)
print("Sum:", [Link](data))
print("Mean:", [Link](data))
print("Median:", [Link](data))
print("Standard Deviation:", [Link](data))

[Link] and stacking arrays

import numpy as np

arr = [Link](1, 13) # 1 to 12


print("Original:", arr)

reshaped = [Link](3, 4)
print("Reshaped (3x4):\n", reshaped)

a = [Link]([1, 2, 3])
b = [Link]([4, 5, 6])

print("Vertical stack:\n", [Link]((a, b)))


print("Horizontal stack:", [Link]((a, b)))

[Link] numbers in NumPy

import numpy as np

# Random floats between 0 and 1


rand_arr = [Link](3, 3)
print("Random 3x3 array:\n", rand_arr)

# Random integers between 1 and 100


rand_int = [Link](1, 101, size=10)
print("Random integers:", rand_int)

[Link] comparison list vs NumPy

import numpy as np
import time
n = 1000000

# Python list
py_list = list(range(n))
start = [Link]()
py_sq = [x * x for x in py_list]
print("List time:", [Link]() - start)

# NumPy array
np_arr = [Link](n)
start = [Link]()
np_sq = np_arr * np_arr
print("NumPy time:", [Link]() - start)

Pandas Practical

13. Create Series and DataFrame

import pandas as pd

# Series
s = [Link]([10, 20, 30, 40], name="Marks")
print("Series:\n", s)

# DataFrame
data = {
"Name": ["Aman", "Bhawna", "Pawan"],
"Age": [20, 21, 25],
"Marks": [85, 90, 95],
}
df = [Link](data)
print("\nDataFrame:\n", df)

14. Read CSV and basic inspection

import pandas as pd

df = pd.read_csv("[Link]") # ensure file exists


print("Head:\n", [Link]())
print("\nInfo:")
print([Link]())
print("\nDescribe:\n", [Link]())
15. Selecting rows/columns with loc and iloc

import pandas as pd

data = {
"Name": ["A", "B", "C", "D"],
"Age": [18, 20, 22, 24],
"Marks": [70, 80, 90, 85],
}
df = [Link](data, index=["s1", "s2", "s3", "s4"])

print("Using loc (label):\n", [Link]["s2":"s4", ["Name", "Marks"]])


print("\nUsing iloc (position):\n", [Link][1:4, 0:2])

16. Filtering, sorting, and adding new column

import pandas as pd

data = {
"Name": ["A", "B", "C", "D"],
"Age": [19, 21, 20, 23],
"Marks": [60, 85, 75, 90],
}
df = [Link](data)

# Filter
filtered = df[df["Marks"] >= 75]
print("Filtered (Marks >= 75):\n", filtered)

# New column
df["Result"] = df["Marks"].apply(lambda x: "Pass" if x >= 40 else "Fail")
print("\nWith Result column:\n", df)

# Sorted by Marks descending


print("\nSorted by Marks:\n", df.sort_values(by="Marks", ascending=False))

17. Handling missing values

import pandas as pd
import numpy as np
data = {
"Name": ["A", "B", "C", "D"],
"Marks": [90, [Link], 75, [Link]]
}
df = [Link](data)

print("Original:\n", df)

# Drop rows with NaN


dropped = [Link]()
print("\nAfter dropna:\n", dropped)

# Fill NaN with mean


mean_marks = df["Marks"].mean()
filled = [Link]({"Marks": mean_marks})
print("\nAfter filling NaN with mean:\n", filled)

18. Groupby and aggregation

import pandas as pd

data = {
"Student": ["A", "B", "C", "D", "E", "F"],
"Course": ["Python", "Python", "ML", "DBMS", "ML", "Python"],
"Marks": [80, 85, 90, 70, 88, 92],
}
df = [Link](data)

grouped = [Link]("Course")["Marks"].mean()
print("Average marks per course:\n", grouped)

19. Merge / Join DataFrames

import pandas as pd

students = [Link]({
"Roll": [1, 2, 3],
"Name": ["Aman", "Bhawna", "Pawan"]
})

marks = [Link]({
"Roll": [1, 2, 3],
"Marks": [85, 90, 95]
})

merged = [Link](students, marks, on="Roll")


print("Merged DataFrame:\n", merged)

Matplotlib Practical

[Link] chart

import [Link] as plt

years = [2020, 2021, 2022, 2023, 2024]


students = [40, 45, 50, 48, 55]

[Link](years, students, marker="o")


[Link]("Number of Students Over Years")
[Link]("Year")
[Link]("Students")
[Link](True)
[Link]()

21. Bar chart

import [Link] as plt

subjects = ["Python", "ML", "DBMS", "OS"]


marks = [88, 92, 75, 80]

[Link](subjects, marks)
[Link]("Marks in Different Subjects")
[Link]("Subjects")
[Link]("Marks")
[Link]()

22. Histogram
import [Link] as plt

marks = [45, 50, 55, 60, 65, 70, 80, 85, 90, 95, 40, 75, 68, 72]

[Link](marks, bins=5, edgecolor="black")


[Link]("Marks Distribution")
[Link]("Marks Range")
[Link]("Frequency")
[Link]()

23. Scatter plot

import [Link] as plt

hours = [1, 2, 3, 4, 5, 6, 7]
marks = [30, 40, 50, 55, 65, 75, 85]

[Link](hours, marks)
[Link]("Hours Studied vs Marks")
[Link]("Hours Studied")
[Link]("Marks")
[Link](True)
[Link]()

24. Pie chart

import [Link] as plt

labels = ["A Grade", "B Grade", "C Grade", "D Grade"]


sizes = [10, 15, 20, 5]

[Link](sizes, labels=labels, autopct="%1.1f%%", startangle=90)


[Link]("Grade Distribution")
[Link]("equal") # equal aspect ratio
[Link]()
Seaborn Practical

25. Histogram / distribution plot

import seaborn as sns


import [Link] as plt

marks = [45, 50, 55, 60, 65, 70, 80, 85, 90, 95, 40, 75, 68, 72]

[Link](marks, kde=True)
[Link]("Marks Distribution (Seaborn)")
[Link]("Marks")
[Link]("Frequency")
[Link]()

26. Countplot (category counts)

import seaborn as sns


import [Link] as plt
import pandas as pd

data = {
"Course": ["Python", "Python", "ML", "DBMS", "ML", "Python", "DBMS"],
}
df = [Link](data)

[Link](x="Course", data=df)
[Link]("Count of Students in Each Course")
[Link]()

27. Boxplot (spread of marks by course)

import seaborn as sns


import [Link] as plt
import pandas as pd

data = {
"Course": ["Python", "Python", "ML", "ML", "DBMS", "DBMS"],
"Marks": [85, 90, 75, 88, 70, 65]
}
df = [Link](data)

[Link](x="Course", y="Marks", data=df)


[Link]("Marks Distribution by Course")
[Link]()

28. Pairplot (relationships between numerical variables)

import seaborn as sns


import [Link] as plt
import pandas as pd

data = {
"Maths": [60, 70, 80, 90, 85],
"Science": [65, 75, 82, 88, 90],
"English": [55, 68, 78, 85, 80]
}
df = [Link](data)

[Link](df)
[Link]("Pairplot of Subjects", y=1.02)
[Link]()

29. Heatmap of correlation

import seaborn as sns


import [Link] as plt
import pandas as pd

data = {
"Maths": [60, 70, 80, 90, 85],
"Science": [65, 75, 82, 88, 90],
"English": [55, 68, 78, 85, 80]
}
df = [Link](data)

corr = [Link]()
print("Correlation:\n", corr)

[Link](corr, annot=True)
[Link]("Correlation Heatmap")
[Link]()

You might also like