You are on page 1of 61

Question Bank

Informatics Practices -XI


Chapter -1
Basic Computer Organization
MLL
Q1. What is Computer?
Ans1-A computer is an electronic device that performs a variety of task according by the given
instruction of the user.
Q2. What is Hardware?
Ans2- The physical electronic components of a computer are called Hardware.
Q3. What is Software?
Ans3- Software represents the recorded instructions that govern computer’s operations.
Q4. What is the full form of CPU?
Ans4- Central Processing Unit
Q5. Define Input/Output Unit?
Ans5-Input unit is used to take the input from the user and converts it into binary form.
Q6. Expand the following-
(i) ALU (II) CU (III) RAM (IV) ROM (V) GPU
Ans6.(i) Arithmetic Logic Unit (ii) Control Unit (iii) Random Access Memory (iv) Read Only Memory
(iv) GPU- Graphics Processing Unit
Q7. What is System Software?
Ans7. Software that controls internal computer operations is known as System Sofware.
Q8. What do you mean by packages?
Ans8. Some general application software are required by the users for the fulfillment of their needs and
requirements are known as Packages.
Q9. Write two names of Business S/W?
Ans9-1. Payroll Management System 2. Inventory Management System
Q10. What is Interpreter?
Ans10. An Interpreter converts and executes an HLL program into machine language line by line.
Q11. Explain the following-
(i) Nibble (ii) Byte (iii) KB (iv) megabyte (v) gigabyte
Ans (i) Nibble- 4 bits
(ii) Byte- 8 bits
(iii) KB – 1024 bytes
(iv) Megabyte- 1024 kilobytes
(v) Gigabyte- 1024 megabytes
Q12. What is GPU?
Ans12. The GPU assist the CPU by handling all graphics related chores of a mobile CPU.
Q13. What is the use of OS?
Ans-13 An operating system is a program which acts as an interface between the user and the hardware.
Q14. What is the Significance of SoC?
Ans14 . SoC refers to System on a Chip . It offers better performance while the power consumption is
comparatively less.
Q15. What is the meaning of the term volatile Primary Memory?
Ans- In Volatile Primary Memory all contents are erased as soon as power goes off. Ex- RAM

HOTs
Q1. Difference between Hardware and Software?
Ans- Hardware-The physical electronic components of a computer are called hardware. Ex: Keyboard ,
CPU , Monitor , Printer etc.
Software-These are the recorded instructions and programs that govern the working of a computer.
Q2. Explain the IPO process with the help of diagram.
Ans-IPO means Input-Process-Output.A certain input given by the user is processed and generate
specific output after processing.
Q3. Explain the functioning of CPU.
Ans-Central Processing Unit is called the brain of thecomputer as it guides ,directs ,controls and governs
the performance of the computer.CPU has some sub components as given below:
i)ALU ii)CU iii)Memory/Registers
Q4. Differentiate between RAM and ROM?
Ans:Random Access Memory:
1)In this memory both read and write operations can take place.
2)RAM is a volatile memory.
Read Only Memory:
1)In this memory only read operations can take place.
2)ROM is a non-volatile memory.
Q5.What is the role of Application Processing Unit?
Ans-The Application Processing Unit is responsible for carrying out different applications that a mobile
system can perform such as making calculations , playing music, browsing net ,streaming videos,
connecting to other devices capturing and save the data.
Q6. What are the major components of the computer System?
Ans-The major components are:
i)The Hardware
ii)The Operating System
iii)The Application Program Routines
iv)The Humanware
Q7. Explain the working hierarchy in a Computer with the help of diagram.
Ans- Check your progress
Q8. What is the role of Mobile Processor in Mobile?
Ans-This is the brain of a smartphone. The CPU receives commands , makes instant calculations , place
audio/video, stores information and sends signals throughout the device.
The CPU of a mobile system has two subprocessor:
1)Communication Processing Unit
2)Application Processing Unit
Q9. Why is primary memory termed as ‘Destructive write’ memory but ‘non-destructive read’ memory?
Ans- When a memory location is read from in the primary memory,The contents of the memory word
remain the same; they are not altered. Therefore ,a primary memory is termed as ‘non-destructive’ read
memory since the read operation does not destruct the contents of a memory word.
When a write operation takes place , the previous contents of the memory word are
overwritten.Thus,the primary memory is termed as ‘destructive write’ memory as the write operation
destructs the contents of a memory word.
Q10. What is the application software ? Why is it required?
Ans-Application software is a software that pertains to one application.
Application software is required because system software can not carry out the routine jobs performed
by the user which application software can easily do.
Q11. What is the difference between an Interpreter and Compiler?
Ans- Interpreter:
1) An interpreter converts an HLL Program into machine language line by line and simultaneously
executes the converted line .
2) An Interpreter must always be present in the memory along with the program for it’s execution.
3) If an error in a line ,the line is displayed and interpreter does not proceed unless the error is
rectified.
Compiler:
1)A compiler converts an HLL program in machine language in one go.
2)If there are errors in the program it gives the error list along with the line number
3)Once the errors are removed ,error free object code is made available and after this compiler is no
more needed in the memory.

Q12.What is SoC? How it is different from CPU?


Ans-Soc refers to System on a Chip.An SoC consists of a Central Processing Unit(CPU),Graphics
Processing Unit (GPU),modem,multimedia processor,security device and signal prcessor.
SoC is not only comprises up of the smartphone’s CPU,but other functional sub-processors like
CPU,display processor,video processor along with LTE modem,and other bits of silicon that turn it into a
functional ‘system’ in a phone.
Q13. What is Utility Software? Write it’s significance in computer performance.
Ans-Utilities are those application programs that ensure the smooth functioning of the computer.It
assist the computer by performing housekeeping functions like backup data, remove outdated files or
recover data that has been accidentally erased .
Name of some Utilities softwares:
i)Text editor ii)Backup Utility iii)Disk Defragmenter iv)Antivirus software

Q14. What is role of power Management Unit in a Mobile System?


Ans-The power management subsystem is responsible for managing battery based power with a battery
management module and providing power to mobile system is required form.
Q15. What are the major functional components of a Mobile System?
Ans-The major functional components of a Mobile System are:
i)Mobile Processor ii)Display subsystem iii)Camera Subsystem iv)Mobile System Memory
v)Storage vi)Power Management Subsystem
Chapter -2
Getting Started with Python
MLL
Q1. Who developed Python Programming Language?
Ans- Guido Van Rossum in 1990s developed Python programming language.
Q2. Is Python an Object Oriented Language.
Ans. Yes, Python is an Object Oriented Language.
Q3.Write the advantage of Python.
Ans. 1. Easy to use OO Language 2. Expressive Language 3. Interpreted Language 4. Cross-platform
Language 5. Free and Open Source
Q4. How Python is easy to Use?
Ans- Python is compact and very easy to use Object Oriented, Very simple syntax rules and user friendly,
so it is very easy comparison to other language.
Q5. Why python is a Cross-platform Language?
Ans- Python is a Cross- Platform Language as it can run equally well on variety of platforms – windows,
Linux, Unix, Smart Phones etc.
Q6. Is Pythons Language is Free and Open Source Langauge.
Ans- Yes, It is a free and open Source Language.
Q7. Write two disadvantages/Minuses of Python.
Ans- 1. Not the Fastest Langauge 2. Not strong on Type-binding 3. Not easily Conertible
Q8. Write full form of IDLE.
Ans. Interactive Development and Learning Environment
Q9. Write the syntax to save a Python Program.
Ans. Python<file –name>.py
Q10. Which of the following are not valid strings in Python?
a) ‘Hello’ b) ‘Hello”
Ans. b)‘Hello”

HOTs
Q1. What is a Cross-Platform Software?
Ans. Something that is compatible across various platfrom is known as Cross-Platform Software. Python
is a Cross- Platform Language as it can run equally well on variety of platforms – windows, Linux, Unix,
Smart Phones etc.
Q2. What are different ways to work in Python?
Ans- There are two different ways to work in Python-
1. Interactive Mode 2. Script Mode
Q3. Explain the functioning of Interactive mode of Python.
Ans. Interactive mode does not save commands in form of a program and also, output is sandwiched
between commands.
Q4. Why Python is an Interpreter Langauge?
Ans. When we work on Python shell the commnds typed one by one and get the result or error one by
one. That’s why it is an Interpreter Language.
Q5. What do you mean by Python Shell?
Ans. The Interactive Interpreter of Python is called Python Shell.
Q6. What is the difference between interactive mode and script mode in Python?
Ans. In interactive mode, instructions are given in front of Python prompt in Python shell. Python carries
out the given instruction and shows the result there iteslf.
In script mode, Python instructions are stored in a file generally with .py extension and are executed
together in one go as a unit. The saved instructions are known as Python script or Python program.
Q7. What are the limitations of Python Langauge?
Ans- Python has following limitions:
 Not the faster language.
 Lesser libraries that C, Java , Perl
 Not strong on Type-binding
Q8. Python is a Free and Open source Langauge. What do you understand by this feature?
Ans.It means- to download Python, One needs not pay anything, because it is Free . And its source-code
is also available , which can be modified /imporoved etc., because it is open-source.
Q9. Write the names of fields where python is used?
Ans. Python is being used in many diverse fields/applications like-
 Scripting
 Rapid Prototyping
 Web Applications
 GUI Programs
 Game Development
 Database Applications
 System Administartions
Q10. Write some features of ANACONDA PYTHON?
Ans- (i) It is free and open source
(ii) It comes preloaded with many packages and libraries
(iii) It offers juypter notebook and spuder IDE
Q11.What is None literal in Python?
Ans.The None literal is used to indicate something that has not yet been created Iin simple words,or
absence of value.
Q12.Predict the output of the following:
x,y=7,2
x,y,x=x+1,y+3,x+10
print(x,y)
Ans: 17 5
Chapter-3
Python Fundaments
MLL
Q1. What is Character set in Python?
Ans- Character set is a set of characters that a language can recognize. A character represents any
letter,digits or any other symbol.
Q2. What is Token?
Ans. The smallest individual unit in a program is known as a Token.
Q3. What is Keyword.
Ans. A Keyword is a word having special meaning reserved by programming language.
Q4. Is, the Python is case sensitive language ?
Ans. Yes, Python is case sensitive as it treats upper and lower-case characters differently.
Q5. What do you mean by escape sequence?
Ans. An escape sequence represents a single character and hence consumes one bytes in ASCII
representation.
Q6. How many types of Strings in Python?
Ans. Python allows two string types-
(i) Single-line Strings (ii) Multiline Strings
Q7. How you define the multiple line string in Python?
Ans. A multiple string define in triple-quote or triple-apostrophe.
Q8. Write the syntax to use the len() function.
Ans. len(<objecy name>)
It is use to find the size/length of an object.
Q9. What do you mean by comment in Python?
Ans. Comment is a non-executable , additional information added in program for readability.
Q10. What is Function?
Ans. A function is a named code that can reused with a program.

HOTs
Q1. What is the difference between keywords and an identifier?
Ans. Keywords-
1. Keyword is a special word that has a special meaning and purpose.
2. Keywords are reserved and are a few. For example, if , elif, else etc.
Identifiers-
1. Identifier is a user-defined name given to a part of a program viz. variable, object, function etc.
2. Identifiers are not reserved .These are defined by the user and they can have letters, digits and a
symbol underscore.
3. They must begin with either a letter or underscore.
Q2. Give the example of Single-line string and Multiline String?
Ans. Single Line string- “This course is great”
Multiline string- There are two ways to write multiline strings-
i) By adding a \ (backslash) at the end of normal single –quote
Example- Text=”Welcome \
To \
Python”
ii) Str1=””” Welcome
To
Python
“””
Q3. Write a program to initalize the value of two variables then find sum.
Ans. # add two numbers
a=4
b=6
c=a+b
print ("Result is: ", c)
Q4. Write a program to enter the value of A and B variables then find Sum.
Ans. # add two numbers
a = int(input ("Enter first number: "))
b = int(input ("Enter second number: "))
c=a+b
print ("Result is: ", c)
Q5. Write a program to enter the value of two numbers then perform all airthmetic functions.
Ans. a = int(input("Enter value for 'a' "))
b = int(input("Enter value for 'b' "))
print ("a+b = ", a+b)
print ("a-b = ", a-b)
print ("a*b = ", a*b)
print ("a/b = ", a/b)
print ("a%b = ", a%b)
print ("a//b = ", a//b)
Q6. Write a program to enter two complex number then perform all arithmetic functions.
Ans. a = complex(input("Enter value for 'a' "))
b = complex(input("Enter value for 'b' "))
print ("a+b = ", a+b)
print ("a-b = ", a-b)
print ("a*b = ", a*b)
print ("a/b = ", a/b)
Q7. Write a Program to enter the value of a and b variable in string form then concatenate the string
and print first string in three times.
Ans. a = input("Enter value for 'a' ")
b = input("Enter value for 'b' ")
print ("a+b = ", a+b)
print ("a*3 = ", a*3)
# output
'''
Enter value for 'a' Computer
Enter value for 'b' Science
a+b = ComputerScience
a*3 = ComputerComputerComputer
'''
Q8. Write a program to enter the value of two variables then swap them using third variable.
Ans.
num1 = input('Enter First Number: ')

num2 = input('Enter Second Number: ')


print("Value of num1 before swapping: ", num1)
print("Value of num2 before swapping: ", num2)
# swapping two numbers using temporary variable
temp = num1
num1 = num2
num2 = temp

print("Value of num1 after swapping: ", num1)


print("Value of num2 after swapping: ", num2)

Q9. Program to get selling price and GST rate and then print Invoice along with both GST and SGST.
Ans. Item=input(“Enter Item Name:”)
SP=float(input(“enter selling price of Item”))
gstrate=float(input(“Enter GST rate”))
cgst=SP*((gstrate/2)/100)
sgst=cgst
amount=SP+cgst+sgst
print(“\t Invoice”)
print(“Item:”, item)
print(“Price :”,SP)
print(“CGST (@”,(gstrate/2), “%): “,cgst)
print(“SGST (@”,(gstrate/2), “%): “,sgst)
print(“Amount payable :”,amount)
Q10. Program to add numbers using floating variables.
Ans.
# add two numbers
a = float(input ("Enter first number: "))
b = float(input ("Enter second number: "))
# input returns str data type
c=a+b
print ("Result is: ", c)
Chapter 4
Data Handling
MLL
Q1.What is datatype?
Ans1.Datatype is the type of data along with specific types of operations which can be performed on it.
Q2.What are the two types of integers in Python?
Ans.The two types of integer datatypes in Python are:
1)Integers(signed) 2)Booleans.
Q3.What is the role of str() function in Python?
Ans.The str() functionconverts a value to string.
Q4.What do you understand by complex number?
Ans.A complex number is in the form of A+Bi where i is imaginary number,equal to the square root of -1.
Q5.What is an expression?
Ans.An Expression is composed of one or more operations.
Q6.What are the two types of Type conversion in Python?
Ans.There are two thypes of conversions in python:
1)Implicit type conversion 2)Explicit type conversion
Q7.Write the syntax to use math library.
Ans.import math
Q8.What is atom in context of expression in python?
Ans.An atom in python is something that has a value.Ex-variables,literals,strings,lists,tuples,sets etc.
Q9.What is the complement opeartor?
Ans.The complement operator inverts the values of each bit of operand.
Q10.What is equality(==) operator?
Ans.Equality operator(==) is used to compare two values and if both values are same then it returns True
otherwise it returns False.

HOTs
Q1.Why is Boolean considered a subtype of integers?
ans.Boolean values True and False internally map to integers 1 and 0 i.e. True for 1 and False for 0.That's
why Booleans are treated as a subtype of integers.
Q2.What do you understand by the term 'immutable'?
Ans.Immutable means unchangeable.In Python immutable types are those whose values cannot be
changed in place.
Q3.What will be the output of the following?
print(len(str(17//4)))
print(len(str(17/4)))
Ans. 1
3
Q4.What will be the output of the following?
a=5
b=-3
c=25
d=-10
a+b+c>a+c-b*d
str(a+b+c>a+c-b*d)==len(str(bool1(1)))
Ans. True
False
True
Q5.What will be the output produced by the folowing code statements?State reasons.
a)bool(0) b)bool(0j) c)bool('0j') d)bool(0.0)
Ans. False.
False
True
False
Q6.When the and operator will test the second operand?
And.The and operator will test the second operand only if the first operand is true,otherwise ignore it.
Q7.Among arithmetic operators and relational operator which operator in Python has higher
precedence?
Ans.In python,arithmetic operators have higher precedence over relational operator i.e
y+x>y*2
The given expression would be evaluated internally as (y+x)>(y*2)
Q8.What will be the output of the following:
a)87//5
b)87//5.0
c)(87//5.0)==(87//5)
d)(87//5.0)==int(87/5.0)
Ans.
a)17
b)17.0
c)True
d)True
Q9.Explian the term Type conversion in Python.
Ans.In Python typeconversion can take place in two forms implicit conversion,in which all operands are
converted up to the type of the largest operand and in Explicit type conversion the conversion of an
operand to a specific type takes place.
Q10.Write a program to obtain temperatures of 7 days(Monday,Tuesday....Sunday) then display average
temperature of the week.
And.Check your knowledge by doing it yourself.
CHAPTER: 5 & 6
1. SELECTION AND ITERATION STATEMENTS
2. STRING MANIPULATION
Q1 Write a program to find maximum of 3 numbers using nested if..else statement.
Ans n1=int(input("Enter first number"))
n2=int(input("Enter second number"))
n3=int(input("Enter third number"))
if n1>n2:
if n1>n3:
max=n1
else:
max=n3
elif n2>n3:
max=n2
else:
max=n3
print ('The largest of',n1,n2,n3,'is',max)

Q2 Write a program to input values for Principle and Time and calculate compound interest. If
time is less than 1 year, the rate of interest will be 5% per annum otherwise it will be 5.5% per
annum.
p=int(input("Enter Principal amount"))
Ans
t=int(input("Enter Time in years"))
if t<5:
r=5
else:
r=5.5
SI=p*r*t/100
print ("The rate of interest on ",p," for",t," years @",r,"% is",SI)

Q3 Write a program to input age of a person and print message “Eligible to Vote” if age is more
than 18 otherwise print message “not eligible to Vote”.
Ans age=int(input("Enter Your age"))
if age<18:
print("You are not eligible to vote.... You still have to wait for\
", 18-age," years to vote")
else:
print("You are eligible to vote... Go ahead and vote")

Q4 Write a program to check whether the entered number by user is even or odd.
Ans Check your progress

Q5 Find the output:


x,y =10, 15
if (x >= y):
z=x+y
else:
z = x -y
z = z ** 2
print “result =“, z
Ans Check your progress.

Q6 Rewrite the following program after finding and correcting syntactical errors and underlining it.
a, b = 0
if (a = b)
a +b = c
print z
Ans Check your progress.

Q7 What will be the output of the following code:


A = 3 – 4 + 10
B=5*6
C = 7.0/2.0
D = “Hello” * 3
print “Value are :“, A. B, C, D
Ans Check your progress

Q8 Write a program that takes name of student, marks (out of 100) of 3 subjects from user and
calculate total marks, percentage and grade as per the following criteria:
percentage Grade
>=75 A
>=60 and <75 B
<60 C
Ans Check your progress

Q9 Write a python program to check for voting age eligibility of a person.


Ans no=int(input("Enter any number"))
if no<0:
print("You have entered a negative number")
elif no>0:
print("You have entered a positive number")
else:
print("You have entered a ZERO")

Q10 Write a python program to acquire marks for a student (out of 100). The
program should display Pass if marks are greater of equal to 33 or else should
display Fail.
Ans Marks=int(input(" Enter the marks obtained out of 100 "))
if Marks>=33:
print("You have Passed")
else:
print("You have failed, Try again! ")

Q11 Write a program to sort three input numbers.

Q12 Find and write the output


for i in range(1,5):
print(i)
Ans 1
2
3
4

Q13 Write a python script to print following.


1

22

333
4444

55555
Ans # 10 is the total number to print
for num in range(6):
for i in range(num):
print (num, end=" ") #print number
# new line after each row to display pattern correctly
print("\n")

Q14 Program to find Greatest between two Numbers


Ans a = int(input(“Enter 1st Number”))
b = (int(input(‘Enter 2nd Number’)))
if a>b :
print (“%d is greater than %d ” % (a,b))
else :
print (“%d is greater than %d ” % (b,a))

Q15 Write a program to read a string with multiple words and then print each word in a new line.
Ans input_string = input("Enter a string : ")
for w in input_string.split():
print (w)

Q16 Write programs as follows using python to print table of Five


Ans n=int(input("Enter a no"))
for i in range(1,11):
print(n,' * ', i, ' = ', n*i)

Q17 What will be the output of the following?

i,total,sum=1,0,0
while(i<=10):
sum=sum+i
i=i+1
print(total+sum)
Ans 55
Q18 Program to Calculate Grade
Ans s1 = int(input(“ENter Marks of 1st Subject”))
s2 = (int(input(‘ENter Marks of 2nd Subject’)))
s3 = (int(input(‘ENter Marks of 3rd Subject’)))
s4 = (int(input(‘ENter Marks of 4th Subject’)))
s5 = (int(input(‘ENter Marks of 5th Subject’)))
total =s1 +s2 +s3 +s4 +s5
per =total/5
print (“\n\n Grade = “,end=”)
if per>=90 :
print(“A”)
elif per> 60 :
print (“B”)
elif per> 45 :
print (“C”)
elif per> 33 :
print (“D”)
else :
print (“E”)

Q19 Write python code to find the Fibonacci series of numbers till 20.
Ans x=0
y=1
print(x)
print(y)
for i in range(3,21):
z=x+y
x=y
y=z
print(z)

Q20 Write python code to print :


*

**

***

****
*****
Ans for i in range(1,6):
for j in range(1,i+1):
print('*',end="")
print("\n")

Q21 Explain any three String handling function used in python programming.
Ans Three string handling functions in python are:
1. It returns a copy of the string with only its first character capitalized.
Syntax
Following is the syntax for capitalize() method −

str.capitalize()

.
2 Description
The count() method returns the number of occurrences of substring sub in the range [start,
end]. Optional arguments start and end are interpreted as in slice notation.
Syntax
Following is the syntax for count() method −

str.count(sub, start = 0,end = len(string))

3. The len() method returns the length of the string.


Syntax
Following is the syntax for len() method −

len( str )

Q22 Rewrite the following code in python after removing all syntax error(s). Underline each
correction done in the code.
for Name in [Amar, Shweta, Parag]
IF Name[0]=’S’:
Print(Name)
for Name in [Amar, Shweta, Parag]
Ans
IF Name[0]=’S’:
Print(Name)
CORRECTED CODE:
for Name in ["Amar", "Shweta", "Parag"]:
if Name[0]=="S":
print(Name)

Q23 Write a program in python to calculate Bill amount as per given criteria..
Bill amount Discount
>=10000 10%
<10000 and >=5000 5%
<5000 and >=2000 2%
<2000 NIL
Ans Additional 2% discount if pay using card.
p_i1=int(input("Enter price of item 1"))
q_i1= int(input("Enter quantity of item 1"))
p_i2=int(input("Enter price of item 2"))
q_i2= int(input("Enter quantity of item 2"))
p_i3=int(input("Enter price of item 3"))
q_i3= int(input("Enter quantity of item 3"))
t_p1=p_i1*q_i1
t_p2=p_i2*q_i2
t_p3=p_i3*q_i3
tot_amt=t_p1+t_p2+t_p3
if tot_amt>=10000:
tot_amt=tot_amt-tot_amt*0.10
elif tot_amt>=5000:
tot_amt=tot_amt-tot_amt*0.05
elif tot_amt>=2000:
tot_amt=tot_amt-tot_amt*0.02
print ("Total payable amount= ",tot_amt)

Q24 To find the prime number series of numbers till 100.


Ans Check your progress
Q25 Write a program to check whether the given Year is Leap Year.
Ans year=int(input(“Enter Year”))
if year%100 ==0 and year % 4==0 :
print(“%d year is leap Year” %(year))
else :
print(“%d year is not a leap Year” %(year))

Q26 Write a program to print reverse a string.


Ans string1=input("Enter a string")
print(string1[::-1])

Q27 ABC shop deals with footwear and apparels. Write a program to calculate
total selling price after levying the GST. Do calculate central Govt. GST
and state govt. GST. GST rates are as under-

Item GST Rate

Footwear <=500 (For each pair) 5%

Footwear > 500 18%

Apparals<= 1000(Per piece) 5%

Ans Apparals> 1000(Per piece) 12%

Check your progress

Q28 Write four elements of while loop in python?


Ans Check your progress

Q29 Identify and correct the problem with following code-

countdown=10
while countdown &gt; 0:
print(countdown, end=’ ‘)
countdown – 1
print(“Finally.”)
Ans Check your progress

Q30 Predict the output of the following code-


d1={5:&quot;number&quot;,&quot;a&quot;:&quot;string&quot;,(1,2):&quot;tuple&quot;}
print(&quot;Dictionarycontents&quot;)
for x in d1.keys():
print(x,&#39;:&#39;,d1[x],end=&#39; &#39;)
print(d1[x]*3)
print()
Ans Check your Progress

Q31 Write a program in Python to check whether the entered string is


palindrome or not. (Hint- &quot;madam&quot; is a palindrome string.)

Q32 Write a python program to take input of three of 3 angles and display whether they form a
triangle or not.

Q33 Re-write the following code using while loop:


for a in (2,7,2):
for b in (1,a):
print(b, end= ‘$‘)
print()

Q34 Find the output of the following program code:


aDict = { ‘Bhavna’:1, “Richard”:2, “Firoza”:10, “Arshnoor”:20 }
temp = “ “
for key in aDict:
if temp < key:
temp = key
print (temp)

Q35 Write output of following

a. What is the output of print str if str = 'Hello World!'?


b. What is the output of print str[0] if str = 'Hello World!'?
c. What is the output of print str[2:5] if str = 'Hello World!'?
d. What is the output of print str[2:] if str = 'Hello World!'?

Q36 Find output of following


a. for x in range(5):
print(x)
b. for x in range(3, 6):
print(x)
c. for x in range(3, 8, 2):
print(x)
d. count = 0
while count < 5:
print(count)
count += 1
e. count = 0
while True:
print(count)
count += 1
if count >= 5:
break
f. for x in range(10):
if x % 2 == 0:
continue
print(x)

Q37 Explain the purpose of loop structures in a programming language. Describe the syntax and
semantics of one loop structure provided by Python.

Q38 Write a line of code to execute infinite loop in python.

Q39 Write a Python program to print multiplication table from 2 to 10.

Q40 Write a python program to accept age of a person from user and check
whether he has completed 18 years or more. If yes print ‘Eligible for Voting’
or else print ‘A Minor’

Q41 What will be the output of the following:


x=1
y=5
sum = 10
for i in range(1,y+1,2):
sum = sum + x
x=x+1
print(prod)
Q42 What will be the output of the following:
m,n=40,20
while m>n:
m=m%7
n = n//2
print(m,n)

Q43 Re-write the following program using for while


sum = 0
for x in range(10):
sum = sum + x**2
print(sum)

Q44 Re-write the following program after removing errors. Also underline the
corrections made.
n = 10
ams = 0
for i in (n+1)
ams=ams + sqrt(i)
print(ams)

Q45 What will be the output of the following:

st = '''My name is
NishaVerma'''
print(len(st))
st = 'My name is\
NidhiTrivedi'
print(len(st))

Q46 Write a program to accept a string from an user and count the number of
alphabets, digits and special characters in the string

Q47 What will be the output of the following python print statements for the
string str = ‘SUNDEW’ :
i) print(str*2)
ii) print(str[-4:-1])
Q48 What is String? How do you create a string in Python?

Q49 Write the outputs of following:


1. print(“I like study”,end=’#’)

2. print(“I like Playing game”)

Q50 What will be the output of following code fragment if the input
given is 8.
a=input(“enter a number”)
if(a>=8):
print(“Good morning”)
else:
print(“Good Evening”)
Chapter- 7 List Manipulation
A Define a list. Why it is a dynamic mutable type:
1
A list is an ordered collection of items which can be of any type. It is dynamic mutable mean we
Ans
can add or delete the items from the list at any time.
B Define a Dictionary. How we can access the data from it?

Dictionary is group of key value pairs. The elements in a dictionary are indexed by keys. Keys
Ans should be unique. we can access the data from dictionary by using keys

C Write a statement for following:


(i) Sum of all elements in a list([1,2,3,…100])
(ii) sum of all odd numbers in a list ([1,2,3,….100])

(i) Sum (range(101))


Ans
(ii) sum(range(1,101,2))

D What will be output of following:


(i) >>>[4]*4
(ii) >>>num=[17,123]
>>>num[-1]

(i) [4,4,4,4]

Ans (ii) 123

E Rewrite the following after removing all syntax errors. Underline each correction

for name in [amar,shveta,parag]


IF name[0] =’S’:
print(name)

for name in [‘amar’,’shveta’,’parag’]:


if name[0] ==’S’:
print(name)
Ans

F Write a program to perform linear search on given list


[10,51,2,18,4,31,13,5,23,64,29]

num=[10,51,2,18,4,31,13,5,23,64,29]
Ans print(“list element s are:”,end=” “)
for i in num:
print(i,end=” “)
print()
find=int(input(“”enter element to search))
flag=0
for i in num:
if(i===find):
flag=1
break
if flag==1:
print(“element found)
else:
print(“element not found)

2 A What are mutable data types ? Explain with example.


Check your progress
Ans

B Write the names of list methods to perform the following :


(i) Delete a given element from the list.
(ii) Add an element in the end of the list.
(i)remove() (ii) append()

C Write a program in Python to search for an element in a given list of numbers.

D Explain the use of following functions in list with example:


(i) insert ()
(ii) pop ()

E Write a program in Python to count the frequency of elements in a list using a dictionary.

For example This is a Computer program. Computer programs are related to real world.
Developing programs is an art.
Output : This :1 , is : 2, a:1, Computer : 2 program : 1 are : 1 and so on.

3 A Find the output of the following program code:


aDict = { ‘Bhavna’:1, “Richard”:2, “Firoza”:10, “Arshnoor”:20 }
temp = “ “
for key in aDict:
if temp < key:
temp = key
print (temp)

B Find and write the o/p.


A = [1,3,5,7,8,9]
print( A[3:0:-1] )
C Predict and write the output :
L=[`p’ ,'r','o','b','l','e','m']
L[2:3]=[]
Print(L)
L[2:5]=[]
Print(L)

D Find and write the o/p :


X=[“F”,66,”QE”,15,”S”,34]
Y=0
Z=””
A=0
For c in range(1,6,2)
Y+=c
Z=Z+X[c-1]+'$’
A+=X[c]
Print(x,y,z)

E Write down the program in python to sort a 3-item list .

F Write a program that rotates a list so that 1st element moves to 2nd index and so on . The item
at last index comes at first index .

4 A Write a program to count the number of elements in a list using dictionary

B Refer the following code and predict the output


a=[1,2,3]
b=[4,5,6]
c=a+b
d=c[0:3]
e=d
a[0]=10
c[4]=20
e[2]=30
Print (A[1]) (ii) print (B[0]) (iii) print (d) (iv) print (c[:])
(I)2 (II)4 (III)[1,2,30] (IV) [1,2,3,4,20,6]

C Identify the errors in the following code:


i.
L1 = [1,2,3,5] ii. L1 = [1,3,5,8]
An = L1.remove(7) An = L1.remove(8)
print(An + 2)

D Find out the output of following code segment:


numlist = [2,5,2,3,6,6,9]
pos=0
odds=evens=0
length=len(numlist)
while pos<length:
if numlist[pos]%2==0:
evens=evens+1
else:
odds=odds+1
pos=pos+1
if odds>evens:
print(Balanced oddity)

5 A Consider the following code and then answer the question that follow—
myDict={a:27,b:43, c:25, d:30}
valA= for I in myDict:
if I > valA
valA=i
valB= myDict[i]
print (valA) #Line1
print (valB) #Line2
print (30 in myDict) #Line3
myLst= (myDict.items())
myLst.sort()
print (myLst[-1]) #Line4
Write the output of the Line 1,2 ,3 and 4

B What type of objects can be used as keys in dictionaries? Also explain why?

C Write a Python program to get the smallest number from a list


Items=list(input(“Enter List Elements “))
Ans min = list[ 0 ]
for a in list:
if a < min:
min = a

print(“Minimum NO. IN LIST “,max)

D Write a Python program to sum all the items in a list.


Items=list(input(“Enter ListElements “))
Ans sum_numbers = 0
for x in items:
sum_numbers += x
print(sum_list([1,2,-8]))
E Write a Python program to get the largest number from a list.
Items=list(input(“Enter List Elements “))
Ans max = list[ 0 ]
for a in list:
if a > max:
max = a
print(“MAXIMUM NO. IN LIST “,max)

F Write a Python program to remove duplicates from a list


a = [10,20,30,20,10,50,60,40,80,50,40]
dup_items = set()
uniq_items = []
for x in a:
if x not in dup_items:
uniq_items.append(x)
dup_items.add(x)
print(dup_items)

6 A Write a Python program to check a list is empty or not.


Ans l=[]
if not l:
print(“List is empty”)

B Program to count numbers in a List


Ans x = [4, 7, 9, 12, 10]
count = 0 for i in x:
count= count + 1
print(“Total number of elements = “, count)

C Program to find average of numbers in a List


Ans A = [6, 2, 7, 9, 1, 3]
Sum = 0
Avg = 0
for x in range(len(A)): Sum += A[x];
Avg = Sum/len(A); print(“Average = “, Avg)

D Program to find maximum among N numbers in a List


Ans x=[]
N = eval(input(“entersize of list : “)) for i in range(0, N):
x.append(eval(input(“enter”+ str(i) + ” element : “))) print(“Numbers in the list are “)
print(x)
max = x[0]
for i in range(1, N):
if ( x[i] > max): max = x[i]
print(“Maximum value in the list = “, max)

E Program to find minimum among N numbers in a List


Ans x=[]
N = eval(input(“entersize of list : “)) for i in range(N):
append(eval(input(“enter”+ str(i) + ” element : “))) print(“Numbers in the list are “)
print(x)
min = x[0]
for i in range(1, N):
if ( x[i] < min): min = x[i]
print(“Minimum value in the list = “, min)

F Program to search a number in the list (Linear Search)


Ans A=[ ]
N=eval(input(“entertotal numbers to be entered”)) for i in range(0,N):
A.append(eval(input(“Enter”+str(i)+”Element”)))
s=eval(input(“enterelement to be searched”)) found=-1
for i in range(0,N):
if (s==A[i]):
found=i
if (found!=-1):
print(“element found at position”,found) else:
print(“element not found”)

7 A Program to arrange numbers in ascending order using Bubble Sort Method


Ans x = []
N = eval(input(“entersize of list : “)) for i in range(0, N):
x.append(eval(input(“enter”+ str(i) + ” element : “))) print(x)
count = 0
for i in range(0, N-1):
for j in range(0, N-i-1): if x[j] > x[j+1]:
t = x[j]
x[j] = x[j+1] x[j+1] = t
count = count + 1 print(“Pass”,i+1,”:”, x)
print(“Total number of operations = “, count)
print(“Elements in ascending order are : \n”, x)

B Program to arrange numbers in ascending order using Insertion Sort Method


Ans. x=[]
N = eval(input(“entersize of list : “)) for i in range(0, N):
x.append(eval(input(“enter”+ str(i) + ” element : “))) print(“List with original elements :\n”,x)
#we assume that smallest element at first index i.e. 0
for i in range(2, N): t = x[i]
k = i-1
while t < x[k]: x[k+1] = x[k] k = k – 1
x[k+1] = t
print(“Sorted List in ascending order :\n”,x)

C Program to arrange numbers in ascending order using Selection Sort Method


Ans x=[]
N = eval(input(“entersize of list : “))
for i in range(0, N):
x.append(eval(input(“enter”+ str(i) + ” element : “)))
print(x)
count = 0
for i in range(0, N-1):
for j in range(i+1, N): if x[i] > x[j]:
t = x[i] x[i] = x[j] x[j] = t
count = count + 1 print(“Pass”,i+1,”:”, x)
print(“Total number of operations = “, count
print(“Elements in ascending order are : \n”, x)

D Program to read a list and print only those numbers which are divisible by 5 and not by 7
Ans num=list(eval((input(“Enter numbers “))))
for i in num:
if (i%5==0 and i%7 !=0):
print (i,”is divisable by 5 but not by 7″)

Chapter – 9 Introduction Python Modules

INTRODUCING PYTHON PANDAS-I

Q 1: Who is the main author of Pandas?


Ans1: Wes McKinney
Q2: What is numpy array?
Ans2: A NumPy array is simply a grid that contains values of the same/homogeneous type.
Q 3: What do you understand by series?
Ans3: A series is a Pandas data structure that represents a one-dimensional array-like object containing
an array of data and an associated array of data labels, called its index.
Q 4: Write a small code to create empty array.
Ans4: numpy.empty ([4 , 2])
Q 5: What is the default datatype for numpy array?
Ans 5: float64
Q 6: Write a simple code to specify Nan values in Series .
Ans 6: obj = pd.Series([2 , 5, np.Nan , 4])
Q 7: How to create a 1D array using arrange function ?
(Create a 1D array of numbers from 0 to 9 )
Ans 7: arr = np.arrange(10)
Q 8 : How to replace all odd numbers in arr with -1
Ans 8 : arr = [ arr % 2== 1] = -1

Q 9: Write a Python program to convert a NumPy array to a Pandas series.


NumPy array:[10 20 30 40 50]
Ans 9: import numpy as np
import pandas as pd
np_array = np.array([10, 20, 30, 40, 50])
print("NumPy array:")
print(np_array)
new_series = pd.Series(np_array)
print("Converted Pandas series:")
print(new_series)
Q 10: Explain head() and tail() functions .
Ans 10 : The head () function is used to fetch first n rows from pandas object.
Syntax: <pandas object>.head( [n] )
The tail() function is used to fetch last n rows from a pandas object.
Syntax : pandas object>.tail( [n] )
Q 11 :What is Pandas/Python/pandas?
Ans 11: Pandas is a Python package providing fast, flexible, and expressive data structures designed to
make working with “relational” or “labeled” data both easy and intuitive. It aims to be the fundamental
high-level building block for doing practical, real world data analysis in Python.
Q 12:What is Python pandas used for?
Ans 12: pandas is a software library written for the Python programming language for data
manipulation and analysis. In particular, it offers data structures and operations for manipulating
numerical tables and time series.
Q 13 . How to create 3x3 identity matrix ?
Ans 13: z =np.eye(3)
print(z)
Q 14: Consider a (6,7,8) shape array, what is the index (x,y,z) of the 100th element?
Ans 14: import numpy as np
z = (np.unravel_index(100,(6,7,8)))

Q 15: Write a Python program to add, subtract, multiple and divide two Pandas Series.
Sample Series: [2, 4, 6, 8, 10], [1, 3, 5, 7, 9]
Ans 15: import pandas as pd
ds1 = pd.Series([2, 4, 6, 8, 10])
ds2 = pd.Series([1, 3, 5, 7, 9])
ds = ds1 + ds2
print("Add two Series:")
print(ds)
print("Subtract two Series:")
ds = ds1 - ds2
print(ds)
print("Multiply two Series:")
ds = ds1 * ds2
print(ds)
print("Divide Series1 by Series2:")
ds = ds1 / ds2
print(ds)
Q 16: write the output of following code:-
Import pandas as pd
Lst = [ 6,9,3,5]
Obj = pd.Series( data = ( 2* Lst))
print (obj)
Ans 16 : 0 6
1 9
2 3
3 5
4 6
5 9
6 3
7 5
Dtype float 64
Q 17: Find the output of the folloing code fragment-
import numpy as np
arr1 = np.array([1,2,3,4,5])
arr2 = np.array([0,9,8,7,6])
arr3 = arr1 + arr2
arr3 *=arr1
print (arr3[2])
Ans 17: Output-
33
Q 18: Find the output of folloing python code-
import numpy as np
a = np.array([1,2,3,4,5])
b = np.arange(-5,5,2)
c=a+b
print (c[4])
Ans 18: Output-
8
Q 19: Find the output of following code-
import numpy as np
a = np.array([[0, 1, 0], [1, 0, 1]])
a += 3
b=a+3
print (a[1,2] + b[1,2])
Ans 19: Output: 11

Que 20 : How to retrieve shape of Series Object?


Ans 20: The shape of a series object tells how many elements it contains including missing or empty
values .
Syntax: print(ob.shape)
Chapter- 11 Python Pandas II – DataFrames and Other Operations

Q 1: What is dataframe ?
Ans 1: A Data frame is a two-dimensional data structure, i.e., data is aligned in a tabular fashion in rows
and columns.
Features of DataFrame
 Potentially columns are of different types
 Size – Mutable
 Labeled axes (rows and columns)
 Can Perform Arithmetic operations on rows and columns
Q 2. Write a python code to create a empty DataFrame from .
Ans 2: import pandas as pd
df = pd.DataFrame()
print ( df)
Q 3: Write a code to create a dtaframe from a 2D dictionary .
Ans 3: import pandas as pd
d={ ‘a’ : 20 , ‘b’:30 , ‘c’ :40 , ‘d’: 50}
df= pd.DataFrame(d)
print(df)
Q 4 : Write the output of the following code-
Import pandas as pd
Import numpy as np
arr=np.array([ [ 6,7,8 ] , [ 3, 6 , 8 ], [1,2,3] , np.int32] )
Df = pd.DataFrame( arr , columns = [ ‘ a’ ,‘b’ ,‘c ‘ ] , index =[‘A’,’B’,’C’]
Ans 5: Output-
a b c
A 6 7 8
B 3 6 8
C 1 2 3
Q 6: How to fill missing values in DataFrame ?
Ans 6: For filling missing values you can use fillna() method . For example-
Df = df1.fillna( 0 )
Q 7: Explain concat () method .
Ans 7: The concat( ) can concate two dataframes along the rows or along columns . This method is
useful if the two dataframe have similar structures.
If we have two data frame df1 and df2 with similer structure than –
pd.concat([ df1 , df2])
Q 8: How to drop columns that have any NaN values ?
Ans 8: Suppose we have a data frame df having some NaN values .
Df2 = df.droapna(axis = 1)

Que 9: Find the output of following program-


def func1():
import pandas as pd
data1 = {'a' : [1,2,3,4],
'b': [11,22,33,44 ],
'c':[20,30,40,50] ,
'd':[100 , 200 , 300 , 400]}
df1 = pd.DataFrame(data1)
row = df1.loc[1,:]
print(row.shape)
func()
Ans 9: Output-
(4, )

Q 10: Find the output of following program


def func3():
import pandas as pd
data1 = {'a':[1,2,3,4],
'b':[11,22,33,44],
'c':[20,30,40,50],
'd':[100,200,300,400]}
df1 = pd.DataFrame(data1)
row = df1.loc[1:1,]
print(row)
func3()
Ans 10 : output -
a 2
b 22
c 33
d 44

I) PYTHON PANDAS II DATAFRAME AND OTHER OPERATIONS


II) DATA TRANSFER BETWEEN FILES,SQL DATABASES AND DATAFRAMES

MLL
Q1.How To Create a Pandas DataFrame?
Ans.Among the many things that can serve as input to make a ‘DataFrame’, a NumPy ndarray is one of
them. To make a data frame from a NumPy array, you can just pass it to the DataFrame() function in
the data argument.
data = np.array([['','Col1','Col2'], ['Row1',1,2], ['Row2',3,4]]) print(pd.DataFrame(data=data[1:,1:],
index=data[1:,0],columns=data[0,1:]))
Q2. How To Select an Index or Column From a Pandas DataFrame?
Ans-selecting an index, column or value from your DataFrame isn’t that hard, quite the contrary. It’s
similar to what you see in other languages (or packages!) that are used for data analysis. If you aren’t
convinced, consider the following:
# Using `iloc[] print(df.iloc[0][0])
# Using `loc[] print(df.loc[0]['A'])
# Using `at[] print(df.at[0,'A'])
# Using `iat[] print(df.iat[0,0])
3. How To Add an Index, Row or Column to a Pandas DataFrame?
Ans-When you create a DataFrame, you have the option to add input to the ‘index’ argument to make
sure that you have the index that you desire. When you don’t specify this, your DataFrame will have, by
default, a numerically
valued index that starts with 0 and continues until the last row of your DataFrame.
However, even when your index is specified for you automatically, you still have the power to re-use
one of your columns and make it your index. You can easily do this by calling set_index() on your
DataFrame.
 .loc[] works on labels of your index. This means that if you give in loc[2], you look for the values
of your DataFrame that have an index labeled 2.
 .iloc[] works on the positions in your index. This means that if you give in iloc[2], you look for the
values of your DataFrame that are at index ’2`.
Adding a Column to Your DataFrame
you want to make your index part of your DataFrame. You can easily do this by taking a column
from your DataFrame or by referring to a column that you haven’t made yet and assigning it to
the .index property, just like this:
df = pd._________(data=np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]), columns=['A', 'B', 'C'])
# Use `.index`
df['D'] = df.index
Q4.How to Delete Indices, Rows or Columns From a Pandas Data Frame?
i)Deleting an Index from Your DataFrame
Ans-You want to remove the index from your DataFrame, you should reconsider because DataFrames
and Series always have an index.
However, what you *can* do is, for example:
 resetting the index of your DataFrame (go back to the previous section to see how it is done) or
 remove the index name, if there is any, by executing del df.index.name,
Deleting a Column from Your DataFrame
To get rid of (a selection of) columns from your DataFrame, you can use the drop() method:
Removing a Row from Your DataFrame
You can remove duplicate rows from your DataFrame by executing df.drop_duplicates(). You
can also remove rows from your DataFrame, taking into account only the duplicate values that
exist in one column.
Q5. How to Rename the Index or Columns of a Pandas DataFrame?
Ans- To give the columns or your index values of your dataframe a different value, it’s best to use
the .rename() method.
newcols = {
'A': 'new_column_1',
'B': 'new_column_2',
'C': 'new_column_3'
}
Q6. How To Create an Empty DataFrame?
Ans. The function that you will use is the Pandas Dataframe() function: it requires you to pass the data
that you want to put in, the indices and the columns.
df = pd.DataFrame(np.nan, index=[0,1,2,3], columns=['A'])
print(df)
Q7. How To Iterate Over a Pandas DataFrame?
Ans-You can iterate over the rows of your DataFrame with the help of a for loop in combination with
an iterrows() call on your DataFrame:
df = pd.DataFrame(data=np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]), columns=['A', 'B', 'C'])

for index, row in df.iterrows() :


print(row['A'], row['B'])
Q8. How To Write a Pandas DataFrame to a File.
Output a DataFrame to CSV
To write a DataFrame as a CSV file, you can use to_csv():
Writing a DataFrame to Excel
Similarly to what you did to output your DataFrame to CSV, you can use to_excel() to write your table to
Excel.
Q9.What is PIP for Python?
Ans: pip is a package management system used to install and manage software packages written
in Python. Many packages can be found in the Python Package Index (PyPI). Python 2.7.9 and later (on
the python2 series), and Python 3.4 and later include pip (pip3 for Python 3) by default.
Q10.Write a Pandas program to convert a Panda module Series to Python list and it’s type.
import pandas as pd
ds = pd.Series([2, 4, 6, 8, 10])
print("Pandas Series and type")
print(ds)
print(type(ds))
print("Convert Pandas Series to Python list")
print(ds.tolist())
print(type(ds.tolist()))
Q11:Write a Pandas program to iterate over rows in a DataFrame.
Ans:import pandas as pd
import numpy as np
exam_data = [{'name':'Anastasia', 'score':12.5}, {'name':'Dima','score':9},
{'name':'Katherine','score':16.5}]
df = pd.DataFrame(exam_data)
for index, row in df.iterrows():
print(row['name'], row['score'])
Q12.What is full form of CSV?
Ans: A CSV is a comma-separated values file, which allows data to be saved in a tabular format. CSVs
look like a garden-variety spreadsheet but with a .csv extension.
Q13.Which method is used for sorting data in a particular column in Data Frame?
Ans: order
Q14.What is the difference between the two data frames given below?
i)df[‘name’] ii)df.loc[:’name’]
Ans:i) This a copy of original dataframe.ii) this is a view of original dataframe.
Q15. How would you create this identity matrix in python?
A=[1,0,0
0,1,0
0,0,1]
Ans: np.eye(3) with import numpy as np
Q15. Write a program to display the record from student table using MySQL?
Ans
import pymysql
con=pymysql.connect(host='local',user='root',password='tiger',db='test')
stmt=con.cursor()
query='select * from student;'
stmt.execute(query)
data=stmt.fetchone()
print(data)
Q16. Write a program to write the data in CSV file using ‘w’ mode.
Ans- f=open("c:\\PythonWork\\stud.csv",'w')
n=int(input("Enter limit : "))
for i in range(101,101+n):
nm=input("Enter Name for roll no : %d"%i)
cl=input("Enter Class for Roll No : %d : "%i)
f.write(str(i)+','+nm+','+cl+'\n')
f.close()
Q17. Write a program to open a CSV file using ‘w+’ mode.
Ans. f=open("c:\\PythonWork\\stud.csv",'w+')
n=int(input("Enter limit : "))
for i in range(101,101+n):
nm=input("Enter Name for roll no : %d"%i)
cl=input("Enter Class for Roll No : %d : "%i)
f.write(str(i)+','+nm+','+cl+'\n')
f.close()
Q18. Write a program to open a CSV file using ‘a’ mode.
Ans- f=open("c:\\PythonWork\\stud.csv",'a')
n=int(input("Enter limit : "))
for i in range(101,101+n+1):
nm=input("Enter Name for roll no : %d"%i)
cl=input("Enter Class for Roll No : %d : "%i)
f.write(str(i)+','+nm+','+cl+'\n')
f.close()
Q19. Write a program to open a CSV file using ‘r+’ mode.
Ans- f=open("c:\\PythonWork\\stud.csv",'r+')
n=int(input("Enter limit : "))
for i in range(101,101+n):
nm=input("Enter Name for roll no : %d"%i)
cl=input("Enter Class for Roll No : %d : "%i)
f.write(str(i)+','+nm+','+cl+'\n')
f.close()

HOTS
Q 1: write any four features of python program?
Ans:Features of DataFrame
Potentially columns are of different types
Size – Mutable
Labeled axes (rows and columns)
Can Perform Arithmetic operations on rows and columns
Q2:What are various inputs are taken to create dataframes.
Ans:Lists
dict
Series
Numpy ndarrays
Another DataFrame
Q 3: Write a small python code to drop a dataframe.
Ans:import pandas as pd
df = pd.DataFrame([[1, 2], [3, 4]], columns = ['a','b'])
df2 = pd.DataFrame([[5, 6], [7, 8]], columns = ['a','b'])
df = df.append(df2)
# Drop rows with label 0
df = df.drop(0)
print df
Q 4: Write a Pandas program to convert a Panda module Series to Python list and it’s type.
Ans:-
import pandas as pd
ds = pd.Series([2, 4, 6, 8, 10])
print("Pandas Series and type")
print(ds)
print(type(ds))
print("Convert Pandas Series to Python list")
print(ds.tolist())
print(type(ds.tolist()))
Q 5:Write steps to convert a dictionary to a Pandas series.
Sample dictionary: d1 = {'a': 100, 'b': 200, 'c':300, 'd':400, 'e':800
Ans:
import pandas as pd
d1 = {'a': 100, 'b': 200, 'c':300, 'd':400, 'e':800}
print("Original dictionary:")
print(d1)
new_series = pd.Series(d1)
print("Converted series:")
print(new_series)
Q6:Write a Pandas program to add, subtract, multiple and divide two Pandas Series.
Ans:import pandas as pd
ds1 = pd.Series([2, 4, 6, 8, 10])
ds2 = pd.Series([1, 3, 5, 7, 9])
ds = ds1 + ds2
print("Add two Series:")
print(ds)
print("Subtract two Series:")
ds = ds1 - ds2
print(ds)
print("Multiply two Series:")
ds = ds1 * ds2
print(ds)
print("Divide Series1 by Series2:")
ds = ds1 / ds2
print(ds)
Q 7:Write a Pandas program to get list from DataFrame column headers.
Assume data from yourself.
Ans:
import pandas as pd
import numpy as np
exam_data = {'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael', 'Matthew', 'Laura',
'Kevin', 'Jonas'],
'score': [12.5, 9, 16.5, np.nan, 9, 20, 14.5, np.nan, 8, 19],
'attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],
'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'no', 'yes']}
labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
df = pd.DataFrame(exam_data , index=labels)
print(list(df.columns.values))
Q 8:what are things or operations performed does very well in python?
Ans: Easy handling of missing data (represented as NaN) in floating point as well as non-floating point
data
Size mutability: columns can be inserted and deleted from DataFrame and higher dimensional objects
Automatic and explicit data alignment: objects can be explicitly aligned to a set of labels, or the user can
simply ignore the labels and let Series, DataFrame, etc. automatically align the data for you in
computations
Powerful, flexible group by functionality to perform split-apply-combine operations on data sets, for
both aggregating and transforming data
Make it easy to convert ragged, differently-indexed data in other Python and NumPy data structures
into DataFrame objects
Intelligent label-based slicing, fancy indexing, and subsetting of large data sets
Intuitive merging and joining data sets
Flexible reshaping and pivoting of data sets
Hierarchical labeling of axes (possible to have multiple labels per tick)
Robust IO tools for loading data from flat files (CSV and delimited), Excel files, databases, and saving /
loading data from the ultrafast HDF5 format
Time series-specific functionality: date range generation and frequency conversion, moving window
statistics, moving window linear regressions
Q 9:Write a Pandas program to calculate the mean score for each different student in data frame. Take
your own data fir name, scorw attempts and qualify fiels.
Ans:
import pandas as pd
import numpy as np
exam_data = {'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael', 'Matthew', 'Laura',
'Kevin', 'Jonas'],
'score': [12.5, 9, 16.5, np.nan, 9, 20, 14.5, np.nan, 8, 19],
'attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],
'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'no', 'yes']}
labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']

df = pd.DataFrame(exam_data , index=labels)
print("\nMean score for each different student in data frame:")
print(df['score'].mean())
Q 10: Write a Pandas program to compare the elements of the two Pandas Series.
Sample Series: [2, 4, 6, 8, 10], [1, 3, 5, 7, 9]
Ans:
import pandas as pd
ds1 = pd.Series([2, 4, 6, 8, 10])
ds2 = pd.Series([1, 3, 5, 7, 10])
print("Series1:")
print(ds1)
print("Series2:")
print(ds2)
print("Compare the elements of the said Series:")
print("Equals:")
print(ds1 == ds2)
print("Greater than:")
print(ds1 > ds2)
print("Less than:")
print(ds1 < ds2)

Simple Queries and Table Creation and Data Manipulation

Ques1 What is DBMS?

Ans: A Database Management System (DBMS) is a program that controls creation,


maintenance and use of a database. DBMS can be termed as File Manager that manages
data in a database rather than saving it in file systems.

Ques2 Why a database is called as relational database model?

Ans: A database model represents the relationship between one or more databases. The
relationship is known as the relational database model. It is an extension of the normal
databases without relations. It provides flexibility and allows one database to be in
relation with another database. It can access the data from many databases at one time
over the network.

Ques3 What are entities and attributes referring to?

Ans: - Table consists of some properties that are known as attributes.


- These consist of the representation of entity in the table.
- They are represented by columns in the table.
- Entity is referred to the store data about any particular thing.
- It is the smallest unit inside the table.

Ques4 What do you understand by Data Independence?

Ans: Data independence tells about the independence of the data inside the application. It
usually deals with the storage structure and represents the ability to modify the schema
definition. It doesn’t affect the schema definition which is being written on the higher
level.

There are two types of data independence:

1. Physical data independence: It allows the modification to be done in physical level and
doesn’t affect the logical level.
2. Logical data independence: It allow the modification to be done at logical level and
affects the view level.

Ques5 What are different features of an RDBMS?

Ans: Answer:
Name. Every relation in a relational database should have a name which is unique
among all other relations.
Attributes. Each column in a relation is called an attribute.
Tuples. Each and every row in a relation is called a tuple. A tuple defines a
collection of attribute values.

Ques6 What are the advantages of RDBMS?

Ans: Answer:
•Controlling Redundancy.
•Integrity can be enforced.
•Inconsistency can be avoided.
•Data can be shared.
•Standard can be enforced.

Ques7 What's Mysql ?

Ans: MySQL (pronounced "my ess cue el") is an open source relational database management
system (RDBMS) that uses Structured Query Language (SQL), the most popular language
for adding, accessing, and processing data in a database. Because it is open source,
anyone can download MySQL and tailor it to their needs in accordance with the general
public license. MySQL is noted mainly for its speed, reliability, and flexibility.

Ques8 What is SQL?

Ans: Structured Query Language is a database tool which is used to create and access
database to support software application.

Ques9 What are tables in SQL?

Ans: The table is a collection of record and its information at a single view.

Ques10 What are the features of MySQL?

Ans: MySQL provides cross-platform support, wide range of interfaces for application
programming and has many stored procedures like triggers and cursors that helps in
managing the database.

Ques11 What do DDL, DML, and DCL stand for?

Ans: DDL is the abbreviation for Data Definition Language dealing with database schemas as
well as the description of how data resides in the database. An example is CREATE TABLE
command. DML denotes Data Manipulation Language such as SELECT, INSERT etc. DCL
stands for Data Control Language and includes commands like GRANT, REVOKE etc.

Ques12 What is a query?

Ans: A DB query is a code written in order to get the information back from the database.
Query can be designed in such a way that it matched with our expectation of the result
set. Simply, a question to the Database.

Ques13 What is a constraint?

Ans: Constraint can be used to specify the limit on the data type of table. Constraint can be
specified while creating or altering the table statement. Sample of constraint are.

Ques14 What is data Integrity?

Ans: Data Integrity defines the accuracy and consistency of data stored in a database. It can
also define integrity constraints to enforce business rules on the data when it is entered
into the application or database.

Ques15 What is a View?

Ans: A view is a virtual table which consists of a subset of data contained in a table. Views are
not virtually present, and it takes less space to store. View can have data of one or more
tables combined, and it is depending on the relationship.

Ques16 What are tables and Fields?

Ans: A table is a set of data that are organized in a model with Columns and Rows. Columns
can be categorized as vertical, and Rows are horizontal. A table has specified number of
column called fields but can have any number of rows which is called record.
Ques17 What is a primary key?

Ans: A primary key is a combination of fields which uniquely specify a row. This is a special
kind of unique key, and it has implicit NOT NULL constraint. It means, Primary key values
cannot be NULL.

Ques18 What is a unique key?

Ans: A Unique key constraint uniquely identified each record in the database. This provides
uniqueness for the column or set of columns.

Ques19 What is a foreign key?

Ans: A foreign key is one table which can be related to the primary key of another table.
Relationship needs to be created between two tables by referencing foreign key with the
primary key of another table.

Ques20 What is different data types in MYSQL?

Ans: SQL Data Types


 Numeric data types such as int, tinyint, bigint, float, real etc.
 Date and Time data types such as Date, Time, Datetime etc.
 Character and String data types such as char, varchar, text etc.

Ques21 How do we use DISTINCT statement? What is its use?

Ans: DISTINCT statement is used with the SELECT statement. If the records contain duplicate
values then DISTINCT is used to select different values among duplicate records.

Ques22 How many Aggregate Functions are available there in SQL?

Ans: SQL Aggregate Functions calculates values from multiple columns in a table and returns a
single value.
 AVG(): Returns the average value from specified columns
 COUNT(): Returns number of table rows
 MAX(): Returns largest value among the records
 MIN(): Returns smallest value among the records
 SUM(): Returns the sum of specified column values

Ques23 Write a SQL SELECT query that only returns each name only once from a table?

Ans: To get the each name only once, we need to use the DISTINCT keyword.
SELECT DISTINCT name FROM table_name;

Ques24 Explain DML and DDL?


Ans: Ans. DML stands for Data Manipulation Language. INSERT, UPDATE and DELETE are DML
statements.
DDL stands for Data Definition Language. CREATE, ALTER, DROP, RENAME are DDL
statements.

Ques25 Can we rename a column in the output of SQL query?.

Ans: Ans. Yes using the following syntax we can do this SELECT column_name AS new_name
FROM table_ name;

Ques26 Give the order of SQL SELECT?.

Ans: Ans. Order of SQL SELECT clauses is: SELECT, FROM, WHERE, GROUP BY, HAVING, ORDER
BY. Only the SELECT and FROM clause are mandatory

Ques27 What is SQL comments?

Ans: Ans. SQL comments can be put by two consecutive hyphens (–).

Ques28 Difference between TRUNCATE, DELETE and DROP commands?

Ans: Ans. DELETE removes some or all rows from a table based on the condition. It can be
rolled back TRUNCATE removes ALL rows from a table by de-allocating the memory
pages. The operation cannot be rolled back
Chapter – 16 Table Joins and Indexes in SQL
MLL/HOTs
Q1. What do you means by Join term in SQL?
Ans. A Join is a query that combines rows from two or more tables.
Q2. What is a Table alias.
Ans- A table alias is a temporary label given along with table name in FROM clause.
Q3. What is use of table Index in SQL.
Ans. An index is a data structure maintained by a database that helps it find records within a table more
quickly. It stores the sorted/ordered values within the index field and their location in the actual table.
Q4. How you can create an Index in SQL?
Ans. Index can be created in MySQL at the time of table creation and even after that.
Q5. What is Cross Join?
Ans- A form of join that produces all possible combinations of row from two tables , is known as Cross
join.
Q6. What is Natural Join?
Ans. The Join in which only one of the identical columns exists, is called Natural Join.
Q7. What is Cartesian Product ?
Ans- In Cartesion Product of two tables, all prossible cpncatenations are formed of all rows of both the
tables.
Q8. How many different types of joins can you create in MySQL?
Ans. (i) Cross Join (ii) Left Join (iii) Natural Join (iv) Equi –Join
Q9. A table FLIGHT has 4 rows and 2 columns and another table AIR HOSTESS has 3 rows and 4 columns.
How many rows and Columns will be there if we obtain the Cartesian product of these tables?
Ans- 12 rows , 6 columns
Q10. Table Employee has 4 records and Table Dept has 3 records in it. Mr. Join wants to display all
information stored in both of these related tables. He forget to specify equi-join condtion in the query.
How many rows will get displayed on execution of this query?
Ans- 12 rows (4x3)
Chapter- 17
Cyber Security
MLL
Q1. What should you do to protect your identity on internet?
Ans 1- The most common solution for protection of identity on internet is Private Browsing or
Anonymous Browsing.
Q2. What is Cyber Safety?
Ans 2- Cyber safety refers to the safe and responsible use of internet so that to ensure safety and
security of personal information and non-posting threat to anyone else’s information.
Q3. What are persistent cookies?
Ans 3- Super cookies are called persistent cookies.
Q4. Name some of the common social networking sites.
Ans 4- Facebook, Twitter, LinkedIn, Instagram, Google+, Pinterest, SnapChat, Reddit etc.
Q5. What is a firewall?
Ans 5- Firewall is a program that monitors all communications and traps all illicit packets.
Q 6- Who are Cyber Trolls?
Ans 6- Derogatory messages or comments posted online targeting people are called cyber trolls.
Q7. Should you use a nickname when you log on to the Internet?
Ans7- Yes. It is always a good practice to use a nickname when we log on to the Internet. This will make
it difficult for identity thieves to find us.
Q8. Should one report cybercrime or should tolerate it silently?
Ans 8- One must report cybercrime without any fear.
Q 9- Where to report cybercrime?
Ans 9- The local police stations can be approached for filling complaints just as the cybercrime cells
specially designated with the jurisdiction to register complaints.
Q10. What do you understand by Super Cookies?
Ans 10- These are also cookies but these are persistent cookies i.e. they come back even after you
delete them.
Q 11- what does https means in an URL?
Ans 11- https:// in a URL means it is a secure connection and no one can see your private information.
Q 12-Name any one browser or search engine for private browsing.
Ans 12- DuckDuckgo.
Q13-What do you mean by VPN?
Ans 13- VPN is a method used to add security and privacy to private and public networks, like WiFi
hotspots and the Internet.
Q 14- What are First Party cookies?
Ans 14- These are the cookies that stores your own login id, passwords, auto fill information etc. for
some websites that you frequently visit.
Q 15- What are Third party cookies?
Ans 15- These are the cookies that websites stores to know about your search history and web browsing
history so as to place advertisements as per your interest.

Hots
Q1. What is private browsing?
Ans 1- It is a type of browsing wherein browser opens in incognito mode or through proxy or VPN, and
does not store cookies about your online activities.
Q2. How do website track you online?
Ans 2- There are various ways by which websites can track us like- IP Address, Cookies and Tracking
Scripts , HTTP Referrer, Super cookies and User Agent.
Q3 What is cybercrime?
Ans 3- Any criminal offense that is facilitated by, or involves the use of, electronic communications or
information systems, including and electronic device, computer, or the internet is referred to as
Cybercrime.
Q4. What is digital footprint?
Ans 4- Digital Footprints are the records and traces individuals’ activities as they use the internet. These
are permanently stored.
Q5. What are the usage rules for effective use of social networking sites?
Ans 5- you should follow following usage rules for the effective use of social networking sites-
a. Be Authentic.
b. Use a Disclaimer
c. Don’t pick fights Online
d. Don’t use Fake Names or Pseudonyms
e. Protect your Identity.
f. Respect your Audience.
g. Respect other’s sentiments.
Q6. Define the term Cyber bullying.
Ans 6- Cyber bullying- Harassing, demeaning, embarrassing, defaming or intimidating someone using
modern technologies like internet, cell phones, instant messengers, social networks etc. is called Cyber
Bullying.
Q7. What do you understand by identity theft?
Ans 7- Identity theft is a type of fraud that involves using someone else’s identity to steal money or gain
other benefits. Online identity theft refers to an act of stealing someone’s personal information such as
name, login details etc. and then posing as that person online.
Q8. What are the common practices to ensure confidentiality of information?
Ans 8- Common practices to ensure confidentiality of information are-. Use Firewall whenever possible.
b. Control browse setting to block tracking.
c. Browse privately whenever possible.
d. Be careful while posting on internet.
e. Ensure safe sites while entering crucial information.
f. Carefully handle emails.
g. Do not give sensitive information on wireless networks.
h. avoid using public computers.
Q9- What is an IP address?
Ans 9- IP address is a unique address of your device when you connect to the internet. From you IP
address, a website can determine your rough geographical location.
Q10. What is an HTTP referrer?
Ans 10- If you clicked a link to an outside website on a webpage then the linked website will get opened
and internally information about you such as your IP address, location, your web browser, machine type
etc. will be provided to the linked website- it is known as HTTP referrer.

Q11. What do you understand by Spreading Rumors Online?


Ans 11-It is a cybercrime and is a punishable offence. As per Information Technology Act of India,
publishing/circulation of rumors, especially hurting religious sentiments is a cybercrime and it may invite
a fine with imprisonment extendable up to three years.
Q 12- what are the common practices while using public computers for personal use?
Ans 12-
a. Browse privately, first of all.
b. Don’t save your login information.
c. Never save your password.
d. Avoid entering sensitive information.
e. Don’t leave the computer unattended.
f. Disable the features that store passwords.
g. Properly logout before leaving.
h. Erase history and traces of your work.
Q13. Define the term Cyber Stalking.
Ans 13-Cyber Stalking- this is a kind of online harassment wherein the victim is subjected to a barrage of
online messages and emails. A cyber stalker relies upon the anonymity afforded by the internet to allow
them to stalk victim without being detected.
Q 14. What are cookies?
Ans 14- Cookies are the small pieces of information websites can store in your browser. Cookies can
identify you and track your browsing activity across a website.
Q 15. What is confidentiality of information?
Ans 15- Confidentiality of information ensures that only authorized users get access to sensitive and
protected data.
Chapter -18
Online access and computer security

MLL
Q1- What is an adware?
Ans 1- These are the programs that deliver unwanted ads to your computer. They consume your
network bandwidth.
Q2- What is anti-virus software?
Ans 2- An anti-virus program help to detect and eliminate any malware that sneaks its way onto your PC.
Q3- What is need for secure passwords?
Ans 3-Secure password is needed in order to check the authenticity of the user.
Q 4- What is a worm?
Ans 4- It is a self-replicating program, which eats up the entire disk space or memory.
Q 5- What is Trojan horse?
Ans 5- It is a program that appears harmless but actually performs malicious functions such as deleting
or damaging files.
Q 6- What is a spyware?
Ans 6- Spyware is software which is installed on your computer to spy on your activities ans report this
data to people willing to pay for it.
Q 7-What is Adware?
Ans 7- Adware are the programs that deliver unwanted ads to your computer.
Q 8- What is Malware?
Ans 8- Malware is a general term used to refer to viruses, worms, spyware, adware etc.
Q 9- What is spamming?
Ans 9- Spamming refers to the sending of bulk-mail by an identified or unidentified source.
Q 10- What are preventive measures for computer security?
Ans 10- Preventive measures for computer security are-
a. Keep your system up-to-date.
b. Use caution when downloading files on the internet.
c. Be careful with email.
d. Disable cookies, if possible.
Q11- What are threats to a computer security?
Ans 11- Threats to a computer security-
a. Viruses
b. Worms
c. Trojans
d. Spyware
e. Adware
f. Spamming
g. PC Intrusion- i. Denial of Service ii. Sweeping iii. Password Guessing
h. Phishing
Q 12- What is password guessing?
Ans 12- Most hackers crack or guess passwords of system accounts and gain entry into remote
computer systems. And then they use it for causing damages in one or another form.
Q 13- What are damages caused by Spyware?
Ans 13- Spyware can do the following if left unchecked-
a. compromises your data, computing habits and identity.
b. alters PC settings.
Slow down your PC.
Q 14- What are damages caused by Adware?
Ans 14- Adyware can do the following if left unchecked-
a. Tracks information just like spyware.
b. Displays arrays of annoying advertising.
c. Slows down your PC.
Q 15- What are the types of Firewall?
Ans 15- Firewall are of two types-
a. Software Firewall b. Hardware Firewall.

HOTs
Q 1- What measures should you take to keep data secure?
Ans 1- 1. Making regular backups of files.
2. Protecting against viruses by running anti-virus software.
3. Using a system of strong password so that access to data is restricted.
4. Safe storage of important files stored on removable disks.
Q 2- What are the methods to get rid of spam?
Ans 2-
a. Sender filtering- i. Digital certificates. ii. Digital signatures.
b. Keyword filtering.
Q 3- What are the security and privacy concerns cookies creates?
Ans 3- Cookies help track user’s browsing sessions and load information faster, but create some security
and privacy concerns as well. These are-
a. Session data.
b. Tracking Information.
c. Public computers.
Q 4-How can a computer virus affect your computer?
Ans 4- Computer viruses are malicious programs that cause damage to data and files on a system.
Viruses can attack any part of a computer’s software such as boot block, operating system, system
areas, files etc.
Q 5-What are different types of threats to a computer?
Ans 5- Viruses, Worms, Trojans, Spyware, Adware, , Phishing , PC Intrusion- i. Denial of Service ii.
Sweeping iii. Password Guessing,
Q 6-What type damages can be caused by viruses to your computer?
Ans 6-Viruses can do the following if left unchecked-
a. Damage or delete files.
b. Slow down your computer.
c. Invade your email program.
Q 7- What are Malware?
Ans 7- Malware is a general term used to refer to viruses, worms, spyware, adware etc.
Q8- What do you understand by PC intrusion?
Ans 8- every PC connected to the internet is a potential target for hackers. Computers are under
constant attack from cyber vandals, this is called PC Intrusion.
Q 9- What is Denial-of-Services?
Ans 9- This type of attack eats up all the resources of a system and the system or application come to a
halt.
Q 10-What is sweeper attack?
Ans 10- It is a malicious program used by hackers. It sweeps i.e., deletes all the data from the system.
Q11-What is phishing?
Ans 11- In phishing, an imposter uses an authentic looking e-mail or website to trick recipients into
giving out sensitive personal information. Though it appears genuine, you may be taken to a fraudulent
site where all your sensitive information is obtained and later used for cyber-crimes and frauds.
Q12- How is pharming similar to and different from phishing?
Ans 12- In phishing, an imposter uses an authentic looking e-mail or website to trick recipients into
giving out sensitive personal information.
Pharming is an attack in which a hacker attempts to redirect a website’s traffic to another, bogus
website.
Q13- What is Authentication?
Ans 13- It is also termed as password-protection as the authorized user is asked to provide a valid
password, is he/she is able to do this, he/she will be considered as authentic user.
Q14- What is Authorization?
Ans 14-It is the process of asking the user to enter a legal log-in ID and password.
Q15- What is Eavesdropping?
Ans 15-It is a passive attack in which an attacker gains access to the communication-medium through
which some communication is taking place and then listens to the communication and gets information
about the content of the message. In short it is unauthorized monitoring of other people’s
communications is called Eavesdropping.

Nisha Verma
PGT(CS)
KV Amhat Sultanpur
&
HCL and Mind Tree Group

You might also like