0% found this document useful (0 votes)
9 views25 pages

Python for Data Analysis Basics

The document provides a comprehensive overview of Python's applications in data analysis, including data cleaning, visualization, and manipulation. It covers fundamental concepts such as data types, control structures, functions, and file operations, along with examples and coding snippets. Additionally, it discusses the advantages of Python and its libraries like NumPy and Pandas, emphasizing its beginner-friendly nature and real-life applications.
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)
9 views25 pages

Python for Data Analysis Basics

The document provides a comprehensive overview of Python's applications in data analysis, including data cleaning, visualization, and manipulation. It covers fundamental concepts such as data types, control structures, functions, and file operations, along with examples and coding snippets. Additionally, it discusses the advantages of Python and its libraries like NumPy and Pandas, emphasizing its beginner-friendly nature and real-life applications.
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

1

1.

(a) List any two uses of Python in data analysis.


Answer:

 Data cleaning

 Data visualizaton

(b) Write any one feature of the Python environment.


Answer:

 It provides an interactve interpreter for immediate code executon.

(c) Give an example of a valid Python identier.


Answer:

 student_name

2.

(a) What are immutable data types?


Answer:
Data types whose values cannot be changed once created.

(b) Give one example each of: string, tuple, and integer.
Answer:

 String: "hello"

 Tuple: (1, 2, 3)

 Integer: 25

(c) Write a Python command to create a list with 5 numbers.


Answer:

nums = [1, 2, 3, 4, 5]

3.

(a) What is the purpose of the if statement?


Answer:
To make decisions and execute code based on conditons.

(b) Write the syntax of a for loop.


Answer:

for variable in sequence:

statements
2

(c) Give one example of a comparison operator.


Answer:
>=

4.

(a) Deine a user-deined functon.


Answer:
A functon created by the user to perform a speciic task.

(b) Write the general syntax.


Answer:

def functon_name(parameters):

body

(c) Give an example of a functon call.


Answer:

result = add(5, 3)

5.

(a) Name any two ile formats used for input/output.


Answer:

 .txt

 .csv

(b) Write a Python code snippet to open a ile.


Answer:

f = open("[Link]", "r")

(c) Menton one diference between reading and writng modes.


Answer:

 "r" opens a ile for reading.

 "w" creates a ile for writng (overwrites existng content).

6.

(a) What is a dictonary?


Answer:
A data structure that stores data as key–value pairs.

(b) Write one example of a key–value pair.


Answer:
"name": "Rahul"
3

(c) Menton one advantage of dictonaries.


Answer:
Fast retrieval using keys.

7.

(a) What is the role of loops?


Answer:
To repeat a block of code multple tmes.

(b) Example of a while loop header.


Answer:

while i < 10:

(c) One use of loops in data analysis.


Answer:
Iteratng through rows of a dataset.

ESSAY QUESTIONS WITH ANSWERS

1.

(a) Explain the use of Python in data analysis.


Answer:
Python helps in cleaning, manipulatng, analyzing, and visualizing data.

(b) Two Python libraries used for data analysis.


Answer:

 NumPy

 Pandas

(c) Describe the Python interactve environment.


Answer:
It allows executng commands line by line using IDLE or Jupyter Notebook.

(d) Two advantages of using Python.


Answer:

 Easy to learn

 Rich library support

(e) One real-life applicaton.


Answer:
Predictng weather using data analysis.
4

2.

(a) Explain numbers, lists, tuples, sets, and dictonaries with examples.
Answer:

 Number: x = 10

 List: [1, 2, 3]

 Tuple: (4, 5, 6)

 Set: {1, 2, 3}

 Dictonary: {"name": "Asha"}

(b) One diference between lists and tuples.


Answer:
Lists are mutable, tuples are immutable.

(c) Code to convert a list to a set.


Answer:

set_data = set([1, 2, 3])

(d) Use of dictonary keys.


Answer:
Keys allow quick access to values.

(e) Practcal applicaton of sets.


Answer:
Removing duplicate values in data.

3.

(a) Explain if-elif-else with syntax.


Answer:

if conditon1:

statements

elif conditon2:

statements

else:

statements

(b) Program to print 1 to 10.


Answer:

for i in range(1, 11):

print(i)
5

(c) Purpose of indentaton.


Answer:
Indentaton deines code blocks in Python.

(d) One use of loops in data cleaning.


Answer:
Detectng missing values row by row.

(e) Example of a nested loop.


Answer:

for i in range(3):

for j in range(2):

print(i, j)

4.

(a) Deine and explain user-deined functons.


Answer:
Functons writen by the user to modularize code and improve reusability.

(b) Functon returning square of a number.


Answer:

def square(n):

return n*n

(c) Meaning of parameters and arguments.


Answer:

 Parameters: variables in functon deiniton

 Arguments: values passed when calling the functon

(d) Advantages of functons.


Answer:

 Avoid repetton

 Improve readability

(e) Example with default argument.


Answer:

def greet(name="Student"):

print("Hello", name)

5.
6

(a) Explain input/output operatons.


Answer:
They allow reading data from iles and writng processed results back to iles.

(b) Code to read a CSV ile.


Answer:

import pandas as pd

df = pd.read_csv("[Link]")

(c) Code to write a list into a text ile.


Answer:

nums = [1,2,3]

with open("[Link]", "w") as f:

for x in nums:

[Link](str(x) + "\n")

(d) Two common ile errors.


Answer:

 File not found

 Permission denied

(e) Why proper ile closing is important?


Answer:
It prevents data loss and frees system resources.

3-MARK QUESTIONS WITH ANSWERS

1.

(a) Menton two advantages of Python for data analysis.


(b) Name one Python environment used in data science.
(c) Why is Python considered beginner-friendly?

Answer:

(a) Simple syntax, large library support (NumPy, Pandas).


(b) Jupyter Notebook / Anaconda.
(c) Indentaton-based structure makes reading and writng code easy.

2.

(a) What is Python syntax?


(b) Give one example of a valid Python statement.
(c) Write one rule for naming identiers.
7

Answer:

(a) The set of rules that deine how Python code must be writen.
(b) x = 10
(c) Identier cannot start with a number.

3.

(a) Give an example of integer, foat, and string.


(b) What kind of data structure is a list?
(c) Write Python code to access the 2nd element of a list.

Answer:

(a) 5, 3.14, "hello"


(b) Ordered and mutable sequence.
(c)

mylist[1]

4.

(a) Deine tuple.


(b) Write one diference between tuple and list.
(c) Create a tuple of 3 names.

Answer:

(a) Immutable ordered collecton.


(b) List is mutable; tuple is immutable.
(c)

t = ("Asha", "Rahul", "Manu")

5.

(a) What is a set?


(b) Menton one advantage of sets.
(c) Write a Python command to remove an element.

Answer:

(a) Unordered collecton of unique elements.


(b) Automatcally removes duplicates.
(c)

[Link](3)

6.
8

(a) Write the syntax of an if-else statement.


(b) State one use of loops.
(c) Write one for-loop header.

Answer:

(a)

if conditon:

statements

else:

statements

(b) Repeatng tasks like printng or iteraton.


(c)

for i in range(5):

7.

(a) What is a user-deined functon?


(b) State one beneit of functons.
(c) Write a functon with one parameter.

Answer:

(a) Functon deined by the programmer using def.


(b) Reusability.
(c)

def greet(name):

print("Hello", name)

8.

(a) Name any two ile formats used for input/output.


(b) Write the command to open a ile in write mode.
(c) Why is with open() preferred?

Answer:

(a) .txt, .csv


(b)

open("[Link]","w")

(c) Automatcally closes the ile.


9

5-MARK QUESTIONS WITH ANSWERS

1.

(a) Explain Python’s usefulness in data analysis.


(b) Name two popular Python libraries.
(c) Deine interpreted executon.
(d) List two features of Python.
(e) Give one applicaton of Python in real-life.

Answer:

(a) Used for cleaning, analyzing, and visualizing data.


(b) Pandas, NumPy.
(c) Code is executed line-by-line.
(d) Easy syntax, cross-platorm.
(e) Stock market predicton.

2.

(a) Deine numbers, strings, lists, sets, dictonaries (with examples).


(b) One list operaton.
(c) One set operaton.
(d) Use of dictonary keys.
(e) Convert a list into a dictonary.

Answer:

(a)

 Number: x = 10

 String: "hello"

 List: [1,2,3]

 Set: {1,2,3}

 Dictonary: {"a": 10}

(b) append()
(c) add()
(d) Keys allow quick access to values.
(e)

lst = ["a","b","c"]

d = {i: lst[i] for i in range(len(lst))}

3.
10

(a) Explain the role of control structures.


(b) Write syntax of if-elif-else.
(c) Program to print even numbers from 1–20.
(d) Diference between for and while loop.
(e) Give one example of nested loop usage.

Answer:

(a) They control program fow and decision making.


(b)

if c1:

s1

elif c2:

s2

else:

s3

(c)

for i in range(1,21):

if i%2==0:

print(i)

(d)

 for → ixed iteraton

 while → conditon-based iteraton


(e) Printng matrix rows and columns.

4.

(a) Deine user-deined functons.


(b) Write a functon to check positve/negatve.
(c) Diference between return and print.
(d) Example of a functon with multple parameters.
(e) Functon call with keyword arguments.

Answer:

(a) Programmer-deined reusable code blocks.


(b)

def check(n):

if n>0: print("Positve")

else: print("Negatve")
11

(c) return sends value back; print displays it.


(d)

def add(a,b):

return a+b

(e)

add(b=3, a=5)

5.

(a) Deine input/output operatons in Python.


(b) Code to read all lines from a ile.
(c) Code to append a new line.
(d) Two common errors in ile handling.
(e) Why must iles be closed?

Answer:

(a) Reading/writng data to external iles.


(b)

with open("[Link]","r") as f:

print([Link]())

(c)

with open("[Link]","a") as f:

[Link]("New line\n")

(d)

 FileNotFoundError

 PermissionError
(e) Prevents data loss and releases resources.

6.

(a) Deine list, tuple, set, dictonary, string.


(b) Give one example for each.
(c) Program to create a dictonary of 3 students.
(d) Program to convert string → list.
(e) Program to remove duplicates using set.

Answer:

(a)

 List: ordered mutable


12

 Tuple: ordered immutable

 Set: unordered unique

 Dictonary: key-value

 String: sequence of characters

(b)
[1,2], (1,2), {1,2}, {"a":1}, "abc"

(c)

d = {"A":50, "B":60, "C":55}

(d)

list("hello")

(e)

s = set([1,2,2,3])

7.

(a) Deine Python syntax.


(b) Menton two rules for writng correct Python code.
(c) Program to compute area of a circle.
(d) Code to take input for name & age.
(e) Why does indentaton error occur?

Answer:

(a) Structure and rules of Python statements.


(b) Proper indentaton, no special symbols in identiers.
(c)

r=5

area = 3.14 * r * r

print(area)

(d)

name = input()

age = int(input())

(e) Occurs when spacing/tabs are misplaced.

3-MARK PROGRAMMING QUESTIONS

3-Mark Question 1
13

Tasks:

(a) Create a list of 6 numbers.


(b) Print only the numbers greater than 20.
(c) Print how many such numbers exist.

Answer

nums = [5, 22, 17, 35, 9, 48] # create a list of integers

greater_20 = [] # empty list to store numbers > 20

for x in nums: # loop through each number in list

if x > 20: # check if number is greater than 20

greater_20.append(x) # add number to new list

print("Numbers > 20:", greater_20) # print iltered numbers

print("Count:", len(greater_20)) # print how many numbers satsfy conditon

3-Mark Question 2

Tasks:

(a) Take a string from user.


(b) Print number of words.
(c) Print the irst word.

Answer

s = input("Enter a sentence: ") # take string input

words = [Link]() # split into list of words

print("Total words:", len(words))# print number of words

print("First word:", words[0]) # print the irst word

3-Mark Question 3

Tasks:

(a) Create a tuple of 5 fruits.


(b) Convert it into a list.
(c) Replace the 2nd element with "banana".
14

Answer

fruits = ("apple", "mango", "grape", "orange", "kiwi") # create tuple

lst = list(fruits) # convert tuple to list to modify

lst[1] = "banana" # replace second element (index 1)

print("Updated list:", lst) # display updated list

3-Mark Question 4

Tasks:

(a) Create a dictonary of 3 employee names and salaries.


(b) Increase each salary by 5%.
(c) Print updated dictonary.

Answer

emp = {"Ajay": 30000, "Meera": 45000, "Salim": 38000} # dictonary with salaries

for k in emp: # loop through each employee

emp[k] = emp[k] * 1.05 # increase salary by 5%

print("Updated Salaries:", emp) # print updated dictonary

3-Mark Question 5

Tasks:

(a) Write a functon to return cube of a number.


(b) Call it for 4.
(c) Print result.

Answer

def cube(n): # deine functon

return n * n * n # return cube

result = cube(4) # call functon with argument 4


15

print("Cube =", result) # print result

5-MARK PROGRAMMING QUESTIONS

5-Mark Question 1

Tasks:

(a) Create a list of numbers.


(b) Count positve numbers.
(c) Count negatve numbers.
(d) Count zero occurrences.
(e) Print all three counts.

Answer

nums = [10, -3, 0, 45, -7, 0, 22] # list with positve, negatve, and zeros

pos = 0 # counter for positve numbers

neg = 0 # counter for negatve numbers

zero = 0 # counter for zeros

for x in nums: # loop through each number

if x > 0: # check positve

pos += 1

elif x < 0: # check negatve

neg += 1

else: # remaining are zeros

zero += 1

print("Positve:", pos) # print count of positves

print("Negatve:", neg) # print count of negatves

print("Zeros:", zero) # print count of zeros

5-Mark Question 2

Tasks:

(a) Accept 5 numbers from user.


(b) Store them in a list.
16

(c) Find average.


(d) Print numbers greater than average.
(e) Print count of those numbers.

Answer

nums = [] # empty list

for i in range(5): # loop 5 tmes

n = int(input("Enter number: ")) # take input

[Link](n) # store in list

avg = sum(nums) / len(nums) # calculate average

greater = [x for x in nums if x > avg] # list of numbers > average

print("Average =", avg) # print average

print("Numbers > average:", greater) # print iltered list

print("Count =", len(greater)) # count of such numbers

5-Mark Question 3

Tasks:

(a) Deine functon string_info(s)


(b) Count vowels
(c) Count consonants
(d) Count digits
(e) Return all values

Answer

def string_info(s): # functon to analyse string

vowels = "aeiouAEIOU" # vowel list

vowel_count = 0 # counter for vowels

consonant_count = 0 # counter for consonants

digit_count = 0 # counter for digits

for ch in s: # loop through each character


17

if ch in vowels: # check vowel

vowel_count += 1

elif [Link](): # check digit

digit_count += 1

elif [Link](): # check alphabet (remaining are consonants)

consonant_count += 1

return vowel_count, consonant_count, digit_count # return all results

# calling the functon

v, c, d = string_info("Python123 Example")

print("Vowels:", v) # print vowels

print("Consonants:", c) # print consonants

print("Digits:", d) # print digits

5-Mark Question 4

Tasks:

(a) Create a dictonary of 4 products and prices.


(b) Give 10% discount on each.
(c) Remove the costliest product.
(d) Add a new product.
(e) Print inal dictonary.

Answer

products = {"Pen": 10, "Book": 120, "Bag": 550, "Botle": 80} # dictonary of products

# Apply 10% discount

for k in products:

products[k] = products[k] * 0.90 # reduce each price by 10%

# Remove costliest product

highest = max(products, key=[Link]) # get product with highest price


18

del products[highest] # delete that item

products["Pencil"] = 5 # add new product

print("Final product list:", products) # print updated dictonary

5-Mark Question 5

Tasks:

(a) Open a ile named [Link] in write mode


(b) Write 5 marks into the ile
(c) Close ile
(d) Reopen ile and read lines
(e) Print highest mark

Answer

# Step 1: writng the ile

f = open("[Link]", "w") # open ile in write mode

[Link]("45\n") # write marks (each on new line)

[Link]("78\n")

[Link]("88\n")

[Link]("56\n")

[Link]("90\n")

[Link]() # close ile

# Step 2: reading the ile

f = open("[Link]", "r") # reopen in read mode

lines = [Link]() # read all lines into list

[Link]() # close again

marks = [int([Link]()) for x in lines] # convert text to integers

print("Highest mark:", max(marks)) # print highest value


19

3-MARK PROGRAMMING QUESTIONS WITH ANSWERS

(Each questio iocludes at least 3 tasks, as required)

3-Mark Question 1

Q1. Write a Python program to:

a) Create a list of numbers


b) Find the largest number in the list
c) Convert the list into a tuple

Answer

nums = [10, 25, 5, 60, 18] # create a list of integers

print("Largest:", max(nums)) # max() gives largest number in the list

nums_tuple = tuple(nums) # convert list into a tuple using tuple()

print("Tuple:", nums_tuple) # display the resultng tuple

3-Mark Question 2

Q2. Write a Python program to:

a) Store a string
b) Find the length of the string
c) Convert the string into uppercase

Answer

s = "Python Programming" # store a string in variable s

print("Length:", len(s)) # len() counts number of characters

print("Uppercase:", [Link]()) # upper() converts all characters to uppercase

3-Mark Question 3

Q3. Write a Python program to:

a) Create a dictonary
b) Add a new key–value pair
c) Display all keys

Answer

data = {"name": "Ravi", "age": 21, "course": "Python"} # create dictonary


20

data["year"] = 2025 # add new key-value pair

print("Keys:", [Link]()) # keys() prints all dictonary keys

3-Mark Question 4

Q4. Write a Python program to:

a) Read a number from user


b) Check whether the number is even
c) Otherwise print odd

Answer

n = int(input("Enter a number: ")) # read user input and convert to int

if n % 2 == 0: # if divisible by 2 → even

print("Even number") # print even

else:

print("Odd number") # otherwise odd

3-Mark Question 5

Q5. Write a Python program to:

a) Generate numbers from 1 to 10


b) Print only even numbers
c) Print the sum of all even numbers

Answer

nums = list(range(1, 11)) # generate numbers 1 to 10

evens = [x for x in nums if x % 2 == 0] # select even numbers using list comprehension

print("Even numbers:", evens) # print even numbers

print("Sum =", sum(evens)) # sum() adds all even numbers

3-Mark Question 6

Q6. Write a Python program to:

a) Deine a functon to compute square


b) Return the square value
c) Print the result
21

Answer

def square(x): # deine a functon with parameter x

return x * x # compute and return square

result = square(7) # call the functon with argument 7

print("Square:", result) # print the result

3-Mark Question 7

Q7. Write a Python program to:

a) Open a ile in write mode


b) Write three lines into the ile
c) Close the ile

Answer

f = open("[Link]", "w") # open ile in write mode

[Link]("First line\n") # write irst line to ile

[Link]("Second line\n") # write second line

[Link]("Third line\n") # write third line

[Link]() # close the ile

5-MARK PROGRAMMING QUESTIONS WITH ANSWERS

5-Mark Question 1

Q1. Write a Python program to:

a) Create a list
b) Reverse the list manually
c) Print the reversed list
d) Find the maximum value
e) Find the minimum value

Answer

nums = [10, 3, 55, 26, 8, 91, 42, 19] # list of numbers

rev = [] # empty list to store reversed values


22

for x in nums: # loop through each number

rev = [x] + rev # add each element at front → reversed order

print("Reversed:", rev) # print reversed list

print("Max:", max(rev)) # max() inds largest number

print("Min:", min(rev)) # min() inds smallest number

5-Mark Question 2

Q2. Write a Python program to:

a) Read a string
b) Count number of vowels
c) Replace spaces with '-'
d) Convert to lowercase
e) Print both results

Answer

s = input("Enter a string: ") # read string from user

vowels = "aeiouAEIOU" # list of vowel characters

count = sum(1 for ch in s if ch in vowels) # count vowels using generator

modiied = [Link](" ", "-").lower() # replace spaces and convert to lowercase

print("Vowel count:", count) # display vowel count

print("Modiied string:", modiied) # display modiied string

5-Mark Question 3

Q3. Write a Python program to:

a) Create a tuple
b) Convert tuple into list
c) Modify the list
d) Convert list back to tuple
e) Print the inal tuple

Answer

t = (1, 2, 3, 4, 5, 6) # original tuple


23

lst = list(t) # convert tuple to list

[Link](7) # add new value

[Link](8)

[Link](3) # remove value 3

t2 = tuple(lst) # convert list back to tuple

print("Final tuple:", t2) # print inal tuple

5-Mark Question 4

Q4. Write a Python program to:

a) Deine a functon
b) Compute sum of list
c) Compute average
d) Count elements greater than average
e) Return and print results

Answer

def analyze_list(lst): # deine functon

total = sum(lst) # compute sum

avg = total / len(lst) # compute average

count_greater = sum(1 for x in lst if x > avg) # count elements > average

return total, avg, count_greater # return results

numbers = [10, 20, 30, 40, 50] # sample list

res = analyze_list(numbers) # functon call

print("Sum:", res[0]) # print sum

print("Average:", res[1]) # print average

print("Count > average:", res[2]) # print count

5-Mark Question 5

Q5. Write a Python program to:


24

a) Create a CSV ile


b) Write student data
c) Close the ile
d) Read the CSV ile
e) Display its content

Answer

# writng part

f = open("[Link]", "w") # open ile in write mode

[Link]("name,mark\n") # write header

[Link]("Ravi,85\n") # write details

[Link]("Asha,90\n")

[Link]("Manu,78\n")

[Link]() # close ile

# reading part

f = open("[Link]", "r") # open in read mode

print([Link]()) # print full ile content

[Link]() # close ile

5-Mark Question 6

Q6. Write a Python program to:

a) Loop from 1 to 20
b) Skip multples of 4
c) Stop the loop at 17
d) Print allowed numbers
e) Count numbers printed

Answer

count = 0 # initalize counter

for i in range(1, 21): # loop from 1 to 20

if i % 4 == 0: # skip multples of 4

contnue

if i == 17: # stop loop if i = 17


25

break

print(i) # print number

count += 1 # increase count

print("Total numbers printed:", count) # display count

5-Mark Question 7

Q7. Write a Python program to:

a) Create dictonary with marks


b) Increase all marks by 10
c) Remove student with lowest mark
d) Add a new student
e) Print updated dictonary

Answer

students = {"Asha": 55, "Ravi": 60, "Manu": 45, "Lina": 70, "Imran": 50}

for k in students: # loop through dictonary keys

students[k] += 10 # increase each mark by 10

lowest = min(students, key=[Link]) # ind key with smallest value

del students[lowest] # remove lowest mark student

students["John"] = 90 # add new student

print("Updated dictonary:", students) # print inal dictonary

You might also like