Brief Overview of Python
1. What is Python Programming Language?
Ans:
a. Python is undoubtedly the most user-friendly general-purpose open source programming language.
b. One of the reasons it is growing in popularity is because it supports Rapid Application Development.
Which means it is much faster to build and implement systems using Python.
c. Its ambit covers web development, scientific computing, data mining and machine learning amongst
many others.
2. What is the basic history of Python Programming?
Ans: The following table lists the major events related to Python Programming Language:
a. Early 1990s:Guido van Rossum created Python Programming language at Centrum Wiskunde &
Informatica (CWI), a National Research Institute for Mathematics and Computer Science in the
Netherlands
b. 1995:Guido released several versions of the Python at the Corporation for National Research
Initiatives (CNRI) in Reston, Virginia
c. October 2000:Python 2.0 was released
d. 2001:Python Software Foundation (PSF) was formed
e. December 2008: Python 3.0 was released
3. How did Python get its name?
Ans: Guido van Rossum was looking for a suitable name for his programming language that was both
unique and mysterious. He came up with the name “Python”. He was influenced by the title of a BBC
comedy series from the 1970s which was called “Monty Python’s Flying Circus”.
Though “Monty Python’s Flying Circus” had nothing to do with programming, the word “Python” was
short, unique and contained the mystery element that Guido was looking for in his programming language.
4. List some of the features which make Python so popular:
Ans:
The following are some of the features which make
Python so popular:
a. Open Source Software: It is an open source software, thus has all the advantages of open source
software.
b. Easier to Code and Understand : When compared to C, C++, JAVA and other traditional programming
languages, programs written in Python are easier to code and understand.
c. Simple Constructs and Syntax: If you are a beginner, then Python is the perfect language for you to
start learning programming owing to its simple constructs and syntax.
d. General Purpose Programming Language: It is a general purpose programming language, so its
implementations are not restricted to a specific field alone.
e. Vast Library of Add-On Modules: It is suitable for advanced programming with vast library of add-
on modules that can be included as and when required.
f. Uses an Interpreter: Since it uses an interpreter, it gives immediate results and no compiling of source
file is required.
g. Rapid Application Development: It is much faster to build and implement systems using Python than
other programming languages. This is a major advantage for Python, since time is essential factor for
implementing systems.
h. Platform Independent Programming Language: Platform independent programming language
means, it can be used to develop programs that can run in all the well known operating systems available.
i. Object Oriented Programming: Python supports object oriented programming with concepts of
classes and objects. Not forgetting the OOPs factor (Object Orientated Programming Systems.)
j. Supports GUI Development: Graphical user interfaces also can be developed using Python.
k. Advanced Data Analysis: It supports advanced data analysis and ‘Big Data’ handling. Python decimal
data type supports precision to 17 digits. That is precisely 0.00000000000000001
l. Machine Learning Systems: Python helps develop machine learning systems that are able to
automatically learn and improve. Machine learning systems are implementations of Artificial
Intelligence (AI). This is a feature that assures us that Python programming languages will not fizzle
away, but may even find its place as a Fifth Generation Language (5 GL).
INSTALLING THE PYTHON INTERPRETER AND RUNNING YOUR FIRST PROGRAM
1. List the requirements to write and run Python programs:
Ans: To write and run Python program, we need to have Python interpreter installed in our computer.
2. List 2 way to install Python interpreter in the computer:
Ans:
a. Install the default Python Distribution (Python IDLE) from www.python.org/downloads
b. Install Anaconda Python distribution from www.anaconda.com/download
3. What is meant by Python IDLE?
Ans:
a. IDLE stands for Integrated Development Environment.
b. IDLE is the standard, most popular Python development environment.
c. IDLE is suitable for beginners, especially as the first step to learn Python programming.
d. IDLE lets us edit, run, browse and debug Python Programs from a single interface.
e. After the installation is completed the Python IDLE application will appear on the startup menu
(in case of Microsoft Windows).
f. Click on the Python 3 and choose the Python IDLE application, this will open the Python IDLE
window.
g. The >>> symbol is the Python IDLE prompt. The >>> prompt indicates Python is ready for your
instructions in the interactive mode.
4. What is Anaconda Python distribution and Jupyter Notebook?
Ans:
a. After learning the basics of Python programming users frequently move on to a more advanced IDE
(Integrated Development Environment) such as Jupyter Notebook that comes as a part of the Anaconda
Python distribution.
b. Jupyter Notebook is an open-source web application that allows you to create and share documents that
contain live code, equations, visualizations and narrative text.
5. List the 2 modes in which Python can run:
Ans: Python IDLE can be used in two ways, viz., interactive mode and script mode.
a. Interactive Mode, as the name suggests, allows us to interact with Python Shell and displays the result(s)
immediately.
b. Script mode let us create and edit python source file and save them for later use.
6. How do we work in the Interactive mode?
Ans:
a. In the Interactive mode we type a Python statement and the interpreter displays the result(s) immediately.
b. Example: If we type the commands on the prompt the results will appear immediately:
Command Result
>>> print("Good Book for Python")
Good Book for Python
7. What is the Script mode of Python?
Ans:
a. In script mode, we type Python program in a file and save them with file extension of .py and then use
the interpreter to execute the contents from the file.
b. Script mode helps us reuse the saved set of command anytime we require.
PYTHON VARIABLES AND DATA TYPES
1. What are meant by Variables?
Ans:
a) Variables are named memory locations.
b) A Variable’s value can change during program execution.
c) Python variables do not need explicit declaration to reserve memory space.
d) The declaration happens automatically when you assign a value to a variable.
e) Pictorial representation of variables stored in the memory:
The diagram shows two variables:
>>>Empno = 25 # An integer assignment
>>>Empname=”Sam” # A String assignment
f) Other Examples of declaring variables:
>>>age = 100 # An integer assignment
>>>kgs = 100.5 # A floating point
>>>name = "Json" # A string
>>>x = y = z= 10 #Multiple Assignment
>>>x,y,z = 10,20,"Json" #Multiple Assignment
2. List the Naming Rules for Python variables:
a) It should start with a letter or the underscore character
b) It cannot start with a number
c) It can only contain alpha-numeric characters and underscores, that is (A-z, 0-9, and _ )
d) Variable names are case-sensitive (name, Name and NAME are three different variables)
3. Explain the Components of a Variable:
Ans:
a) Every Variable has the following three components:
i) Name of the Variable: Name assigned to the memory address. It has to be unique in its scope.
ii) Data type: The kind of value that it can store.
a) Value stored in a variable: The actual value that the memory address holds.
b) Example to describe the components of a variable:
>>>speed = 20
#The variable speed is assigned value 20 and is of Integer data type.
4. Explain Number Data Type in Python.
Ans: Number data type is used to store Numeric Values. Number data type is immutable (Mutable and
Immutable Variables are explained later)
These are of three different types:
a) Integer and Long Data Type
i) Integers: Integers numbers are numbers without decimals.
Example: a = 10
ii) Long integer: By appending L to the value. It can be of any length only limited by
memory space.
Example: length = 99998L
iii) Boolean: True and False are Boolean values.
Example: connected = True
b) Float/floating point: Numbers with decimal point are called floating point numbers.
Example: height= 5.6
c) Complex: A complex number has two parts, 'real number part' and 'imaginary part'. It is in the form, x
+ yj. Where x and y are the real numbers and j is the imaginary unit.
Example: x = 5+2j
5. Explain None Data Type in Python.
Ans: None is used to define a null value or no value at all. It is not the same as 0, False, or an empty.
Example: Sal = None
PYTHON OPERATORS
1. What is meant by Operators?
Ans: Operators are the symbols which tell the Python interpreter to do some operations on the operands.
Example of some commonly used python operators are: +,*,>,=
2. What is meant by Operands?
Ans: Value and variables when used with operator are known as operands.
Example of operands :
>>>a=5 # a and 5 are operands, = is the operator
3. What is meant by Expression?
Ans: Operators when applied on operands form an expression.
Example of Expression:
>>>a=3+7
Note: In the above :
Operators are : =,+
Operands are : a,3,7
4. List the types of Operators used in Python:
Ans: Python has the following categories of operators:
i) Mathematical/Arithmetic Operators
ii) Relational Operators
iii) Logical Operators
iv) Assignment Operators
5. Explain Mathematical/Arithmetic Operators
Ans: Explanation of the Mathematical/Arithmetic Operators:
a) + Adds values on either side of the operator
>>>2+3
5
b) - Subtracts the right hand operand from then left hand operand
>>>3-2 1
3
c) * Multiplies values on either side of the operator
>>>3*2
6
d) / Divides then left hand operand by then right hand operand
>>>5/2
2.5
e) % Modulus - Divides left hand operand by right hand operand and returns remainder
>>>5/2
1
f) ** Performs exponential calculation on operators >
>>>2**3
8
g) // Integer Division- The division of operands where the result is the quotient in which the digits
after the decimal point is removed
>>>5//2
2
6. Explain Relational Operators
Ans: Explanation of the Relational Operators:
a) == Returns true if the operands are equal, else returns false
>>>a=7 #assigning
>>>a==7 #comparing
True
b) != Returns true if the operands are not equal, else returns false.
The <> operator can also be used to check inequality
>>>a=7 #assigning
>>>a!=7 #comparing
False
c) > Returns true if the value of left operand is greater than the value of right operand, else returns false
>>>10>8
True
d) < Returns true if the value of left operand is less than the value of right operand, else returns false
>>>8<10
True
e) >= Returns true if the value of left operand is greater than or equal to the value of right operand, else
returns false
>>>10>=10
True
f) <= Returns true if the value of left operand is less than or equal to the value of right operand, else
returns false
>>>8<=10
True
7. Explain Logical Operators
Ans: Explanation of the Logical Operators:
and Returns true if both the operands are true
>>>a=2
>>>(a>1) and (a<10)
True
or Returns true if anyone of the operands are true
>>>a=2
>>>(a>3) and (a<10)
True
not It returns the reverse logical state of its operand.
>>>not True
False
8. Explain Assignment Operators
Ans: Explanation of the Assignment Operators:
a) = Assigns values from right side operands to left side operand >>>a=2 Variable a
takes the value 2
b) += Adds values on either side of the operator and assign the result to left operand
>>>a=2
>>>a+=1
>>>print(a)
3
c) -= Subtracts the right hand operand from then left hand operand and assign the result to left operand
>>>a=2
>>>a-=1
>>>print(a)
1
d) *= Multiplies values on either side of the operator and assign the result to left operand
>>>a=2
>>>a*=3
>>>print(a)
6
e) /= Divides then left hand operand by then right hand operand and assign the result to left operand
>>>a=5
>>>a/=2
>>>print(a)
2.5
f) %= Modulus - Divides left hand operand by right hand operand and returns remainder and assign the
result to left operand
>>>a=5
>>>a%=2
>>>print(a)
1
g) **= Performs exponential calculation on operators and assign the result to left operand
>>>a=5
>>>a**=2
>>>print(a)
25
h) //= It performs Integer division on operators and assign value to the left operand
>>>a=5
>>>a//=2
>>>print(a)
2
9. Explain Membership Operators of Python:
Ans: Python also has membership operators, which test for membership in a sequence, such as strings,
lists, or tuples.
There are two membership operators explained below:
in: Returns true if it finds a variable in the sequence else returns false >>>a=[1,3,6,7]
>>>print(3 in a)
True
not in: Returns true if it does not finds a variable in the sequence else returns false
>>>a=[1,3,6,7]
>>>print(10 not in a)
True
10. List the Operator Precedence of Python:
Ans: The operator precedence in Python is listed in the following table.
It is in descending order; upper group has higher precedence than the lower ones.
Precedence of Operators in the same level will have precedence from left to right.
PYTHON INPUT AND OUTPUT OPERATIONS
1. Explain the function that helps to accept the Input from the user.
Ans:
a) In python, the input ( ) function helps getting input from the user.
b) Example for input():
>>>n1= input (“Enter your Name :”)
Enter data: David
#Will assign “David” to variable n1
c) Point to remember: The value received by the input() is always string data type , and it has to be
converted to integer or float if required by the programmer.
2. Explain the function that helps to display information to the user.
Ans:
a) The print() function prints the given data to the screen.
b) Print evaluates the expression before printing it on the monitor.
c) Print function print on newline every time it is used.
d) Print function can print more than one item on a single line, by using comma (,)
e) Example :
>>>a="Hello"
>>>print("Python")
Python
>>>print(a,"Python")
Hello Python
3. Explain Comment statements in Python:
Ans:
Definition: Comments are notes added to the code.
Need for Comments:
(a) Comments make the code more readable: As the program gets bigger, it becomes difficult to
read it, and to make out what it is doing by just looking at it.
(b) Any assumptions made can be stated
(c) Important details or decisions made in the program can be specified as an comment
(d) Comments are not mandatory but are a good programming habit
Symbol used for Comments: In Python, comment start with “#” symbol. Anything written after #
in a line is ignored by interpreter, i.e. it will not have any effect on the program.
A comment can appear on a line by itself or they can also be at the end of line.
Example :
# Calculating area of a square
>>>area = side **2
or
>>>area= side**2 #calculating area of a square
4. Explain Multiline Comments in Python:
Ans: For adding multi-line comment in a program, we can:
i) Place “#” in front of each line, or
ii) Use triple quoted string: The ‘‘‘signify the start of the comment and ’’’ signifies the end of the comment.
All that appears in between will not be interpreted.
Example of Multiline comment:
>>> ‘‘‘ Calculating area
of a rectangle ’’’
CONDITIONAL OPERATIONS IN PYTHON
1. What are Conditional Statements?
Ans:
a) Conditional Statement in Python performs different computations or actions depending on whether
a specific Boolean constraint evaluates to true or false.
b) Conditional statements are handled by if statements in Python.
2. Explain if statement:
Ans:
a) In Python, if statement is used for decision making.
b) It will run a block of code only when the if statement’s condition evaluates to True.
c) Syntax for if statement:
d) If the condition is True (i.e. satisfied), the statement(s) written after if (i.e. STATEMENT-BLOCK)
is executed.
e) Example using if statement:
>>>a=9
>>>if(a<10):
>>> b="a is less than 10"
>>> print(b)
a is less than 10
3. Explain else statement:
Ans:
a) else statement is used in case we want to execute a set of statements if the if statement becomes False.
b) Syntax for if statement:
c) If the condition is True (i.e. satisfied), the statement(s) written after if (i.e. STATEMENT-BLOCK) is
executed.
d) Example using if else statement:
>>>a=9
>>>if(a<10):
>>> b="a is less than 10"
>>>else:
>>> b="a is greater than 10"
>>>print(b)
a is less than 10
4. Explain ‘elif’ clause:
Ans:
a) elif is used in case we want to consider multiple/chained conditions.
b) Syntax for if statement:
c) Example using elif to implement multiple conditions:
>>>a=9
>>>if(a<10):
>>> b="a is less than 10"
>>>elif(a>10):
>>> b="a is greater than 10"
>>>else:
>>> b="a is equal to 10"
>>>print(b)
a is less than 10
d) If any of the conditions is evaluated to True, then the corresponding block of statement(s) are executed
and control moves out of “if statement”.
5. Explain Nested Condition:
Ans:
a) It is possible to have a condition within another condition. Such conditions are known as Nested
Condition.
b) Example of nested conditions:
>>>a=int(input("Enter any number between 1 to 10:")) # incase we enter 5
>>>if(a>=1): # first if statement
>>> if(a<=10): # second if statement
>>> print("You have entered number:",a)
>>> else:
>>> print("The number you have entered is not between 1 to 10")
You have entered number:5
ITERATION/LOOPING CONSTRUCT IN PYTHON
1. What is meant by iteration or looping construct?
Ans:
a) When a set of statements are repeated until a certain condition is fulfilled it is known as iteration or looping.
b) Iteration helps us re-run parts of your program without having to duplicate the code.
c) In python looping is done using ‘for loop’ and ‘while loop’.
2. What is the basic structure of a looping construct?
Ans:
a) Initialize the counter variable
b) Testing the counter variable against a stopping condition
c) Executing the body of the loop (the part to be repeated)
d) Update(increasing or decreasing ) the value of the counter variable.
2. List the two constructs that Python provides to implement looping:
Ans: There are two construst that are used for looping in Python.
a. while statement
b. for statement
3. Explain the while statement with the help of examples.
Ans:
a) while statement keep on executing the statements in its block until the given condition is true.
b) When the condition becomes false then the while statement will exit the loop.
c) Syntax of while is:
while condition: # check if the condition is true/false
Statements Block
[else: # else is optional part of while
Statements Block]
d) Example of While loop:
#Program to display 1 to 10 using while loop
a=1
while(a<=10):
print("a=",a)
a=a+1
print("On Exiting the Loop the value of a is :",a)
Output:
a= 1
a= 2
a= 3
a= 4
a= 5
a= 6
a= 7
a= 8
a= 9
a= 10
On Exiting the Loop the value of a is : 11
6. Explain the for statement with the help of examples.
Ans:
a) The ‘for’ loop is used to process the items in a given range or sequence one-by-one till the end of the
sequence/list.
b) When the condition becomes false then the while statement will exit the loop.
c) Syntax of for is:
for <variable> in <List/Range>: # variable takes values one-by-one till the end of the sequence
Statement Block inside the for loop
[else: # Optional Block
Statement Block inside the else]
Example : Program to display a list , one item at a time and the sum of all the numbers in the list:
sum=0
for x in [2,5,3,8,44,8]:
print(x)
sum=sum+x
print("The sum is :",sum)
Output:
2
5
3
8
44
8
The sum is : 70
7. Explain the use of range( ) function using examples.
Ans:
a) range() function generates a list of values in the specified range.
b) Syntax of range() is:
range(start, stop, [step]) # step is optional
Please Note: the ‘stop’ is not inclusive that is the reason only 1 to 10 is printed.
c) Example 2 : Program to print the even number between 2 to 10 using range() along with for loop:
for x in range(2,11,2): # the step value is specified as 2
print(x)
Output:
2
4
6
8
10
10. What are nested loops?
Ans:
a) A loop that contains another loop is called a nested loop.
b) Example:
for x in range(1,5,1):
for y in range(1,4,1):
print("x=",x," y=",y)
print("--------------------")
Output:
x= 1 y= 1
x= 1 y= 2
x= 1 y= 3
--------------------
x= 2 y= 1
x= 2 y= 2
x= 2 y= 3
--------------------
x= 3 y= 1
x= 3 y= 2
x= 3 y= 3
--------------------
x= 4 y= 1
x= 4 y= 2
x= 4 y= 3
HANDLING LISTS IN PYTHON
1. What are Python Lists?
Ans:
a. A list is a data type of Python that can store a ordered sequence of values belonging to any type.
b. Python lists are defined by square brackets [ ].
c. Values in the list are mutable, they can be modified.
d. Example of some type of Lists in Python:
>>>Score = [ ] #Empty list i.e. list with no element
>>>timezone = [“CSD”, “PSD”, “ISD”]
#List of 3 string elements
>>>Points = [3, 2, 3, 4] #List of 4 integer elements.
>>>notes = [“go to work”, 100, 40]
List with different types of elements.
Graphical representation of the notes list.
2. Explain different ways in which Lists can be created.
Ans:
a. Empty List a list will no items:
>>>score = [ ] #or
>>>score = list( )
b. Nested List is a list that can have elements in it, which itself is a list. It is a list within a list.
i) Example>>>score=[5,3,[4,6,9],7]
ii) Commands to display the contents of a nested list:
>>> score[0] # output 5
>>> score[2] #output [4,6,9]
>>>score[2][1] #output 4
c. List created using other Lists: Lists can also be created using other
lists.
Example :
>>>score=[5,7,9]
>>>game=score
>>>print(game) # output [5,7,9]
d. List from Sequences: List can also be created from sequences.
Example :
>>>book=list("best python")
>>>print(book)
Output : ['b', 'e', 's', 't', ' ', 'p', 'y', 't', 'h', 'o', 'n']
3. Difference between List data type and String data types:
Ans:
a) List work similar to String in many ways but the difference is that List are mutable and Strings are
immutable.
b) String data type only contains strings; but List can contain any type of data.
6. Explain the Joining operation that can be performed on list.
Ans: The + operator can be used to join lists as shown below:
Example:
>>>score1=[3,2,3]
>>>score2=[12,7,8]
>>>finalscore=score1+score2
>>>print(finalscore)
Output: [3,2,3,12,7,8]
6. Explain the Replicating operation that can be performed on list.
Ans: The * operator can be used to replicate lists as shown below:
Example:
>>>score=[12,7,8]
>>>print(score*2)
Output: [12,7,8, 12,7,8]
7. Explain the comparison operation that can be performed on list.
Ans: The * operator can be used to replicate lists as shown below:
>>>score1=[1,2,3]
>>>score2=[1,2,3]
>>>print(score1==score2)
Output: True
8. Explain the Slicing operation that can be performed on list.
Ans: Slicing of List is similar to slicing of string:
Example:
>>>score=[1,2,3,4,5,6]
>>>print(score[1:4])
Output: [2,3,4]
9. Explain the built-in functions of List.
Ans: The following inbuilt functions and methods help to manipulate the python lists.
a) len() : Returns the length of the list
>>> myList=[1,2,5,1,4]
>>> len(myList)
5
b) index() Returns the index of the first match
>>> myList=[1,2,5,1,4]
>>> myList.index(5)
2
c) append() Appends One item to the end of the list
>>> myList=[1,2,5,1,4]
>>> myList.append(5)
>>> myList
[1, 2, 5, 1, 4, 5]
d) extend() Appends One or more item(s) to the end of the list
>>> myList=[1,2,5,1,4]
>>> M=[12,14,15]
>>> myList.extend(M)
>>> myList
[1, 2, 5, 1, 4, 12, 14, 15]
e) insert() Inserts one element at any position that you choose.
>>> myList=['p','y','t','o','n']
>>> myList.insert(3,'h')
>>> myList
['p', 'y', 't', 'h', 'o', 'n']
f) pop() It pops out or removes the specified element from the list and also returns it.
>>>L=['p','y','t','h','o','n']
>>> A=L.pop(3)
>>> L
['p', 'y', 't', 'o', 'n']
>>> A
'h'
g) remove() It removes the first occurrence of give element from the list
>>> myList=['p','y','t','h','o','n']
>>> myList.remove('t')
>>> myList
['p', 'y', 'h', 'o', 'n']
h) clear() It deletes all the content of the list and makes it an Empty list.
>>> L =['p','y','t','h','o','n']
>>> L.clear()
>>> L
[]
i) count() It returns the number of occurrences of a specified element.
>>> myList=[1,2,5,1,5,7]
>>> myList.count(5)
2
j) reverse() It reverses all the elements of the list in-place.
>>> L =['p','y','t','h','o','n']
>>> L.reverse()
>>> L
['n', 'o', 'h', 't', 'y', 'p']
k) sort() It sorts the elements of the list in-place. The default is ascending order. If descending
order is required then use the following:
sort(reverse=True)
>>> myList=[1, 2, 5, 1, 4, 12, 14, 15]
>>> myList.sort()
>>> myList
[1, 1, 2, 4, 5, 12, 14, 15]
l) min() It returns the smallest value
>>>score1=[1,2,3]
>>>print(min(score1))
1
m) max() It returns the largest value
>>>score1=[1,2,3]
>>>print(max(score1))
3
n) count() It returns the count of items
>>>score1=[1,2,3]
>>>print(count(score1))
3
o) sum() It returns the sum of all the numeric values
>>>score1=[1,2,3]
>>>print(sum(score1))
6
p) sorted() It return a new sorted list
>>>score1=[4,2,1,3]
>>>a=sorted(score1)
>>>print(a)
[1,2,3,4]
HANDLING DICTIONARIES IN PYTHON
1. What are Dictionaries in python?
Ans :
a. Dictionaries are similar to Associative Arrays.
b. It has keys with some values associated to those keys.
c. Just as lists have index numbers that are used to associate values, in dictionaries keys are used.
d. Curly brackets { } mark the beginning and end of dictionaries.
e. In dictionaries the keys are immutable but the values are mutable.
f. They are unordered set of elements. The stored order and printed order may not be same.
2. Give examples of dictionaries.
Ans:
a. D={ } # creates an Empty Dictionary
b. Sal={‘Sam’:2000,’Kate’:3000,’Dan’:5000}
c. Emp={‘Eno’:101,’Ename’:’Matthew’,’Dept’:’Sales’}
3. How to access the values from a dictionary?
Ans: The following code shows how to access the values from a dictionary:
>>>Student={'Rno':101,'name':'Matthew','Sec':'Sci A'}
>>>print(Student['Rno'])
Output: 101
>>>Student={'Rno':101,'Sname':'Matthew','Sec':'Sci A'}
>>>print(Student['Rno'],Student['Sec'])
Output: 101 Sci A
4. How to display the content of dictionary using For loop?
Ans:
Example :
Student={'Rno':101,'Sname':'Matthew','Sec':'Sci A'}
for i in Student:
print(i,":",Student[i])
Output:
Rno : 101
Sname : Matthew
Sec : Sci A
5. How to add a new value:pair of element to an existing dictionary?
Ans: Example
Student={'Rno':101,'Sname':'Matthew','Sec':'Sci A'}
Student['Mark']=70 # Adding a new Value:pair
print(Student)
Output: {'Rno': 101, 'Sname': 'Matthew', 'Sec': 'Sci A', 'Mark': 70}
6. How to Edit/Update an element of an existing dictionary?
Ans: Example
Student={'Rno':101,'Sname':'Matthew','Sec':'Sci A'}
Student['Sec']='Sci B' # Edit the value part
print(Student)
Output: {'Rno': 101, 'Sname': 'Matthew', 'Sec': 'Sci B'}
7. How to delete value pairs from the dictionary?
Ans: Example1: Using del statement
Student={'Rno': 101, 'Sname': 'Matthew', 'Sec': 'Sci A', 'Mark': 70}
del Student['Sec']
print(Student)
Output: {'Rno': 101, 'Sname': 'Matthew', 'Mark': 70}
Example2: Using pop() method
Student={'Rno': 101, 'Sname': 'Matthew', 'Sec': 'Sci A', 'Mark': 70}
Student.pop('Sec')
print(Student)
Output: {'Rno': 101, 'Sname': 'Matthew', 'Mark': 70}
8. How to use ‘in’ and ‘not in’ with dictionaries?
Ans: In the dictionaries ‘in’ and ‘not in’ are used to check if the specified key is present in the dictionary or not.
Example 1:
Student={'Rno': 101, 'Sname': 'Matthew', 'Sec': 'Sci A', 'Mark': 70}
'Sname' in Student
Output: True
Example 2:
Student={'Rno': 101, 'Sname': 'Matthew', 'Sec': 'Sci A', 'Mark': 70}
'Sname' not in Student
Output: False
9. List the functions used with dictionaries:
Ans: The following are the functions used with dictionaries:
a) len() It returns the number of elements
>>>Student={'Rno': 101, 'Sname': 'Matthew', 'Sec': 'Sci A', 'Mark': 70}
>>>len(Student)
Output:4
b) clear() It removes all the elements and makes it an empty dictionary
>>>Student={'Rno': 101, 'Sname': 'Matthew', 'Sec': 'Sci A', 'Mark': 70}
>>>Student.clear()
print(Student)
Output: { }
c) get() It returns the value stored in the given key
>>>Student={'Rno': 101, 'Sname': 'Matthew', 'Sec': 'Sci A', 'Mark': 70}
>>>print(Student.get('Sname'))
Output: Matthew
d) items() Returns the dictionary in the form of a sequence along with both keys and values
>>>Student={'Rno': 101, 'Sname': 'Matthew', 'Sec': 'Sci A', 'Mark': 70}
>>>mySt=Student.items()
>>>for i in mySt:
print(i)
Output:
('Rno', 101)
('Sname', 'Matthew')
('Sec', 'Sci A')
('Mark', 70)
e) keys() Returns all the keys of the dictionary in the form of a sequence
>>>Student={'Rno': 101, 'Sname': 'Matthew', 'Sec': 'Sci A', 'Mark': 70}
>>>mySt=Student.keys()
>>>for i in mySt:
print(i)
Output:
Rno
Sname
Sec
Mark
f) values() Returns all the values of the dictionary in the form of a sequence
>>>Student={'Rno': 101, 'Sname': 'Matthew', 'Sec': 'Sci A', 'Mark': 70}
>>>mySt=Student.values()
>>>for i in mySt:
print(i)
Output:
101
Matthew
Sci A
70
g) update() It merges two dictionaries
>>>Student={'Rno': 101, 'Sname': 'Matthew', 'Sec': 'Sci A'}
>>>Marks={'Rno': 101,'test1':98,'test2':79}
>>>Student.update(Marks)
>>>print(Student)