Python All Questions Note Micro
Python All Questions Note Micro
1. Python is Free – Python can be implemented without purchase of any software or there is no
licensing issues.
2. Portable – python code can be developed on any hardware or software platform and can be
easily transferred to any other hardware or software platform.
3. Extensible – The complete python language is written in C language and it’s original code is also
available, hence any one can download it, and can add new features to it, thus python language can
be extended to support new features.
4. Database Interaction – Python can be connected with any std database application to read and
write data.
6. Scalable - python code size can be changed at any time and can also handle small as well as large
size data
8. Powerful language - python library comes with huge library of useful modules that supports
programmer to perform ▪ Network communication ▪ Text processing ▪ Regular expression matching ▪
Low-level operations of Operating system
Easy to learn – as it uses few keywords, simple structure and simple syntax.
Easy to read – as it uses many English keywords hence easy to read o Easy to maintain – due to
structured programming, python code is easy to maintain.
Collection of std library – to performs different operations it provides many std lib to make the
code eay. o Interactive mode - supports interactive way of testing and debugging of python
code.
Portable – it can run on any hardware or OS platform.
Extendable – new modules can be easily added to existing code so that it can be extended.
Database Interaction – Python can be connected with any std database application to read and
write data.
GUI Programming – Graphics interfaces can also be created using python.
Scalable – python code size can be changed at any time and can also handle small as well as
large size data
1
Q.2 Define Variables
- Such data element can be stored using variable so that it can be processed any time.
- For which variable, how much memory is required is decided on the basis of data type of that
variable.
- as per the datatype or type of value stored in variable, interpreter decides and allocates memory
to variable.
- As oppose to C,C++,Java languages, Python does not needs explicit declaration for variable & to
reserve memory space.
- Based on the data type of a variable, Therefore, by assigning different data types to variables, you
can store integers, decimals or characters in these variables.
- While creating variable, a valid variable name must be assigned as per variable naming
conventions.
1) Static assignment
2) Dynamic assignment
1) Static assignment – in this, value to any variable can be assigned directly in prog code using =
operator as:
VariableName=value
e.g.
ctr=100 9
2
print("Type of variable a=",type(c),"value in a=",c)
Output –
('Type of variable a=', , 'value in a=', 12)
('Type of variable a=', < class 'float'>, 'value in a=', 15.67)
('Type of variable a=', < class 'str'>, 'value in a=', 'A')
('Type of variable a=', < class 'str'>, 'value in a=', 'Abc Xyz')
3
Q.3 Explain String Operators
4
ii. Contents of memory locations.
- Under this category, two operators are supported as:
i) is – returns true if both variables points same memory location else returns false.
ii) is not - returns false if both variables points same memory location else returns true. suppose
there are two variables with values like
a=10
b=10
if we check these two as :
a is b → it will return true
a is not b→ it will return false
- Operators helps to compose an expression in prog code like:
o A=10+20
- All operators also have their pre-defined precedence and always follows the precedence rule like
o When + (Addition) and * (Multiplication) operators are used in same expression then, *
will be evaluated first & then + like
o A=10+5*3
▪ Value in A variable will be 25.
- Operator precedence can be changed using parenthesis ( ) as:
o A=(10+5)*3
▪ In above case first, + will be evaluated & then *, hence Value in A variable will be 45.
5
Q.4 Explain Data Types in Python
- Python as programming language supports data types using which variable can be created.
- Python provides following standard data types which decides How which value to be stored?
1)
Numeric – It
6
i) keys() – returns only the keys used to create dictionary items.
ii) values() – returns only the values in dictionary.
iii) clear() – deletes all the items in the dictionary.
-len() function can be used to count number of items present in dictionary as:
print(len([Link]())
e.g
a={1.8:200,7:'Abc','X':45.7}
print("All Keys and values=",a)
print("Total Number of Items",len([Link]()))
print("All Keys are=",([Link]()))
print("All values are=",[Link]())
3. Boolean – This data type provides two built-in values True and False. It can be used as:
a=True print(type(a))
note: T and F of values must be capitals, if used small, will show error.
4. Set - Set datatype in python represents the unordered collection of the data type.
- It is iterable, mutable (can modify after creation), and has unique elements.
- In set, the order of the elements is undefined; it may return the changed sequence of the element.
- values in set can be of same or different types: -
The set can be created in one of the following ways:
i) by using a built-in function set(), as:
setName=set((value1,value2,value3………))
a=set(('Abc',300,35.77)) print("All the Elements in Set=",a)
output
All the Elements in Set= {35.77, 300, 'Abc'}
ii) group of elements is passed in the curly braces and separated by the comma. It can contain
various types of values. a={44,'Abc',89.09,"Xyz",100} print("All the Elements in Set=",a)
output
All the Elements in Set= {100, 'Abc', 44, 89.09, 'Xyz'}
3. Sequence Type – Sequence data type represents collection of data elements. Python
supports following sequence subtypes
7
s1='FYBCA'
s2="SYBCA"
s3='''TYBCA'''
print("String-1=",s1)
print("String-2=",s2)
print("String-3=",s3)
- As like java & other languages, string indexing in python also starts with zero.
- This indexing helps in performing different string manipulations like
a) Extracting single char – a single character at given position can be extracted as:
StringName[Index]
e.g.
s1='Hello India'
print("Sub String=",s1[3])
b) Extracting sub-string – to extract set of characters, start index and number of characters to be
specified as:
StringName[startIndex:NumberofChars]
s1='Hello India'
print("Sub String=",s1[0:3])
c) Repeating string – same string can be repeated using * operator as
StringName * int
Eg
s1='Hello'
print("Repeated String=",s1*3)
Output – Repeated String= HelloHelloHello
output
Current Data= ['Abc', 1001, 78.99, 'A']
- On list following different operations are supported:
8
Q.5 Explain Looping Statement in Python with Example
- Looping is the programming technique by which block of code can be repeatedly executed for fixed
number of time. - python supports following looping statements.
1) while statement
2) for statement
1) While statement – This loop statement is used to design general loop codes.
- The Python while loop allows a part of the code to be executed until the given condition returns
false.
- It is also known as a pre-tested loop.
- with while statement, expression or condition is given which will be tested repeatedly.
2) for statement –
- for statement in python is used to repeat execution of given code block.
- As oppose to other languages like C, C++, etc it is used to iterate over a sequence (list, tuple, string)
or other iterable objects.
- Iterating over a sequence is called traversal.
9
- for loop statement can be used to in following different forms
i) using range() – this function provides list of fixed range values to execute the loop as:
for <var>in range([start],stop,[step]):
---- loop body--- -- -
range() functions uses following different parameters:
i) start – it is optional parameter and it is used as initializing value.
- If not given, by default zero is considered.
ii) stop – it is terminating value which decide when loop to be stopped. Loop executed till stop-1
value.
iii) step – it decides the incrementing value of loop. It can be either positive or negative value.
- Forward order loop
– Positive value.
- Reverse Order loop - negative value
- It is optional parameter, if not given, by default it is incremented by 1.
e.g.1
for i in range(3):
print(i)
output –
0
1
2
e.g.3
for i in range(1,10,2):
print(i) output - 1
3
5
7
9
10
Q.6 Explain Input and Output Statements in Python with Example
input Statements – the programming statement which is useful to get input from user during prog
execution time is called input statement.
- For this python supports input() function as: VariableName=input(“Message”)
Sname=input(“Enter Student Name=”)
- The input taken using input statement is by default is of string type, hence if numerical
value is taken as input and if arithmetic operations to be performed on it, then it must be type
casted as :
- E.g. num1=int(input(“Enter a number=”))
- Num2=float(input(“Enter a number=”))
e.g
import math a=int(input("Enter a number="))
print ("Sq Root=", [Link](a))
Output Statements - The statement in programming code which completes the job to print or write
output on any output location.
- Python uses print( ) lib function to give output at specified output location.
- Python code can use following output destinations :-
1. Std Output Device
2. File
1. Std Output Device – print( ) by default writes output on std output device as:
print(“Hello)
- This Std output can be given in following different forms as:-
i. printing dummy message
print(‘Any message’)
print(“Any message”)
ii. printing with escape sequence characters
- as like C, python also allows to use following escape sequence chars
\n – new line
\t – tab space
print(‘Any message \t Any message \n Any Message’)
iii. printing defined output or variable output
print(VariableName)
a=10 print(a)
iii. printing combined output – undefined and defined output can be printed, for this comma (,) can
be used as separator
a=10
print(‘Value of a=’,a)
iv. Printing with format character –As like C lang, python also allows to use format chars such as
%d – for integer
%f – for float
%c – for char
As
11
print(‘ any message %char’ %VariableName)
A=10
print(‘int value=%d’ %A)
v. printing selected number of digits in real value
n=234.6754327
print('Float value %0.2f' %n)
vi. printing without new line
- By default print( ) gives new line after writing the output on output screen.
- To avoid new line, the “end” parameter can be used as
print(‘output’,end=’ ‘)
prints with space print(‘output’,end=’\t’)
print with tab space print(101,end=’\t’)
print(‘Abc’)
output
101 Abc
12
Q.7 What is Inheritance? Explain Hierarchical Inheritance with
Example
Syntax
1. class derived-class(base class):
2. <class-suite>
A class can inherit multiple classes by mentioning all of them inside the bracket. Consider the
following syntax.
Example 1
1. class Animal:
2. def speak(self):
3. print("Animal Speaking")
4. #child class Dog inherits the base class Animal
5. class Dog(Animal):
6. def bark(self):
7. print("dog barking")
8. d = Dog()
9. [Link]()
10. [Link]()
Output:
dog barking
Animal Speaking
Explain Hierarchical Inheritance with Example
In the world of object-oriented programming, inheritance is a powerful
concept that allows one class to inherit the properties and behaviors of
13
another. Hierarchical Inheritance is a specific form of inheritance in Python
that involves a single base class with multiple derived classes. This article
explores the concept of Hierarchical Inheritance, its syntax, advantages,
and provides three examples to illustrate its application in Python.
def speak(self):
pass
class Dog(Animal):
def speak(self):
return f"{[Link]} says Woof!"
class Cat(Animal):
def speak(self):
return f"{[Link]} says Meow!"
# Usage
dog = Dog("Buddy")
cat = Cat("Whiskers")
print([Link]())
print([Link]())
Output
Buddy says Woof!
Whiskers says Meow!
14
Q.8 Explain Date Time Module
The datetime module in Python is part of the standard library and provides classes and functions for
working with dates and times. The datetime module is especially useful for tasks such as:
Parsing dates and times from strings o Formatting dates and times into strings
Doing arithmetic with dates and times (e.g., finding the difference between two dates)
Extracting components of dates and times (e.g., the year, month, day, hour, minute, second,
etc.)
Representing dates and times in a time zone-aware or time zone-naive manner
The main classes in the datetime module are date, time, and datetime. The date class represents a
date (year, month, day), the time class represents a time of day (hours, minutes, seconds,
microseconds), and the datetime class represents a date and time together. The datetime module
also includes a timedelta class, which represents a duration or the difference between two dates or
times.
With the datetime module, you can easily perform operations on dates and times, and it is widely
used in various applications such as database operations, scheduling tasks, working with time-series
data, etc.
The datetime module in Python provides classes and functions for working with dates and times.
These classes and functions allow you to perform a wide range of operations, from simple tasks such
as formatting dates and times to more complex ones such as performing arithmetic with dates and
times or working with time zones.
Some of the main classes and functions provided by the datetime module
are:
1. datetime class: The datetime class represents a date and time as a single object. It has attributes
for the year, month, day, hour, minute, second, and microsecond. You can create a datetime object
by passing the year, month, day, hour, minute, second, and microsecond as arguments to the
constructor, or by using the [Link]() method to get the current date and time.
2. date class: The date class represents a date (year, month, day) without a time of day. You can
create a date object by passing the year, month, and day as arguments to the constructor, or by
using the [Link]() method to get the current date.
3. time class: The time class represents a time of day (hours, minutes, seconds, and microseconds)
without a date. You can create a time object by passing the hours, minutes, seconds, and
microseconds as arguments to the constructor.
4. timedelta class: The timedelta class represents a duration or the difference between two dates or
times. You can use timedelta objects to perform arithmetic with dates and times, such as finding the
difference between two datetime objects, or adding or subtracting a timedelta from a datetime
object to get a new datetime.
5. tzinfo class: The tzinfo class is used to represent time zones in the datetime module. You can use
tzinfo objects to create time zone-aware datetime objects, which allow you to work with dates and
times in different time zones.
6. Formatting and parsing functions: The datetime module provides functions for formatting and
parsing dates and times as strings, such as strftime and strptime. These functions allow you to
control the format of dates and times when they are converted to or from strings.
15
Q.9 Explain Polymorphism with Suitable Example
What is polymorphism? Polymorphism refers to having multiple forms. Polymorphism is a programming term that refers to
the use of the same function name, but with different signatures, for multiple types.
Example of in-built polymorphic functions:
1. # Python program for demonstrating the in-built poly-morphic functions
2.
3. # len() function is used for a string 4. print (len("Javatpoint"))
5.
6. # len() function is used for a list
7. print (len([110, 210, 130, 321]))
Output:
10
4
Polymorphism with Class Methods
Below is an example of how Python can use different types of classes in the same way. For loops that iterate through
multiple objects are created. Next, call the methods without caring about what class each object belongs to. These
methods are assumed to exist in every class.
Example:
1. class xyz():
2. def websites(self):
3. print("Javatpoint is a website out of many availabe on net.")
4.
5. def topic(self):
6. print("Python is out of many topics about technology on Javatpoint.")
7.
8. def type(self):
9. print("Javatpoint is an developed website.")
10.
[Link] PQR():
12. def websites(self):
13. print("Pinkvilla is a website out of many availabe on net. .")
14.
15. def topic(self):
16. print("Celebrities is out of many topics.")
17.
18. def type(self):
19. print("pinkvilla is a developing website.")
20.
21.obj_jtp = xyz()
22. obj_pvl = PQR()
[Link] domain in (obj_jtp, obj_pvl):
24. [Link]()
25. [Link]()
26. [Link]()
Output:
Javatpoint is a website out of many availabe on net.
Python is out of many topics about technology on Javatpoint.
Javatpoint is an developed website.
Pinkvilla is a website out of many availabe on net.
Celebrities is out of many topics.
Pinkvilla is a developing website.
16
Q.10 Explain Class in Detail
In any programming language, a class is a user-defined plan or blueprint using which objects or
instances of the class are created. You may wonder why we need classes in programming. We can
create something like a variable or a structure, store what we want, and use it.
A class can have its attributes - variables and functions with pre-stored values and
functionalities.
Example situation: If we want to store the data of different age groups of children and their
details in an orphanage :
We cannot just create a list and keep on storing the ages and names of the children without any
organization.
Creating multiple lists for multiple age groups - one list to store ages, one for names, another to
match - becomes complex and leads to ambiguity.
Syntax:
#Definition of a class
1. class class_name:
3. #variables
4. #functions
8. Attributes are the variables owned by the class (declared inside the class) that the created objects
can use.
9. Methods are the functions owned by the class (defined inside the class) that the created objects
can use.
10. The created objects using the dot (.) operator uses these attributes and methods of a class.
Example program:
1. class Employee:
3. #Methods
17
Q.11 Explain Packages with Example
A package is considered a collection of tools that allows the programmers to initiate the code. A
Python package acts as a user-variable interface for any source code. This feature allows a Python
package to work at a defined time for any functional script in the runtime.
Example:
2. import math
3. # printing a statement
Output:
Packages
1. A Package consists of the __init__.py file for each user-oriented script. However, the same does
not apply to the modules in runtime for any script specified to the users.
2. A module is a file that contains a Python script in runtime for the code specified to the users. A
package also modifies the user interpreted code in such a manner that it gets easily operated in the
runtime.
18
Q.12 How to Import MySQL for Python
Navigate your command line to the location of PIP, and type the following:
demo_mysql_test.py:
import [Link]
If the above code was executed with no errors, "MySQL Connector" is installed and ready to be
used.
19
Q.13 Explain Tkinter Module
Python provides the standard library Tkinter for creating the graphical user interface for desktop
based applications.
An empty Tkinter top-level window can be created by using the following steps.
3. Add the widgets like labels, buttons, frames, etc. to the window.
4. Call the main event loop so that the actions can take place on the user's computer screen.
Example
Tkinter widgets
There are various widgets like button, canvas, checkbutton, entry, etc. that are used to build the
python GUI applications.
20
Q.14 How to Pass Query in MySQL in Detail
I'm trying to pass a list of data into a MySQL database but for the life of me I can't figure
out what I'm doing wrong, even after scouring the internet for a solution I decided to
post a question here.
I can connect to the database no problem, and sending simple queries like 'SHOW
TABLES' work like a charm, but when trying to pass the contents of a list into MySQL just
doesn't work. this code here is as close as i got to it working, but I get an error because
of an email address.
the error is: "You have an error in your SQL syntax... near '@[Link], x123, False ..."
In Python, passing a query to a MySQL database is primarily handled through the cursor object of a
database connector (like mysql-connector-python ). The process involves establishing a
connection, creating a cursor, and using the execute() method.
[Link](query, params)
21
Q.15Write Steps for Connecting with Databases
In this section, we will discuss the steps to connect the python application to the database.
There are the following steps to connect a python application to our database.
1. Import [Link] module
2. Create the connection object. 3. Create the cursor object
4. Execute the query
To create a connection between the MySQL database and the python application, the
connect () method of [Link] module is used.
Pass the database details like HostName, username, and the database password in the
method call. The method returns the connection object.
The syntax to use the connect () is given below.
22
Q.16 Explain the Concept of GUI in Python
A GUI (graphical user interface) is a system of interactive visual components for computer
software.
A GUI displays objects that convey information, and represent actions that can be taken by the
user. The objects change color, size, or visibility when the user interacts with them.
The GUI was first developed at Xerox PARC by Alan Kay, Douglas Engelbart, and a group of other
researchers in 1981.
Later, Apple introduced the Lisa computer with a GUI on January 19, 1983.
These graphical elements are sometimes enhanced with sounds, or visual effects like
transparency and drop shadows. Using these objects, a user can use the computer without having to
know commands.
Below is a picture of the Windows 7 desktop and an example of a GUI operating system. In
this example, you could use a mouse to move a pointer and click a program icon to start a program.
Elements of a GUI?
To make a GUI as user-friendly as possible, there are different elements and objects that the user
uses to interact with the software. Below is a list of each of these with a brief description.
23
Button - A graphical representation of a button that performs an action in a program when pressed
Dialog box - A type of window that displays additional information, and asks a user for input.
Menu - List of commands or choices offered to the user through the menu bar.
Ribbon - Replacement for the file menu and toolbar that groups programs activities together.
Tab - Clickable area at the top of a window that shows another page or area.
Toolbar - Row of buttons, often near the top of an application window that controls software
functions.
Window - Rectangular section of the computer's display that shows the program currently being
used.
Benefits of GUI?
Unlike a command-line operating system or CUI, like Unix or MS-DOS, GUI operating systems are
easier to learn and use because commands do not need to be memorized.
Microsoft Windows
Chrome OS
3. GNOME
4. KDE
24
Q.17 Explain Sets in Detail
This is one of the important Python Data Structures. A Python set is a slightly different concept from
a list or a tuple. A set, in Python, is just like the mathematical set. It does not hold duplicate values
and is unordered. However, it is not immutable, unlike a tuple.
Let’s first declare a set. Use curly braces for the same.
>>> myset={3,1,2}
>>> myset
Output
{1, 2, 3}
As you can see, it rearranged the elements in an ascending order.
Since a set is unordered, there is no way we can use indexing to access or delete its elements. Then,
to perform operations on it, Python provides us with a list of functions and methods like discard(),
pop(), clear(), remove(), add(), and more. Functions like len() and max() also apply on sets.
>>> basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
>>> print(basket) # show that duplicates have been removed
{'orange', 'banana', 'pear', 'apple'}
>>> 'orange' in basket # fast membership testing
True
>>> 'crabgrass' in basket False >>> # Demonstrate set operations on unique letters from two
words ...
>>> a = set('abracadabra')
>>> b = set('alacazam')
>>> a # unique letters in a
{'a', 'r', 'b', 'c', 'd'}
>>> a - b # letters in a but not in b
{'r', 'd', 'b'}
>>> a | b # letters in a or b or both
{'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}
>>> a & b # letters in both a and b
{'a', 'c'} >>> a ^ b # letters in a or b but not both
{'r', 'd', 'b', 'm', 'z', 'l'}
Similarly to list comprehensions, set comprehensions are also supported:
>>> a = {x for x in 'abracadabra' if x not in 'abc'}
>>> a
{'r', 'd'}
25
Q.18 What is Exception Handling? Explain in Detail
The try-expect statement If the Python program contains suspicious code that may throw the
exception, we must place that code in the try block. The try block must be followed with the except
statement, which contains a block of code that will be executed if there is some exception in the try
block.
Syntax
1. try:
2. #block of code
3.
4. except Exception1:
5. #block of code
6.
7. except Exception2:
8. #block of code
9.
10. #other code Consider the following example.
Example 1
1. try:
2. a = int(input("Enter a:"))
3. b = int(input("Enter b:"))
4. c = a/b
5. except:
6. print("Can't divide with zero")
Output:
Enter a:10
Enter b:0
Can't divide with zero
We can also use the else statement with the try-except statement in which, we can place the code
which will be executed in the scenario if no exception occurs in the try block. The syntax to use the
else statement with the try-except statement is given below.
1. try:
2. #block of code
3.
4. except Exception1:
5. #block of code
26
6.
7. else:
8. #this code executes if no except block is executed
Output:
Enter a:10
Enter b:0
can't divide by zero
27
Q.19 Explain List in Detail
Python List
A list in Python is a heterogeneous container for items. This would remind you of an array in C++,
but since Python does not support arrays, we have Python Lists.
1. How to Declare Python List?
To use a list, you must declare it first. Do this using square brackets and separate values with
commas.
>>> languages=['C++','Python','Scratch']
You can put any kind of value in a list. This can be a string, a Tuple, a Boolean, or even a list itself
>>> list1=[1,[2,3],(4,5),False,'No']
Note that here, we put different kinds of values in the list. Hence, a list is (or can be) heterogeneous.
2. How to Access Python List?
a. Accessing an entire list
To access an entire list, all you need to do is to type its name in the shell.
>>> list1
Output
[1, [2, 3], (4, 5), False, „No‟+
b. Accessing a single item from the list
To get just one item from the list, you must use its index. However, remember that indexing begins
at 0. Let’s first take a look at the two kinds of indexing.
Positive Indexing– As you can guess, positive indexing begins at 0 for the leftmost/first item, and
then traverses right.
>>> list1[3]
Output
False
Negative Indexing– Contrary to positive indexing, negative indexing begins at -1 for the
rightmost/last item, and then traverses left. To get the same item form list1 by negative indexing, we
use the index -2.
>>> type(list1[-2])
Output
<class „bool‟>
It is also worth noting that the index can’t be a float, it has to be an integer.
>>> list1[1.0]
Output
Traceback (most recent call last):File “”, line 1, in list1*1.0+
TypeError: list indices must be integers or slices, not float
If you face any doubt in a Python list or Python Data Structure, please comment.
3. Slicing a Python List
Sometimes, you may not want an entire list or a single item, but a number of items from it. Here, the
slicing operator [:] comes into play.
Suppose we want items second through fourth from list ‘list1’. We write the following code for this.
>>> list1[1:4]
Output
28
[[2, 3], (4, 5), False]
Here, we wanted the items from [2,3] to False. The indices for these boundary items are 1 and 3
respectively. But if the ending index is n, then it prints items till index n-1. Hence, we gave it an
ending index of 4 here.
We can use negative indexing in the slicing operator too. Let’s see how.
>>> list1[:-2]
Output
[1, [2, 3], (4, 5)]
Here, -2 is the index for the tuple (4,5).
4. A list is mutable
Mutability is the ability to be mutated, to be changed. A list is mutable, so it is possible to reassign
and delete individual items as well.
>>> languages
Output
*„C++‟, „Python‟, „Scratch‟+
>>> languages[2]='Java'
>>> language
Output
*„C++‟, „Python‟, „Java‟+
Of how to delete an item, we will see in section d.
5. How to Delete a Python List?
Like anything else in Python, it is possible to delete a list.
To delete an entire list, use the del keyword with the name of the list.
>>> list1
Output
Traceback (most recent call last):File “”, line 1, in list1 NameError:
name „list1‟ is not defined
But to delete a single item or a slice, you need its index/indices.
>>> del languages[2]
>>> languages
Output
*„C++‟, „Python‟+
Let’s delete a slice now.
>>> del languages[1:]
>>> languages
Output
*„C++‟+
6. Reassigning a List in Python
You can either reassign a single item, a slice, or an entire list. Let’s take a new list and then reassign
on it.
>>> list1=[1,2,3,4,5,6,7,8]
More on Lists
The list data type has some more methods. Here are all of the methods of list objects:
[Link](x)
Add an item to the end of the list. Equivalent to a[len(a):] = [x].
29
[Link](iterable)
Extend the list by appending all the items from the iterable. Equivalent to a[len(a):] = iterable.
[Link](i, x)
Insert an item at a given position. The first argument is the index of the element before which to
insert, so [Link](0, x) inserts at the front of the list, and [Link](len(a), x) is equivalent to
[Link](x).
[Link](x)
Remove the first item from the list whose value is equal to x. It raises a ValueError if there is no such
item.
[Link]([i])
Remove the item at the given position in the list, and return it. If no index is specified, [Link]()
removes and returns the last item in the list. (The square brackets around the i in the method
signature denote that the parameter is optional, not that you should type square brackets at that
position. You will see this notation frequently in the Python Library Reference.)
[Link]()
Remove all items from the list. Equivalent to del a[:].
[Link](x[, start[, end]])
Return zero-based index in the list of the first item whose value is equal to x. Raises a ValueError if
there is no such item.
The optional arguments start and end are interpreted as in the slice notation and are used to limit
the search to a particular subsequence of the list. The returned index is computed relative to the
beginning of the full sequence rather than the start argument.
[Link](x)
Return the number of times x appears in the list.
[Link](*, key=None, reverse=False)
Sort the items of the list in place (the arguments can be used for sort customization, see sorted() for
their explanation).
[Link]()
Reverse the elements of the list in place.
[Link]()
Return a shallow copy of the list. Equivalent to a[:]
30
Q.20 Explain Concept of Dictionaries in Python
Python Dictionaries
Finally, we will take a look at Python dictionaries. Think of a real-life dictionary. What is it used for?
It holds word-meaning pairs. Likewise, a Python dictionary holds key-value pairs. However, you may
not use an unhashable item as a key
To declare a Python dictionary, we use curly braces. But since it has key-value pairs instead of single
values, this differentiates a dictionary from a set.
>>> mydict={1:2,2:4,3:6}
>>> mydict
Output
{1: 2, 2: 4, 3: 6}
To access pairs from a Python dictionary, we use their keys as indices. For example, let’s try
accessing the value 4.
>>> mydict[2]
Output
False
31
The dict() constructor builds dictionaries directly from sequences of key-value pairs:
>>>
In addition, dict comprehensions can be used to create dictionaries from arbitrary key and value
expressions:
>>>
When the keys are simple strings, it is sometimes easier to specify pairs using keyword arguments:
>>>
32
Q.21 Write a Program to Check Prime Number or Not
To check if a number is prime, you must verify it is a positive integer greater than 1 and has
no divisors other than 1 and itself. An efficient way to do this is by checking for factors
only up to the square root () of the number.
import math
def is_prime(n):
# Numbers less than or equal to 1 are not prime
if n <= 1:
return False
# Check for factors from 2 up to the square root of n
for i in range(2, int([Link](n)) + 1):
if n % i == 0:
return False
return True
Key Logic: If a number has a factor larger than its square root, it must also have a
corresponding factor smaller than the square root.
Try it online: You can run this code in the Programiz Online Python Compiler
33
Q.22 Explain Math Module in Python
In this article, we are discussing Math Module in Python. We can easily calculate many mathematical
calculations in Python using the Math module. Mathematical calculations may occasionally be
required when dealing with specific fiscal or rigorous scientific tasks. Python has a math module that
can handle these complex calculations. The functions in the math module can perform simple
mathematical calculations like addition (+) and subtraction (-) and advanced mathematical
calculations like trigonometric operations and logarithmic operations.
This tutorial teaches us about applying the math module from fundamentals to more advanced
concepts with the support of easy examples to understand the concepts fully. We have included the
list of all built-in functions defined in this module for better understanding.
What is Math Module in Python?
Python has a built-in math module. It is a standard module, so we do not need to install it
separately. We only must import it into the program we want to use. We can import the module,
like any other module of Python, using import math to implement the functions to perform
mathematical operations.
Since the source code of this module is in the C language, it provides access to the functionalities of
the underlying C library. Here we have given some basic examples of the Math module in Python.
The examples are written below –
Program Code 1:
Here we give an example of a math module in Python for calculating the square root of a number.
The code is given below –
1. # This program will show the calculation of square root using the math module
2. # importing the math module
3. import math
4. print([Link]( 9 ))
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the
output is given below –
3.0
This Python module does not accept complex data types. The more complicated equivalent is the
cmath module.
We can, for example, calculate all trigonometric ratios for any given angle using the builtin functions
in the math module. We must provide angles in radians to these trigonometric functions (sin, cos,
tan, etc.). However, we are accustomed to measuring angles in terms of degrees. The math module
provides two methods to convert angles from radians to degrees and vice versa.
Math Module:
Program code
We use a program code to know all the functions of the Math module in Python. The code is given
below –
1. import math
2. dir(math
Output:
34
Now we compile the above code in Python, and after successful compilation, we run it. Then the
output is given below –
['__doc__',
'__loader__',
'__name__',
'__package__',
'__spec__',
'acos',
'acosh',
'asin',
'asinh',
'atan',
'atan2',
'atanh',
'ceil',
'comb',
'copysign',
'cos',
'cosh',
'degrees',
'dist',
'e',
'erf',
'erfc',
'exp',
'expm1',
'fabs',
'factorial',
'floor',
'fmod',
'frexp',
'fsum',
'gamma',
'gcd',
'hypot',
'inf',
'isclose',
'isfinite', 'isinf'
, 'isnan',
'isqrt',
'ldexp',
'lgamma',
'log',
'log10',
'log1p',
'log2',
'modf',
'nan',
'perm',
'pi',
'pow',
'prod',
'radians',
'remainder',
'sin',
'sinh',
'sqrt',
'tan',
'tanh',
'tau',
'trunc']
35
Q.23 Explain Getting Input from User in Python
The Entry widget is used to provide the single line text-box to the user to accept a value from the
user.
We can use the Entry widget to accept the text strings from the user.
It can only be used for one line of text from the user.
Syntax
36
Example
#Input Demo
top = Tk()
[Link]("400x250")
[Link]('MainPage')
[Link]()
Output
37
Q.24 Describe Python Interpreter
You can start Python from Unix, DOS, or any other system that provides you a commandline
interpreter or shell window. Enter python the command line.
- As python is high level interpreted language, it’s execution requires Python interpreter.
- Python code first converted into intermediate code i.e. byte code (as in java language).
- Once python code is converted into byte code, it is saved in a file with .pyc extension.
- Python interpreter takes raw-text source code and executes each statement.
Directly python statement can be given to interpreter – any executable statement can be
given to python interpreter prompt >>> as
e.g
or
Start Python Idle → go to file menu → New→ type the python code-→ File menu → Save → give
filename In Run menu → Select Run Module or Press F5
38