0% found this document useful (0 votes)
16 views29 pages

Len Count

The document consists of a series of questions and answers related to computer science and programming concepts, covering topics such as software types, Python functions, database keys, and data structures. It includes explanations of programming constructs, data types, and examples of Python code for various tasks. Additionally, it touches on concepts in artificial intelligence, cloud computing, and data analysis using pandas.
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)
16 views29 pages

Len Count

The document consists of a series of questions and answers related to computer science and programming concepts, covering topics such as software types, Python functions, database keys, and data structures. It includes explanations of programming constructs, data types, and examples of Python code for various tasks. Additionally, it touches on concepts in artificial intelligence, cloud computing, and data analysis using pandas.
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
You are on page 1/ 29

1. To run your computer system, what types of software are necessary?

What role
does each type play in a computer's functioning?

Answer: System software (e.g., operating system) and application software (e.g., word
processor) are necessary. System software manages computer resources, while
application software performs specific tasks.

2. What happens if two keys in a dictionary have the same name?

Answer: In Python, dictionaries cannot have duplicate keys. If you try to create a
dictionary with duplicate keys, the last key-value pair will overwrite the previous ones.

3. Differentiate between len( ) and count( ) functions.

Answer: len() returns the total number of elements in a list, while count() returns the
number of occurrences of a specific element in a list.

4. What is the role of memory in computer functioning? With what types of


memory does the computer work?

Answer: Memory stores data and program instructions. Computers work with two types
of memory: primary memory (RAM) and secondary memory (hard disk, SSD, etc.).

5. Why foreign keys are allowed to have NULL values? Explain with an example.

Answer: Foreign keys can have NULL values to indicate that the relationship with the
referenced table is not applicable or unknown. For example, a customer order may not
have a salesperson assigned (NULL foreign key).

6. How is the len( ) function different from count( ) function in Python?

Answer: Same as question 3.

7. Differentiate between primary key and Foreign key with an example of each.

Answer: Primary key uniquely identifies a record in a table, while a foreign key
references the primary key of another table. Example: In a customers table, customer_id
is the primary key, and in an orders table, customer_id is a foreign key referencing the
customers table.
8. Differentiate between CHAR and VARCHAR data type.

Answer: CHAR is a fixed-length character data type, while VARCHAR is a variable-length


character data type.

9. How is the clear( ) function different from del <Dictionary> in Python?

Answer: clear() removes all items from a dictionary, while del deletes the entire
dictionary.

10. Differentiate between a list and a string.

Answer: A list is a collection of items that can be of different data types, while a string is a
sequence of characters.

11. What is Machine Learning? Write its applications.

Answer: Machine learning is a subset of AI that enables systems to learn from data and
improve their performance. Applications include image recognition, natural language
processing, recommendation systems, and more.

12. What is the difference between extend() and append()?

Answer: extend() adds multiple elements to a list, while append() adds a single
element to a list.

13. How can you eliminate duplicate records in a table with select query?

Answer: Use the DISTINCT keyword in the SELECT statement.

14. How is Virtual Reality different from Augmented Reality?

Answer: Virtual reality creates a completely artificial environment, while augmented


reality overlays digital information onto the real world.

15. Explain ‘if-elif-else’ construct with an example.

Answer: The if-elif-else construct is used for conditional statements. Example: if x


> 5: print("x is greater than 5"); elif x == 5: print("x is equal to
5"); else: print("x is less than 5").
16. Can the ‘if’ statement be referred to as conditional statements? Comment.

Answer: Yes, the if statement is a type of conditional statement.

17. What do you mean by the precedence of operators?

Answer: The precedence of operators determines the order in which operators are
evaluated in an expression.

18. Write the full forms of these: (i) IaaS, (ii) PaaS, (iii) SaaS, (iv) P2P

Answer: (i) Infrastructure as a Service, (ii) Platform as a Service, (iii) Software as a


Service, (iv) Peer-to-Peer.

19. What do you understand about ASCII?

Answer: ASCII (American Standard Code for Information Interchange) is a character


encoding standard that represents characters using numerical codes.

20. What is the difference between interactive mode and script mode in Python?

Answer: Interactive mode is a prompt-based interface for executing Python code, while
script mode involves executing a Python script file.

21. Differentiate between DROP and DELETE command.

Answer: DROP deletes a table or database, while DELETE deletes specific rows from a
table.

22. How is IS operator different from LIKE is SELECT queries?


solve these
I'll continue answering the remaining questions.

22. How is IS operator different from LIKE is SELECT queries?

Answer: The IS operator is used to test for null or not null values, while the LIKE
operator is used for pattern matching.

23. What is the significance of the DISTINCT clause? Explain it with an example.
Answer: The DISTINCT clause is used to remove duplicate rows from a result set.
Example: SELECT DISTINCT department FROM employees; returns a list of unique
departments.

24. In what way Artificial Intelligence is helpful in video games?

Answer: AI is used in video games for tasks such as pathfinding, decision-making, and
adaptive difficulty adjustment, creating a more immersive and engaging experience.

25. State the output of the following code:


aList=[123, ‘xyz’, ‘zara’, ‘abc’]; aList.insert(3,2009) print “Final List:”, aList

Answer: The output will be: Final List: [123, 'xyz', 'zara', 2009, 'abc']

26. Differentiate between primary key and Foreign key with an example of each.

Answer: Same as question 7.

27. Write a program to obtain temperatures of 7 days(Monday, Tuesday....Sunday)


and then display average temperature of the week.

Answer: Here is a Python program to achieve this:


VerifyOpen In EditorEditCopy code
1temperatures = []
2for day in ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday",
"Saturday", "Sunday"]:
3 temp = float(input(f"Enter temperature for {day}: "))
4 temperatures.append(temp)
5
6average_temp = sum(temperatures) / len(temperatures)
7print(f"Average temperature of the week: {average_temp:.2f}°C")

28. What will be the output of the following code: Lst=[10,50,20,30,40] print(Lst[::-
2])

Answer: The output will be: [40, 20, 10]

29. Write a short note on important services/advantages of the following: i. Cloud


computing ii. Artificial intelligence iii. Big Data iv. Robotics v. Internet of
Things(IoT)
Answer: Here are brief notes on each:

i. Cloud computing: On-demand access to computing resources, scalability, and cost-


effectiveness.

ii. Artificial intelligence: Automation, decision-making, and problem-solving capabilities.

iii. Big Data: Storage, processing, and analysis of large datasets for insights and decision-
making.

iv. Robotics: Automation of tasks, increased efficiency, and improved productivity.

v. Internet of Things (IoT): Interconnected devices, real-time data exchange, and


automation.

30. What is the difference between a literal and an identifier? Give 2 examples of
both.

Answer: A literal is a value that is written exactly as it is meant to be interpreted, while


an identifier is a name given to a variable, function, or label.

Examples:

Literals: 5, "hello"

Identifiers: x, my_function

31. Write a program to read elements of a list and do the following: a) The
program should ask for the position of the element to be deleted from the list.
Write a function to delete the element at the desired position in the list. b) The
program should ask for the value of the element to be deleted from the list. Write
function to delete the element of this value from the list.

Answer:

def delete_by_position(lst, pos):

if pos < len(lst):

del lst[pos]
else:

print("Invalid position")

def delete_by_value(lst, val):

if val in lst:

lst.remove(val)

else:

print("Value not found in the list")

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

print("Original list:", my_list)

pos = int(input("Enter position to delete: "))

delete_by_position(my_list, pos)

val = int(input("Enter value to delete: "))

delete_by_value(my_list, val)

print("Updated list:", my_list)

32. What is the difference between a tuple and a list in Python?


Answer: A tuple is an immutable collection of elements, while a list is a mutable
collection of elements.

33. Write a Python program to find the maximum and minimum values in a list.

Answer:

my_list = [12, 45, 7, 23, 56, 89, 34]

max_val = max(my_list)

min_val = min(my_list)

print("Maximum value:", max_val)

print("Minimum value:", min_val)

34. What is the purpose of the split() function in Python?

Answer: The split() function is used to split a string into a list of substrings based on a
specified separator.

35. Write a Python program to draw a graph with a suitable label in the X axis and
Y axis and a title.

Answer:

import matplotlib.pyplot as plt

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

y = [2, 4, 6, 8, 10]
plt.plot(x, y)

plt.xlabel('X Axis')

plt.ylabel('Y Axis')

plt.title('Line Graph')

plt.show()

36. What is the difference between break and continue statements in Python?

Answer: The break statement exits the loop, while the continue statement skips the
current iteration and continues with the next iteration.

37. Write a Python program to find the factorial of a number using recursion.

Answer:

def factorial(n):

if n == 0:

return 1

else:

return n * factorial(n-1)

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

result = factorial(num)

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

38. What is the purpose of the join() function in Python?

Answer: The join() function is used to concatenate a list of strings into a single string.
39. Write a Python program to find the sum of digits of a number.

Answer:

def sum_of_digits(n):

sum = 0

while n > 0:

sum += n % 10

n //= 10

return sum

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

result = sum_of_digits(num)

print("Sum of digits of", num, "is", result)

40. What is the difference between is and == operators in Python?

Answer: The is operator checks for object identity, while the == operator checks for
value equality.

41. Write a Python program to find the average of a list of numbers.

Answer: my_list = [12, 45, 7, 23, 56, 89, 34]

average = sum(my_list) / len(my_list)

print("Average of the list:", average)


1. The python code written below has syntactical errors. Rewrite the correct code
and underline the corrections made.

Answer:

import pandas as pd

df={"Technology":["Programming","Robotics","3DPrinting"],"Time(in months)":[4,4,3]}

df= pd.DataFrame(df)

print(df)

Corrections:
• Pd should be pd (lowercase)
• dataframe should be DataFrame (capitalized)

2. Complete the given Python code to get the required output as: Rajasthan

Answer:

import pandas as pd

di = {'Corbett': 'Uttarakhand', 'Sariska': 'Rajasthan', 'Kanha': 'Madhya


Pradesh','Gir':'Gujarat'}

NP = pd.Series(di)

print(NP['Sariska'])

3. Fill the missing statements to get the given output:

Answer:

import pandas as pd

rollno=[1,2,3,4,5,6,7]

p=pd.Series(rollno) #Statement 1
print(p.head(3)) #Statement 2

4. Consider two objects L and S. L is a list whereas S is a Series. Both have values
20, 40,90, 110. What will be the output of the following two statements considering
that the above objects have been created already.

Answer:

print(L+2) #Statement 1 -> [22, 42, 92, 112]

print(S+2) #Statement 2 -> Series: [22, 42, 92, 112]

5. Mr. Harry wants to draw a line chart using a list of elements named LIST.
Complete the code to perform the following operations:

Answer:

import matplotlib.pyplot as PLINE

LIST=[10,20,30,40,50,60]

PLINE.plot(LIST) #Statement 1

PLINE.xlabel("Sample Number") #Statement 2

PLINE.show()

6. A dictionary ‘stationary’ contains the following: Write statements for the


following:

Answer:

stationary={'Name':['books', 'copies', 'pencil box', 'Pen'],

'Price':[500, 350, 400, 250]}

# a. Create a Dataframe named “stock”

stock = pd.DataFrame(stationary)
# b. Add a column called ‘discount’ with the following data: [15, 20, 30, 25]

stock['discount'] = [15, 20, 30, 25]

# c. Delete column discount with all values.

stock.drop('discount', axis=1, inplace=True)

7. Differentiate between Single Row and Multi Row Functions?

Answer: Single Row Functions operate on a single row of data and return a single value,
whereas Multi Row Functions operate on multiple rows of data and return a single value.

8. Write a program to create the series that stores the term marks of 10 students.
Find the highest and lowest three marks scored by students.

Answer:

import pandas as pd

marks = pd.Series([85, 90, 78, 92, 88, 76, 95, 89, 84, 91])

print("Highest three marks:", marks.nlargest(3))

print("Lowest three marks:", marks.nsmallest(3))

9. Write a program to create a series from list marks and taking index values from
list roll no. Show all elements that are above 80 marks.

Answer:

import pandas as pd
roll_no = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

marks = [85, 90, 78, 92, 88, 76, 95, 89, 84, 91]

series = pd.Series(marks, index=roll_no)

print("Marks above 80:", series[series > 80])

10. WAP to plot a line chart between two given arrays

Answer:
import matplotlib.pyplot as plt

A = [4, 56, 78, 23, 45, 67, 89]


B = [0, 1, 2, 3, 4, 5, 6]

plt.plot(B, A)
plt.xlabel("Index")
plt.ylabel("Value")
plt.title("Line Chart")
plt.show()

11. Write Python code to create the following DataFrame df1 using Python Pandas.

Answer:

import pandas as pd

data = {'Name': ['Arjun', 'Ruchi', 'Prerna', 'Himali'],


'Class': ['XII', 'X', 'XI', 'XI'],

'Marks': [95, 84, 90, 75]}

df1 = pd.DataFrame(data)

print(df1)

12. Consider a given Series, D1: Write a program in Python Pandas to create the
series.

Answer:

import pandas as pd

data = {'MAX MARKS': [30, 40, 50, 100]}

index = ['TEST 1', 'TEST 2', 'TEST 3', 'TEST 4']

D1 = pd.Series(data['MAX MARKS'], index=index)

print(D1)

13. Consider the decimal number x with value 54567.8577. Write commands in
SQL to:

Answer:

-- i. display the whole number without round it off.

SELECT FLOOR(x) FROM table_name;

-- ii. round it to 2 places of the decimal.


SELECT ROUND(x, 2) FROM table_name;

14. Based on the SQL table EMPL, write suitable queries for the following:

Answer:

-- a. Display DESIGNATION wise average salary.

SELECT DESIGNATION, AVG(Salary) FROM EMPL GROUP BY DESIGNATION;

-- b. Display department wise highest salary.

SELECT DEPT, MAX(Salary) FROM EMPL GROUP BY DEPT;

-- c. Display the records in the descending order of salary.

SELECT * FROM EMPL ORDER BY Salary DESC;

15. Create a DataFrame in Python from the given list:

Answer:

import pandas as pd

data = {'NAME': ['Divya', 'Mamta', 'Payal', 'Deepak'],

'DEPARTMENT': ['HR', 'Marketing', 'IT', 'Sales'],

'SALARY': [95000, 97000, 980000, 79000]}

df = pd.DataFrame(data)

print(df)
16. Poonam wants to display first 3 elements from series S.

Answer:

import pandas as pd

S = pd.Series([10, 20, 30, 40, 50], index=[1, 2, 3, 4, 5])

# a. Rewrite the above program with necessary changes to help her get the desired
output.

print(S.iloc[:3])

# b. Write the statement to display the values which are greater than equal to 30.

print(S[S >= 30])

# c. Write the statement to change the index name of the Series as "My Index".

S.index.name = "My Index"

print(S)

17. Write MySQL statements for the following:

Answer:

-- i. To create a database named FOOD.

CREATE DATABASE FOOD;


-- ii. To create a table named Nutrients based on the following specification:

CREATE TABLE Nutrients (

FOOD_ITEM VARCHAR(20) PRIMARY KEY,

CALORIE INTEGER

);

18. Consider the given DataFrame ‘Genre’:

Answer:

import pandas as pd

Genre = pd.DataFrame({'Type': ['Fiction', 'Non Fiction', 'Drama', 'Poetry'],

'Code': ['F', 'NF', 'D', 'P']})

# i. Add a column called Num_Copies with the following data:[300,290,450,760].

Genre['Num_Copies'] = [300, 290, 450, 760]

# ii. Add a new genre of type ‘Folk Tale' having code as “FT” and 600 number of copies.

new_row = pd.DataFrame({'Type': ['Folk Tale'], 'Code': ['FT'], 'Num_Copies': [600]})

Genre = pd.concat([Genre, new_row])

# iii. Rename the column ‘Code’ to ‘Book_Code’.

Genre = Genre.rename(columns={'Code': 'Book_Code'})


print(Genre)

19. Sunita is working as DBA in Infosys, help her by writing answers of following
queries

Answer;

-- a. Write a query to display the year of DOB.

SELECT YEAR(DOB) FROM table_name;

-- b. Write a query to display the month of most recent DOJ.

SELECT MONTH(MAX(DOJ)) FROM table_name;

-- c. Write a query to display the details all those employees who joined in the
month of May.

SELECT * FROM table_name WHERE MONTH(DOJ) = 5;

-- d. Write a query to count total number of employees who joined in the year
2022.

SELECT COUNT(*) FROM table_name WHERE YEAR

20. Write the output of the given statement(s), based on the given DataFrame
named "df":

Answer:

# a. print(df.loc[:1])

# Output: depends on the DataFrame df


# b. df["Married"]=False

# print(df.loc[2:,["Name","Married"]])

# Output: depends on the DataFrame df

# c. df.weight[1]

# ans :123

# Output: 123

# d. print(df.age)

# ANS 15,20,18

# Output: [15, 20, 18]

21. Write suitable SQL queries for the following:

Answer:

-- i. To calculate the exponent for 3 raised to the power of 4.

SELECT POWER(3, 4) FROM table_name;

-- ii. To display current date and time.

SELECT NOW() FROM table_name;


-- iii. To round off the value -34.4567 to 2 decimal place.

SELECT ROUND(-34.4567, 2) FROM table_name;

-- iv. To remove all the probable leading spaces from the column user_id of the table
named user.

SELECT TRIM(user_id) FROM user;

-- v. To display the length of the string ‘welcome to SMS’.

SELECT LENGTH('welcome to SMS') FROM table_name;

22. Write a program to plot a bar graph and show the population of 6 years.

Answer:

import matplotlib.pyplot as plt

population = [50, 34, 30, 67, 65, 70, 95]

year = [2010, 2011, 2012, 2013, 2014, 2015, 2016]

plt.bar(year, population)

plt.xlabel("Year")

plt.ylabel("Population")

plt.title("Population of 6 Years")

plt.show()
23. HR Department of ABC Tech has created a dataframe ‘df1’ to store data about
name, salaries and bonus paid to their employees.

Answer:

import pandas as pd

# i. Display the columns Sal and Bonus

print(df1[["Sal", "Bonus"]])

# ii. Display the details of the last employee.

print(df1.tail(1))

# iii. Add a new column named ‘Email’ with NULL value for all rows.

df1["Email"] = None

# iv. To import the proper library/module.

import pandas as pd

# v. Display details of last 3 employee without using tail function

print(df1.iloc[-3:])

24. Write a Pyhton program to draw a line with a suitable label in the X axis and Y
axis and a title.
Answer:

import matplotlib.pyplot as plt

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

y = [10, 20, 30, 40, 50]

plt.plot(x, y)

plt.xlabel("X Axis")

plt.ylabel("Y Axis")

plt.title("Line Graph")

plt.show()

25. Write a code to draw the following bar graph representing the number of
students in each class:.

Answer:

import matplotlib.pyplot as plt

classes = ["Class 1", "Class 2", "Class 3", "Class 4", "Class 5"]

students = [30, 40, 20, 35, 45]

plt.bar(classes, students)

plt.xlabel("Class")
plt.ylabel("Number of Students")

plt.title("Bar Graph of Students in Each Class")

plt.show()

26. Write a python program to draw a histogram with following information:

Answer:

import matplotlib.pyplot as plt

scores = [10, 15, 10, 10, 10, 15, 20, 20, 20, 20, 20, 25, 25]

plt.hist(scores, bins=10, color="cyan")

plt.xlabel("Score")

plt.ylabel("Frequency")

plt.title("Frequency of Score")

plt.show()

27. Mr Ramesh wrote a Query to find the sum of bonus earned by the employees of
WEST zone:

Answer:

SELECT SUM(bonus) FROM employee WHERE zone = "west";

28. Carefully observe the following code:

Answer:

import pandas as pd
x = [[100, 200, 300], [10, 20]]

df = pd.DataFrame(x)

print(df)

# i. Display the dataframe

print(df)

# ii. Write the syntax for displaying size and shape of the above dataframe.

print(df.size)

print(df.shape)

29. Based on the SQL table STUDENT, write suitable queries for the following:

Answer:

-- d. Display total number of male and female students.

SELECT COUNT(*), gender FROM STUDENT GROUP BY gender;

-- e. Display gender wise minimum weight.

SELECT MIN(weight), gender FROM STUDENT GROUP BY gender;

-- f. Display the records in the descending order of HEIGHT.


SELECT * FROM STUDENT ORDER BY HEIGHT DESC;

30. Predict the output of the following queries based on the table PURCHASE given
above:

Answer:

-- 1. SELECT LEFT(CNAME,2) FROM PURCHASE WHERE QUANTITY>=100;

-- Output: depends on the table PURCHASE

-- 2. SELECT QUANTITY/2 FROM PURCHASE WHERE MONTH(DOP)=10;

-- Output: depends on the table PURCHASE

-- 3. SELECT SUM(QUANTITY) "TOT SALE" FROM PURCHASE WHERE


CITY=”CHANDHIGARH";

-- Output: depends on the table PURCHASE

31. Kapil has created following table named exam:

Answer:

-- 1. Insert a new record in the table having following values: [6,'Khushi','CS',85]

INSERT INTO exam (RegNo, Name, Subject, Marks) VALUES (6, 'Khushi', 'CS', 85);

-- 2. To change the value “IP” to “Informatics Practices” in subject column.

UPDATE exam SET Subject = 'Informatics Practices' WHERE Subject = 'IP';

-- 3. To remove the records of those students whose marks are less than 30 .
DELETE FROM exam WHERE Marks < 30;

-- 4. To add a new column Grade of suitable datatype.

ALTER TABLE exam ADD COLUMN Grade VARCHAR(10);

-- 5. To display records of “Informatics Practices” subject.

SELECT * FROM exam WHERE Subject = 'Informatics Practices';

32. Consider the two objects s1 and s2. s1 is a list whereas s2 is a Series. Both have
values 100, 200, 300, 400, 500.

Answer:

# a. print(s1 * 2)

# Output: [200, 400, 600, 800, 1000]

# b. print(s2 * 2)

# Output: 0 200

1 400

2 600

3 800

4 1000

dtype: int64
33. Given the dataset for Employee:

Answer:
import pandas as pd

data = {'Name': ['Ravi', 'Sanjay', 'Ramesh', 'Nipun'],

'Age': [38, 44, 35, 53],

'Designation': ['Accountant', 'Cashier', 'Clerk', 'Manager']}

df = pd.DataFrame(data)

print(df)

# Perform pivoting on the dataframe

print(df.pivot_table(index='Designation', values='Age', aggfunc='mean'))

# Draw a histogram based on Employee data

import matplotlib.pyplot as plt

plt.hist(df['Age'], bins=10)

plt.xlabel("Age")

plt.ylabel("Frequency")

plt.title("Histogram of Employee Ages")

plt.show()

You might also like