Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 9

Mod -2

2 mark question
1.Given series of numbers from 1 to 100, print the
number and their squares.
ans: for i in range(1, 101):
print(i, i ** 2)
2.Enter your name and print individual characters with
index value.
Ans: name = input("Enter your name: ")
for i in range(len(name)):
print(f"Character '{name[i]}' is at index {i}")
o/p: Enter your name: shruti
Character 's' is at index 0
Character 'h' is at index 1
Character 'r' is at index 2
Character 'u' is at index 3
Character 't' is at index 4
Character 'i' is at index 5
3. Using while loop display 1 to 10 without printing 5.
Ans: num = 1
while num <= 10:
if num != 5:
print(num)
num += 1
o/p:1
2
3
4
6
7
8
9
10

4. Create an array of numbers with size 10 using numpy library and print the
sum of third and fifth elements from it.
Ans: import numpy as np

# Create an array of numbers with size 10


arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])

# Print the sum of the third and fifth elements


result = arr[2] + arr[4]
print("Sum of the third and fifth elements:", result)
Sum of the third and fifth elements: 8
5. Using a step value of -2 print the square root of even numbers from 100 to 90.
Ans: import math

for num in range(100, 89, -2):


if num % 2 == 0:
print(math.sqrt(num))
o/p: 10.0
9.899494936611665
9.797958971132712
9.695359714832659
9.591663046625438
9.486832980505138
6. Enter five words in a list. Then print the words one by one without the 3rd
one. Write a program for this using for loop.
ans: # Taking input of five words
word_list = []
for i in range(5):
word = input("Enter word {}: ".format(i + 1))
word_list.append(word)

# Printing words one by one excluding the third one


for index, word in enumerate(word_list):
if index != 2:
print(word)
o/p:
Enter word 1: bus
Enter word 2: car
Enter word 3: truck
Enter word 4: bike
Enter word 5: cycle
bus
car
bike
cycle
7.Create an array of numbers with size 10 using numpy library and print
the sum of third and fifth elements from it.
ans:same as 4

7. Why pandas is used and define a data frame.


Ans: Pandas is used for data analysis and manipulation.

A DataFrame is a 2-dimensional labeled data structure in pandas

6 mark questions

1. What is Numpy ? Write python code - create a numeric array of 10 elements.


a.Slice elements from index 4 to the end of the array and print. b. Slice elements from the
beginning to index 4c. Slice from the index 3 from the end to index 1 from the end:
d.Print every alternate element from index 1 to index 5:
ans: NumPy is a powerful Python library used for numerical computing. It provides support
for large, multi-dimensional arrays and matrices, along with a collection of mathematical
functions to operate on these arrays efficiently. NumPy is widely used in scientific
computing, data analysis, machine learning, and various other fields where numerical
operations are performed on large datasets. It offers capabilities for performing operations
such as mathematical, logical, shape manipulation, sorting, selecting, I/O, discrete Fourier
transforms, basic linear algebra, basic statistical operations, random simulation, and more.

import numpy as np
int_array = np.array([1, 2, 3, 4, 5,6,7,8,9,10])
print(int_array)
print(int_array[4:])
print(int_array[:5])
print(int_array[-4:-1])
print(int_array[1:6:2])
o/p:
[ 1 2 3 4 5 6 7 8 9 10]
[ 5 6 7 8 9 10]
[1 2 3 4 5]
[7 8 9]
[2 4 6]

2. Create a 2-D array using numpy by taking some numbers . a.From the second element,
slice elements from index 1 to index 4 & write output. b.From both elements, return the
value of index 2 and write output. c.From both elements, slice index 1 to index 4 and
write output
Ans: import numpy as np

# Create a 2-D array


array_2d = np.array([[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10]])

# a. From the second element, slice elements from index 1 to index 4


sliced_a = array_2d[1, 1:5]
print("a. Sliced elements from index 1 to index 4 in the second element:", sliced_a)

# b. From both elements, return the value of index 2


index_2_values = array_2d[:, 2]
print("b. Value of index 2 from both elements:", index_2_values)

# c. From both elements, slice index 1 to index 4


sliced_c = array_2d[:, 1:5]
print("c. Sliced elements from index 1 to index 4 from both elements:", sliced_c)
o/p:
a. Sliced elements from index 1 to index 4 in the second element: [ 7 8 9 10]
b. Value of index 2 from both elements: [3 8]
c. Sliced elements from index 1 to index 4 from both elements: [[ 2 3 4 5]
[ 7 8 9 10]]

3. (i).Write program - Print all odd numbers from 100 to 1 which


are divisible by 7 (ii).Write program - Print
the numbers and their squares from 1 to 100 with an interval of 2.
Ans:i. for num in range(100, 0, -1):
if num % 2 != 0 and num % 7 == 0:
print(num)
o/p: 91
77
63
49
35
21
ii.for num in range(1, 101, 2):
print(f"Number: {num}, Square: {num ** 2}")
4. Write program to : i.Display all odd numbers from 50 to 200 which are divisible by 7 and 3
both.
ii. Display the numbers and their cubes from 40 to 80
with an interval of 3. 5.Explain NUMPY library. Show the
following features through an example. Accessing array
elements, slicing array, using step value and slicing 2-D
arrays.
Ans:i. for num in range(51, 201, 2):
if num % 7 == 0 and num % 3 == 0:
print(num)
o/p: 63
105
147
189
ii. for num in range(40, 81, 3):
print(f"Number: {num}, Cube: {num ** 3}")
5. Explain NUMPY library. Show the following features through an example.
Accessing array elements, slicing array, using step value and slicing 2-D arrays
Ans: NumPy is a Python library used for numerical computing, particularly for handling large
datasets and performing mathematical operations efficiently. It provides support for multi-
dimensional arrays and matrices, along with a wide range of mathematical functions to
operate on these arrays.
import numpy as np

# Creating a 1-D array


arr1d = np.array([1, 2, 3, 4, 5])

# Accessing array elements


print("Element at index 2:", arr1d[2]) # Output: 3

# Slicing array
print("Slice from index 1 to 3:", arr1d[1:4]) # Output: [2 3 4]

# Using step value


print("Every second element:", arr1d[::2]) # Output: [1 3 5]

# Creating a 2-D array


arr2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

# Slicing 2-D array


print("Slice row 0, column 1 to 2:", arr2d[0, 1:3]) # Output: [2 3]
6. What is Pandas ? Define data frame. Write a python code to create a data frame and
assign some values. Display the content of data frame. What is csv file ? Show the use of
read_csv( ) and to_string( ) in a program.
Ans: Pandas is a powerful Python library used for data manipulation and analysis. It
provides high-level data structures and functions designed to make working with
structured data fast, easy, and expressive. One of the key data structures in Pandas is the
DataFrame.

A DataFrame in Pandas is a 2-dimensional labeled data structure with columns of


potentially different types. It is similar to a spreadsheet or SQL table, where each column
represents a different variable, and each row represents a different observation or record
import pandas as pd

# Creating a DataFrame with some values


data = {'Name': ['Alice', 'Bob', 'Charlie', 'David'],
'Age': [25, 30, 35, 40],
'City': ['New York', 'Los Angeles', 'Chicago', 'Houston']}

df = pd.DataFrame(data)

# Displaying the content of the DataFrame


print("DataFrame:")
print(df.to_string(index=False))
o/p: DataFrame:
Name Age City
Alice 25 New York
Bob 30 Los Angeles
Charlie 35 Chicago
David 40 Houston
A CSV (Comma-Separated Values) file is a plain text file that contains tabular data where
each line represents a row, and columns are separated by commas. CSV files are
commonly used for storing and exchanging data.
# Reading data from a CSV file
csv_data = pd.read_csv('data.csv')

# Displaying the content of the DataFrame read from the CSV file
print("Content of the CSV file:")
print(csv_data.to_string(index=False))

7. Do a program using loop to continue entering some numbers and summing up till a -ve
number is entered. At last print the sum of only odd numbers.
Ans: # Initialize sum of odd numbers
sum_odd = 0

# Continue entering numbers until a negative number is entered


while True:
num = int(input("Enter a number (enter a negative number to stop): "))
if num < 0:
break # Exit loop if a negative number is entered
if num % 2 != 0:
sum_odd += num # Add odd numbers to the sum

# Print the sum of only the odd numbers


print("Sum of odd numbers:", sum_odd)
o/p: Enter a number (enter a negative number to stop): -2
Sum of odd numbers: 0

16 mark question

1.Write the purpose of while and for loop.What is the purpose of break and
continue ? Give one example of each. Enter a number, if the number is
positive , then write python program to calculate its factorial using loop.

Ans: While loop:

The purpose of a while loop is to repeatedly execute a block of code as long as a specified condition is true. It is used when the
number of iterations is not fixed and depends on a condition.
while True:
num = int(input("Enter a number (negative to stop): "))
if num < 0:
break
print("You entered a positive number.")
For loop:

The purpose of a for loop is to iterate over a sequence (such as a list, tuple, string, or range) and execute a block of code for each
element in the sequence. It is used when the number of iterations is known or can be determined in advance.
for i in range(1, 11):
if i % 2 != 0:
continue
print(i)
Break statement:

The purpose of the break statement is to exit a loop prematurely, regardless of whether the loop's condition has become false or
not. It is used to terminate the loop when a certain condition is met.
Continue statement:

The purpose of the continue statement is to skip the rest of the code inside a loop for the current iteration and proceed to the next
iteration. It is used to skip specific iterations of the loop based on a condition.

while True:
num = int(input("Enter a number (negative to stop): "))
if num < 0:
break
print("You entered a positive number.")
num = int(input("Enter a positive number: "))
factorial = 1

if num < 0:
print("Factorial is not defined for negative numbers.")
elif num == 0:
print("Factorial of 0 is 1.")
else:
for i in range(1, num + 1):
factorial *= i
print("Factorial of", num, "is", factorial)
2.Explain the following terms in short with one

example for each. Range ( ) , ELSE in for loop ,

break , continue, pass.

Ans: Range():

The range() function generates a sequence of numbers within a specified range. It is commonly used in for loops to iterate a
specific number of times or to generate indices for accessing elements in a sequence.
Example:

for i in range(5):
print(i)
This will print numbers from 0 to 4, as range(5) generates a sequence of numbers from 0 to 4 (excluding 5).
ELSE in for loop:

The else block in a for loop executes when the loop completes all iterations without encountering a break statement. It provides a
way to execute a block of code when the loop finishes normally, without prematurely terminating due to a condition.
Example:

for i in range(5):
print(i)
else:
print("Loop completed successfully.")
This will print numbers from 0 to 4, and then print "Loop completed successfully" because the loop finished all iterations without
encountering a break statement.
Break:

The break statement is used to exit a loop prematurely, regardless of whether the loop's condition has become false or not. It
allows you to terminate the loop based on a specific condition.
Example:

for i in range(10):
if i == 5:
break
print(i)
This will print numbers from 0 to 4 and then exit the loop when i becomes 5.
Continue:

The continue statement is used to skip the rest of the code inside a loop for the current iteration and proceed to the next iteration.
It allows you to skip specific iterations of the loop based on a condition.
Example:

for i in range(5):
if i == 2:
continue
print(i)
This will print numbers from 0 to 4, skipping the number 2 because of the continue statement.
Pass:

The pass statement is a null operation that does nothing when executed. It is used as a placeholder when a statement is
syntactically required but no action is needed.
Example:

for i in range(5):
if i == 2:
pass
else:
print(i)
This will print numbers from 0 to 4, and pass has no effect on the execution of the loop.
3. Explain the following terms in short and show their use through a program based on pandas. Consider a data file revenue-
profit.csv (year, revenue, cost, profit)
Import, head( ), to_string( ) , loc( ), iloc( ), describe( )

3. Explain the following terms in short and show their use through a program based on pandas.
Consider a data file revenue-profit.csv (year, revenue, cost, profit)
Import, head( ), to_string( ) , loc( ), iloc( ), describe( )
ii.Write a program to demonstrate Nested if and NOT operator in a single python program.
Ans: Import:

The import statement in Python is used to import modules or packages into a script or program, making their
functions, classes, and variables available for use. In the context of pandas, it is used to import the pandas library so
that its functionalities can be utilized.
Example:

import pandas as pd
head():

The head() method in pandas is used to display the first few rows of a DataFrame. By default, it shows the first five
rows, but you can specify the number of rows to display.
Example:

df.head()
to_string():

The to_string() method in pandas is used to convert a DataFrame to a string representation. It provides a formatted
string representation of the DataFrame, which can be useful for displaying the entire DataFrame in a readable format.
Example:

df_string = df.to_string()
print(df_string)
loc():

The loc[] accessor in pandas is used to access a group of rows and columns by label(s) or a boolean array. It allows
you to select data based on the labels of rows and columns.
Example:

df.loc[0] # Selects the first row of the DataFrame


iloc():

The iloc[] accessor in pandas is used to access a group of rows and columns by integer position(s). It allows you to
select data based on the integer indices of rows and columns.
Example:

df.iloc[0] # Selects the row at index 0 of the DataFrame


describe():

The describe() method in pandas is used to generate descriptive statistics for numerical columns in a DataFrame. It
provides summary statistics such as count, mean, standard deviation, minimum, maximum, and quartile values.
Example:

df.describe()
Here's a program demonstrating the use of these terms with a DataFrame imported from a CSV file:
import pandas as pd

# Importing the DataFrame from a CSV file


df = pd.read_csv('revenue-profit.csv')

# Displaying the first few rows of the DataFrame


print("First few rows of the DataFrame:")
print(df.head())

# Converting the DataFrame to a string representation


df_string = df.to_string()
print("\nDataFrame as a string:")
print(df_string)

# Accessing a specific row using label-based indexing (loc[])


print("\nRow with label 0:")
print(df.loc[0])

# Accessing a specific row using integer-based indexing (iloc[])


print("\nRow at index 0:")
print(df.iloc[0])

# Generating descriptive statistics for numerical columns


print("\nDescriptive statistics for numerical columns:")
print(df.describe())
ii. # Input a number from the user
num = int(input("Enter a number: "))

# Check if the number is positive


if num > 0:
print("The number is positive.")

# Check if the number is even


if num % 2 == 0:
print("The number is even.")
else:
print("The number is odd.")

# Check if the number is negative


elif num < 0:
print("The number is negative.")

# If the number is not positive or negative, it must be zero


else:
print("The number is zero.")
o/p: Enter a number: 6
The number is positive.
The number is even.

You might also like