Professional Documents
Culture Documents
Mod 2 Finalans
Mod 2 Finalans
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
6 mark questions
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
# Slicing array
print("Slice from index 1 to 3:", arr1d[1:4]) # Output: [2 3 4]
df = pd.DataFrame(data)
# 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
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.
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
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:
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:
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