0% found this document useful (0 votes)
7 views6 pages

Asignment Python

The document provides an overview of Python data structures, including lists, tuples, dictionaries, and sets, highlighting their features and differences. It also covers string manipulation, NumPy arrays, data visualization using Matplotlib, error handling, functions, loops, dictionaries, and file handling. Additionally, it discusses the advantages of using NumPy for numerical operations and when to use different types of plots for data analysis.
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)
7 views6 pages

Asignment Python

The document provides an overview of Python data structures, including lists, tuples, dictionaries, and sets, highlighting their features and differences. It also covers string manipulation, NumPy arrays, data visualization using Matplotlib, error handling, functions, loops, dictionaries, and file handling. Additionally, it discusses the advantages of using NumPy for numerical operations and when to use different types of plots for data analysis.
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

Q1.

Python Data Structures:


a) Difference between List, Tuple, Dictionary, and Set:

Feature List Tuple Dictionary Set

Mutability Mutable (changeable) Immutable (cannot Mutable Mutable


change)

Element By index By index By key No index


Access

Storage Ordered, allows Ordered, allows Key–value Unordered, no


duplicates duplicates pairs duplicates

b) Python Code:
# Creating data structures
my_list = [10, 20, 30]
my_tuple = (1, 2, 3)
my_dict = {"name": "Ali", "age": 20}
my_set = {5, 10, 15}

# Adding elements
my_list.append(40)
my_dict["city"] = "Lahore"

# Removing elements
my_list.remove(20)
my_set.remove(10)

# Accessing elements
print(my_list[0]) # List
print(my_tuple[1]) # Tuple
print(my_dict["name"]) # Dictionary
print(list(my_set)[0]) # Set (converted to list)

c) Real-World Examples:

 List: Storing a grocery shopping list.


 Tuple: Storing GPS coordinates (Latitude, Longitude) because they shouldn't change.
 Dictionary: A phonebook where names are keys and numbers are values.
 Set: Storing unique User IDs for a website to avoid duplicates.

Q2. Strings and Lists:


a) Count vowels in a string:
string = input("Enter a string: ")
vowels = "aeiouAEIOU"
count = 0

for char in string:


if char in vowels:
count += 1

print("Number of vowels:", count)


b) Max, Min, and Average:
numbers = [10, 20, 30, 40, 50]

maximum = max(numbers)
minimum = min(numbers)
average = sum(numbers) / len(numbers)

print("Maximum:", maximum)
print("Minimum:", minimum)
print("Average:", average)

c) Remove duplicates without set( ):


numbers = [1, 2, 2, 3, 4, 4, 5]
unique_list = []

for num in numbers:


if num not in unique_list:
unique_list.append(num)

print("List without duplicates:", unique_list)

Q3. NumPy Arrays:


a) Explanation:
 NumPy Array: A powerful N-dimensional array object used for numerical computing.
 Indexing: Accessing specific elements using coordinates.
 Slicing: Extracting a portion of the array (e.g., arr[0:2]).
 Reshaping: Changing the shape (dimensions) of an array without changing its data.
 Broadcasting: How NumPy treats arrays with different shapes during arithmetic operations.

b) NumPy Code:
import numpy as np

# Create 3x3 matrix


matrix = [Link]([[1,2,3],[4,5,6],[7,8,9]])

# Replace second row


matrix[1] = 5

# Multiply by scalar
matrix = matrix * 2

# Find mean, max, sum


print("Mean:", [Link]())
print("Maximum:", [Link]())
print("Sum:", [Link]())

# Reshape to 1x9
reshaped = [Link](1,9)
print(reshaped)
Q4. Data Visualization Using Matplotlib:
a) Explanation:

Data Visualization is the process of representing data in graphical or visual form such as charts, graphs,
plots, and diagrams. It helps in converting large and complex datasets into an easy-to-understand visual
format.

Importance in Data Science:

1. Better Understanding of Data: Visuals make it easier to understand trends, patterns, and
relationships in data.
2. Quick Decision Making: Graphs allow data scientists and decision-makers to analyze information
quickly.
3. Identifying Patterns and Outliers: Visualization helps in spotting unusual data points, trends, or
errors.
4. Effective Communication: Complex results can be explained clearly to non-technical people using
charts.
5. Data Exploration: It helps data scientists explore data before applying machine learning or
statistical models.

b) Python Code:
import [Link] as plt

x = [1,2,3,4]
y = [10,20,30,40]

# Line Chart
[Link](x, y)
[Link]("Line Chart")
[Link]()

# Bar Chart
[Link](x, y)
[Link]("Bar Chart")
[Link]()

# Scatter Plot
[Link](x, y)
[Link]("Scatter Plot")
[Link]()

c) Real-World Applications:

 Line Chart: Tracking Stock Market prices over time.


 Bar Chart: Comparing sales of different products in a month.
 Scatter Plot: Showing the relationship between study hours and exam scores.

Q5.
a) List vs Tuple: Lists are mutable (can change), while Tuples are immutable (cannot change after
creation).

b) List vs NumPy: NumPy arrays are faster, more memory efficient, and support element-wise calculations,
unlike Python lists.
c) Purpose of Visualization: To simplify complex data and communicate insights effectively to
stakeholders.

Q6. Error Handling


a) Exception in python:
An exception is an error that occurs during program execution.

b) Code
try:
a = int(input("Enter number: "))
b = int(input("Enter divisor: "))
result = a / b
print("Result:", result)
except ZeroDivisionError:
print("Error: Division by zero is not allowed")

Q7. Write the output of the following code and justify:


Code:
values = [1, 3, 5, 7]
[Link](9)
[Link](1, 4)
print(values)

Output:
[1, 4, 3, 5, 7, 9]

Justification:

 append(9) adds 9 at the end


 insert(1,4) adds 4 at index 1

Q8. Functions in Python:


a) Definition: A reusable block of code that performs a specific task.

b) Code:
def sum_and_average(numbers):
total = sum(numbers)
avg = total / len(numbers)
return total, avg

nums = [10, 20, 30]


s, a = sum_and_average(nums)
print("Sum:", s)
print("Average:", a)

c) Benefit:
Functions reduce code repetition, make debugging easier, and improve readability.
Q9. Loops and Conditions:
num = int(input("Enter a number: "))

if num % 2 == 0:
print("Even number")
print("Square:", num ** 2)
else:
print("Odd number")
print("Cube:", num ** 3)

Q10. Dictionaries:
a) Create a dictionary to store student information:
students = {
1: {"name": "Ali", "marks": 85},
2: {"name": "Sara", "marks": 90}
}

b): Python Code:


# Add new student
students[3] = {"name": "Ahmed", "marks": 88}

# Update marks
students[1]["marks"] = 95

# Display records
for roll, info in [Link]():
print(roll, info)

c) Why are dictionaries preferred over lists in such cases?

 Dictionaries store data in key–value form, which makes access easy.


 Data can be accessed directly using roll number (key).
 Searching is faster than lists.
 Data remains well-organized and structured.
 Easy to update, add, or remove student records.
Q11. File Handling
a) Define:

File handling in Python is the process of creating, opening, reading, writing, and closing files.
It allows programs to store data permanently in files and retrieve it whenever needed, instead of losing data
when the program ends.

b) Code
# Write to file
file = open("[Link]", "w")
[Link]("Ali\nSara\nAhmed")
[Link]()

# Read file
file = open("[Link]", "r")
print([Link]())
[Link]()

Q12.
a) Why is NumPy faster than Python lists?
NumPy is faster because it uses optimized C-based code and stores data in continuous memory blocks,
which makes mathematical and numerical operations faster and more efficient than Python lists.

b) When would you prefer a scatter plot over a line plot?


A scatter plot is preferred when we want to analyze the relationship or correlation between two variables
and when the data points are independent and not in a specific order.

You might also like