0% found this document useful (0 votes)
0 views38 pages

Python All Questions Note Micro

The document outlines key features of Python, including its free and portable nature, extensibility, and support for database interaction and GUI programming. It explains variables, their types, and how to assign values, as well as string operators and various data types such as numeric, dictionary, boolean, set, and sequence types. Additionally, it covers looping statements, input and output operations in Python, providing examples for clarity.

Uploaded by

dipakkhillare040
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views38 pages

Python All Questions Note Micro

The document outlines key features of Python, including its free and portable nature, extensibility, and support for database interaction and GUI programming. It explains variables, their types, and how to assign values, as well as string operators and various data types such as numeric, dictionary, boolean, set, and sequence types. Additionally, it covers looping statements, input and output operations in Python, providing examples for clarity.

Uploaded by

dipakkhillare040
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Q.

1 Explain Features of Python

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.

5. GUI Programming – Graphics interfaces can also be created using python.

6. Scalable - python code size can be changed at any time and can also handle small as well as large
size data

7. C/C++ Embedding – Python code can be embedded into C or C++ applications.

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

- The other features of python can be enlisted as:

 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

- Python program may needs data element for it’s execution.

- Such data element can be stored using variable so that it can be processed any time.

- Variable is reserved memory location to hold/store required value.

- 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.

- A python prog may uses single or multiple variables.

- 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.

- Value to any variable can be assigned in two ways:

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

Prog codea=12 b=15.67

c='A' d='Abc Xyz'

print("Type of variable a=",type(a),"value in a=",a)

print("Type of variable a=",type(b),"value in a=",b)

2
print("Type of variable a=",type(c),"value in a=",c)

print("Type of variable a=",type(d),"value in a=",d)

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')

2) Dynamic assignment – value to variable cn be assigned dynamically at runtime using input()


method as:
VariableName=input(“Dummy Msg”) num=input(“Enter a number=”)
- Based on input value, datatype of variable will be decided.
- Only one input is possible using one input() statement, hence prog can use any number of
input statements.
e.g.
a=input("Enter a value==")
print("Type of variable a=",type(a),"value in a=",a)
a=input("Enter a value==")
print("Type of variable a=",type(a),"value in a=",a)
a=input("Enter a value==")
print("Type of variable a=",type(a),"value in a=",a)
a=input("Enter a value==")
print("Type of variable a=",type(a),"value in a=",a)
Output
Enter a value=="Abc"
('Type of variable a=', < class 'str'>, 'value in a=', 'Abc')
Enter a value==35.7
('Type of variable a=', < class 'float'>, 'value in a=', 35.7)
Enter a value=='A'
('Type of variable a=', < class 'str'>, 'value in a=', 'A')
Enter a value==12
('Type of variable a=', < class 'int'>, 'value in a=', 12)

3
Q.3 Explain String Operators

- It is one type of token used by any programming language.


- Operator is one special character or symbol associated with pre-defined operation and when used
performs it’s pre-defined operations.
- Operator to complete it’s operation always uses operand which any value or variable.
- Operators as one of the basic/fundamental entity of programming language helps to apply
required logic in prog code.
- python supports following different types of operators –
1) Arithmetic operators – these are used to perform arithmetic/mathematical operations on given
operands. These operators are like:
+ →addition - →subtraction
* → Multiplication / → Division
% → modulo
/ remainder
** → Exponent
// → floor division
2) Relational or Comparison – These operators are used to check the relation between two
operands by comparison.
 These operators returns Boolean value true or false after comparison. These operators are:
== → equality != → Not Equal
<= → Less than or equal >=→ Greater than or equal
< → less than > → Greater than
These operators are mostly used to compose conditional statements in prog code.
3) Assignment – these operators are used to assign right-hand side value to lefthand side operand as
= → simple assignment += →
Addition/increase and then assignment
-= → subtraction/decrease then assignment
*= → multiply & then assignment
/= →Division & then assignment
%= → remainder assignment
**= → Exponent and then assignment
//= → Floor Division
e.g.
4) Bitwise – these operators are used to operate on low level or binary values.
5) Membership – These operators helps to find given data element is present or is member of given
sequence. Python supports following membership operators:-
i) IN – It returns TRUE if given entity is present in sequence else FALSE.
ii) NOT IN - It returns FALSE if given entity is present in sequence else TRUE.
6) Identity operators – These operators are used to compare:
i. Memory locations &

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

represents numeric value in following different forms


[Link] – numeric value without decimal point.
e.g. a=100
b. Complex number – it combination multiple real or floating numbers. In this, the number
must be suffixed by j or J as
a=1.3+3.4j
c. Float – it is a single numeric value with decimal point as
e.g. a=12.34
2). Dictionary – It is an associative array i.e. collection of unordered set of data elements.
Each data element is also must be associated with key. Multiple value-key pair must be separated by
comma and all values must be enclosed in curly braces as:
<Dict Name> =,Key:Value,Key:value,……..-
e.g. values={1:100,5:250,3:120}
- in same dictionary, key can be of same type or different types.
e.g. values=,1:’Abc’,5.5:250,’X’:12.90-
- In this, values can be duplicate, but keys must be unique
- if key is repeated, then previous value of same key is replaced by new value.
- Dictionary supports following useful methods

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

i) Strings – It represents sequence of character or collection of bytes in quotation marks.


- Python allows, string to be enclosed in single, double or triple quotes.
e.g.

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

ii) List – It represents “list” class type of python language.


- Python list is similar to array of C, C++ and java like languages i.e. to store collection of data
elements.
- But it also can contain multiple elements of same as well as different data types.
- To store data items in list, items to be separated by comma and enclosed in brackets []
e.g.
data=["Abc",1001,78.99,'A']
print ("Current Data=",data)

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.

- The syntax is given below.


While :<exp>:
---- loop body---
e.g. program to display Hello message 5 times
i=1
while i<=5:
print('Hello')
i=i+1

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

Inheritance is an important aspect of the object-oriented paradigm. Inheritance provides code


reusability to the program because we can use an existing class to create a new class instead of
creating it from scratch. In inheritance, the child class acquires the properties and can access all the
data members and functions defined in the parent class. A child class can also provide its specific
implementation to the functions of the parent class. In this section of the tutorial, we will discuss
inheritance in detail. In python, a derived class can inherit base class by just mentioning the base in
the bracket after the derived class name. Consider the following syntax to inherit a base class into
the derived class.

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.

What is Hierarchical Inheritance?


Hierarchical Inheritance is a type of inheritance in which a single base class
is inherited by multiple derived classes. In this scenario, each derived class
shares common attributes and methods from the same base class, forming
a hierarchy of classes.
class BaseClass:
# Base class attributes and methods
class DerivedClass1(BaseClass):
# Additional attributes and methods specific to
DerivedClass1
class DerivedClass2(BaseClass):
# Additional attributes and methods specific to
DerivedClass2
class Animal:
def __init__(self, name):
[Link] = name

def speak(self):
pass

class Dog(Animal):
def speak(self):
return f&quot;{[Link]} says Woof!&quot;

class Cat(Animal):
def speak(self):
return f&quot;{[Link]} says Meow!&quot;

# Usage
dog = Dog(&quot;Buddy&quot;)
cat = Cat(&quot;Whiskers&quot;)
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:

2. #body of the class

3. #variables

4. #functions

5. #body of the functions

6. class" is a keyword in python libraries.

7. A class name must be capitalized.

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:

2. #Attributes like name, id

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.

Let us consider the following example demonstrating the package in Python.

Example:

1. # importing the package

2. import math

3. # printing a statement

4. print("We have imported the math package")

Output:

We have imported the math package

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.

Creating and Accessing Packages


1. Create a Directory: create a folder that will act as the package root.
2. Add Modules: Inside the directory, add Python files (modules). Each
module can contain related functions or classes.
3. Add __init__.py: add an __init__.py file to the directory. This file tells
Python that the directory should be treated as a package.
4. Create Sub-packages (Optional): One can organize code further by
creating subdirectories with their own __init__.py files.
5. Import Modules: Modules or functions inside the package can be
imported using dot notation, for example:

18
Q.12 How to Import MySQL for Python

 Python needs a MySQL driver to access the MySQL database.

 In this tutorial we will use the driver "MySQL Connector".

 We recommend that you use PIP to install "MySQL Connector".

 PIP is most likely already installed in your Python environment.

Navigate your command line to the location of PIP, and type the following:

 Now you have downloaded and installed a MySQL driver.

Test MySQL Connector


 To test if the installation was successful, or if you already have "MySQL Connector" installed,
create a Python page with the following content:

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.

1. import the Tkinter module.

2. Create the main application window.

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.

1. Basic Query Execution


To run a simple SQL statement, you pass the query as a string to
the execute() method. 1.1.4, 1.2.5
 Step-by-step process:
1. Establish Connection: Use [Link]() with your host, user,
password, and database. 1.1.1
2. Create Cursor: Call [Link]() to interact with the database. 1.2.7
3. Execute: Run [Link]("YOUR SQL QUERY") . 1.2.7
4. Fetch Results: For SELECT queries,
use [Link]() or [Link]() . 1.4.5

2. Passing Parameters (Parameterized Queries)


Never use f-strings or string formatting (like f"SELECT... WHERE id={user_id}" ) to
pass variables into queries, as this leaves your database vulnerable to SQL
Injection. 1.5.1, 1.5.2 Instead, use placeholders ( %s ).
 Syntax: [Link](query, params)
 Placeholders: Use %s as a marker in your SQL string. 1.1.5
 Params: Pass the actual values as a tuple or dictionary as the second
argument. 1.1.3, 1.5.1

query = "SELECT * FROM employees WHERE hire_date BETWEEN %s AND %s"

params = (date_start, date_end) # Values passed as a tuple

[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.

Consider the following example.


Example
import [Link]
#Create the connection object
myconn = [Link](host = "localhost", user = "root", passwd = "google")
#printing the connection object
print(myconn)
Output:
<[Link] object at 0x7fb142edd780>
 Here, we must notice that we can specify the database name in the connect () method if we want
to connect to a specific database.
Example
import [Link]
#Create the connection object
myconn = [Link](host = "localhost", user = "root",passwd = "google",
database = "mydb")
#printing the connection object
print(myconn)
Output:
<[Link] object at 0x7ff64aa3d7b8>

22
Q.16 Explain the Concept of GUI in Python

Graphical User Interfaces

 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.

 GUI is often pronounced by saying each letter (G-U-I or gee-you-eye).

 It sometimes is also pronounced as "gooey."

 A GUI includes GUI objects, like icons, cursors, and buttons.

 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.

 Icon - Small graphical representation of a program, features, or file.

 Menu - List of commands or choices offered to the user through the menu bar.

 Menu bar - Thin, horizontal bar containing the labels of menus.

 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?

 A GUI is considered to be more user-friendly than a textbased command-line interface, such as


MS-DOS, or the shell of Unixlike operating systems

 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.

Examples of a GUI operating system

 Microsoft Windows

 Apple System 7 and macOS

 Chrome OS

 Linux variants like Ubuntu using a GUI interface.

Examples of a GUI interface

1. Apple macOS 2. Microsoft Windows

3. GNOME

4. KDE

5. Any Microsoft program, including Word, Excel, and Outlook.

6. Internet browsers, such as Internet Explorer, Chrome, and Firefox.

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

Consider the following program.


Example 2
1. try:
2. a = int(input("Enter a:"))
3. b = int(input("Enter b:"))
4. c = a/b
5. print("a/b = %d"%c)
6. # Using Exception with except statement. If we print(Exception) it will return exception class
7. except Exception:
8. print("can't divide by zero")
9. print(Exception) 10. else:
11. print("Hi I am else block")

Output:
Enter a:10
Enter b:0
can't divide by zero

The except statement with no exception


Python provides the flexibility not to specify the name of exception with the exception statement.
Consider the following example.
Example
1. try:
2. a = int(input("Enter a:"))
3. b = int(input("Enter b:"))
4. c = a/b;
5. print("a/b = %d"%c)
6. except:
7. print("can't divide by zero")
8. else:
9. print("Hi I am else block")

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

>>> tel = {'jack': 4098, 'sape': 4139}

>>> tel['guido'] = 4127

>>> tel {'jack': 4098, 'sape': 4139, 'guido': 4127}

>>> tel['jack'] 4098

>>> del tel['sape']

>>> tel['irv'] = 4127

>>> tel {'jack': 4098, 'guido': 4127, 'irv': 4127}

>>> list(tel) ['jack', 'guido', 'irv']

>>> sorted(tel) ['guido', 'irv', 'jack']

>>> 'guido' in tel True

>>> 'jack' not in tel

False

31
The dict() constructor builds dictionaries directly from sequences of key-value pairs:

>>>

>>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])

{'sape': 4139, 'guido': 4127, 'jack': 4098}

In addition, dict comprehensions can be used to create dictionaries from arbitrary key and value
expressions:

>>>

>>> {x: x**2 for x in (2, 4, 6)}

{2: 4, 4: 16, 6: 36}

When the keys are simple strings, it is sometimes easier to specify pairs using keyword arguments:
>>>

>>> dict(sape=4139, guido=4127, jack=4098)

{'sape': 4139, 'guido': 4127, 'jack': 4098}

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.

Below are implementations in Python and C:

Python Program (Optimized)


This program uses a function to check primality by iterating from 2 up to

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

# Taking user input


try:
num = int(input("Enter a number: "))
if is_prime(num):
print(f"{num} is a prime number.")
else:
print(f"{num} is not a prime number.")
except ValueError:
print("Please enter a valid integer.")

 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

Modulo Check If n % i == 0, the number has a factor and is not prime.

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.

 For multiple lines of text, we must use the text widget.

The syntax to use the Entry widget is given below.

Syntax

w = Entry (parent, options

A list of possible options is given below.

36
Example

#Input Demo

from tkinter import *

top = Tk()

[Link]("400x250")

[Link]('MainPage')

name = Label(top, text = "Name").place(x = 30,y = 50)

email = Label(top, text = "Email").place(x = 30, y = 90)

password = Label(top, text = "Password").place(x = 30, y = 130)

sbmitbtn = Button(top, text = "Submit",activebackground = "pink"

activeforeground = "blue").place(x = 30, y = 170)

e1 = Entry(top).place(x = 80, y = 50)

e2 = Entry(top).place(x = 80, y = 90)

e3 = Entry(top).place(x = 95, y = 130)

[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.

Start coding right away in the interactive interpreter.

- As python is high level interpreted language, it’s execution requires Python interpreter.

- An interpreter is a kind of program that executes other programs.

- Python code first converted into intermediate code i.e. byte code (as in java language).

- This intermediate code is translated in machine language code for execution.

- 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.

- Python statements can be executed in following ways

 Directly python statement can be given to interpreter – any executable statement can be
given to python interpreter prompt >>> as

e.g

>>> print (“Hello”)

or

>>> print (‘Hello’)

 Python statement can be saved in file and then executed by interpreter.

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

You might also like