Professional Documents
Culture Documents
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.
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: ')
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
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.
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
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! ")
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")
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)
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)
**
***
****
*****
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 −
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)
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-
countdown=10
while countdown > 0:
print(countdown, end=’ ‘)
countdown – 1
print(“Finally.”)
Ans Check your progress
Q32 Write a python program to take input of three of 3 angles and display whether they form a
triangle or not.
Q37 Explain the purpose of loop structures in a programming language. Describe the syntax and
semantics of one loop structure provided by Python.
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’
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)
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?
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
(i) [4,4,4,4]
E Rewrite the following after removing all syntax errors. Underline each correction
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)
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.
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 .
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?
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″)
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
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)
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'])
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)
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.
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.
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.
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.
Ans: Answer:
•Controlling Redundancy.
•Integrity can be enforced.
•Inconsistency can be avoided.
•Data can be shared.
•Standard can be enforced.
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.
Ans: Structured Query Language is a database tool which is used to create and access
database to support software application.
Ans: The table is a collection of record and its information at a single view.
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.
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.
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.
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.
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.
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.
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.
Ans: A Unique key constraint uniquely identified each record in the database. This provides
uniqueness for the column or set of columns.
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.
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.
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;
Ans: Ans. Yes using the following syntax we can do this SELECT column_name AS new_name
FROM table_ name;
Ans: Ans. Order of SQL SELECT clauses is: SELECT, FROM, WHERE, GROUP BY, HAVING, ORDER
BY. Only the SELECT and FROM clause are mandatory
Ans: Ans. SQL comments can be put by two consecutive hyphens (–).
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.
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