Python 2 Marks (NEP & CBCS) Questions with Answers (Important)
2 Marks (Important)
1. What is python? (2019)
Python is a high-level, general-purpose programming language. It is dynamically typed and garbage-collected. It supports multiple programming paradigms, including structured (particularly procedural), object-oriented and functional programming.
2. Define scalar and non scalar objects?
a scalar object is an object that has a single value. Examples of scalar objects include integers, floats, strings, and Booleans. A non-scalar object is an object that has multiple values. Examples of non-scalar objects include lists, tuples, dictionaries, and sets.
3. Define tuples?
a tuple is a collection of objects that are ordered and immutable. This means that the order of the elements in a tuple cannot be changed, and the elements of a tuple cannot be modified once the tuple is created.
4. Write an examples for mutable and immutable types?
Mutable types
– Lists
– Dictionaries
– Sets
Immutable types
– Strings
– Tuples
– Numbers
– Booleans
5. What is higher order function programming?
a higher-order function is a function that takes one or more functions as arguments or returns a function as a result. Some examples of built-in higher-order functions in Python are map(), filter(), and reduce().
6. Define testing & Debugging?
Testing is the process of finding bugs and errors in software. It is done by executing the software with different inputs and checking for the expected outputs. There are many different types of tests, such as unit tests, integration tests, and system tests.
Debugging is the process of fixing bugs found during testing. It is done by identifying the cause of the bug and then making changes to the code to fix it. There are many different
debugging techniques, such as print statements, breakpoints, and debuggers.
7. What you mean by Inheritance?
The basic idea of inheritance is that one class can inherit the properties and methods of another class. The class that inherits from another class is called the derived class, and the class that is inherited from is called the base class.
8. What is Exception?
An exception is an event that occurs during the execution of a program that disrupts the normal flow of the programs instructions.
9. What is regular expression?
A regular expression (RegEx) in Python is a sequence of characters that defines a search pattern. It can be used to search for a specific pattern of text within a larger string of text. The Python “re” module provides regular expression support.
10. What is database?
A database in Python is a collection of data that is organized and stored so that it can be easily accessed, managed, and updated. Python provides a variety of modules for
working with databases, including:
– The sqlite3 module for working with SQLite databases
– The mysql module for working with MySQL databases
– The postgresql module for working with PostgreSQL databases
– The oracle module for working with Oracle databases
11. Name data types in python with examples.(2021)
– Numeric data types: Integers, Floating point numbers and Complex numbers.
– String data type
– Sequence data types: List,Tuple,Range and Dictionary.
– Boolean data type.
– NoneType.
12. Define list and dictionaries with example.
A list is a data structure that stores a collection of ordered data. The elements of a list can be of any data type, and they can be accessed by their index. Lists are created using square brackets [].
example :
list1 = [1, 2, 3, 4, 5]
A dictionary is a data structure that stores a collection of key-value pairs. The keys are
unique, and the values can be of any data type. Dictionaries are created using curly
braces {}.
example:
dict1 = {“John”: 30, “Mary”: 25, “Peter”: 20}
13. Mention the task of software quality assurance group.
– Plan and execute tests
– Identify and fix bugs
– Ensuring that the software meets its requirements
– Improving the quality of the software
14. What is assertion?
An assertion in Python is a statement that checks the validity of an assumption made by the code. If the assumption is false, an assertion error is raised. Assertions are used to debug code and to ensure that the code is working as expected.
syntax :
assert expression, message
example :
x = 10
assert x > 0, “The value of x must be greater than 0.”
15. Define testing. Mention types of testing.
Testing is the process of evaluating software to find errors, gaps, or missing requirements. It is an important part of the software development process, and it helps to ensure that the software is of high quality and meets the needs of its users.
Types of testing
– Unit testing
– System testing
– Acceptance testing
– Performance testing
– Security testing
– Usability testing
16. Name any two Tkinter widgets with example.
1.Button :
Ex : button=tk.Button(root, text=”This is example to create a button”)
2.Label:
Ex : label=tk.Label(root, text=”This is example to create a label”)
17. What is Cursor?
A cursor in Python is an object that is used to iterate over the results of a database query. It provides a way to access the rows of data one at a time.
The cursor() method of the Connection class is used to create a cursor object.
18. Define commit and rollback.
In Python, commit and rollback are two commands used to manage transactions in a database.
– Commit permanently saves the changes made in a transaction.
– Rollback cancels the changes made in a transaction and returns the database to its previous state.
19. Who developed python?(2022)
Guido van Rossum developed Python in the late 1980s and early 1990s while working at
CWI in the Netherlands as a part of the Amoeba operating system project. He released
the first version of Python in 1991.
Here are some of the reasons why Python is a popular programming language:
– It is easy to learn and use.
– It is powerful and versatile.
– It has a large and active community.
– It is free and open-source.
– It is portable and runs on many different platforms.
20. How to accept user input? Give example.
To accept user input in Python, we can use the input() function. The input() function takes a prompt as its argument and returns the user’s input as a string.
example:
name = input(“Enter your name: “)
print(“Hello, {}!”.format(name))
21. How to declare single and multiline comments in python?
1.Single-line comments can be declared using the hash (#) symbol. Anything after the hash symbol is ignored by the Python interpreter.
For example:
# This is a single-line comment
print(“Hello, world!”)
2.Multiline comments can be declared using triple quotes (”’ or “””). Anything between
the triple quotes is ignored by the Python interpreter.
For example:
”’
This is a multiline comment
that spans multiple lines
”’
print(“Hello, world!”)
22. What is a list? Give an example.
A list is a data structure in Python that can store an ordered collection of elements. The elements of a list can be of any data type, including numbers, strings, and other lists. Lists are created using square brackets [].
example:
numbers = [1, 2, 3, 4, 5]
23. Sate any two differences between tuple and list.
Sr. No. Key List Tuple
1 Type List is mutable. Tuple is immutable.
2 Iteration List iteration is slower and is time consuming. Tuple iteration is faster.
3 Appropriate for List is useful for insertion and deletion operations. Tuple is useful for read-only operations like accessing elements.
4 Memory Consumption List consumes more memory. Tuples consumes less memory.
5 Methods List provides many in-built methods. Tuples have less in-built methods.
6 Error prone List operations are more
error prone. Tuples operations are safe.
24. What is __init__()?
The __init__() method in Python is a special method that is called when an object is created. It is used to initialize the object’s attributes. The __init__() method is always called with no arguments, but it can take any number of arguments.
class Dog:
def __init__(self, name, breed):
self.name = name
self.breed = breed
dog = Dog(“Spot”, “Labrador Retriever”)
print(dog.name)
print(dog.breed)
25. What is inheritance? Give syntax to derive a child class from a parent class.
class ParentClass:
# methods and attributes of the parent class
class ChildClass(ParentClass):
# methods and attributes of the child class
26. What is lambda function? Give example.
A lambda function in Python is a small, anonymous function. It is often used as a shorthand for creating simple functions.
syntax :
lambda arguments: expression
example :
add_two_numbers = lambda x, y: x + y
print(add_two_numbers(1, 2))# 3
27. Write the use of any two functions used in GUI layout Management.
pack(): The pack() function is used to pack widgets into a container. The widgets are arranged in a single row or column, depending on the available space.
place(): The place() function is used to place widgets in a specific location on the screen. The widgets are not arranged in any particular order, and each widget is placed independently.
grid(): The grid() function is used to arrange widgets in a grid. The widgets are arranged in rows and columns, and each widget is assigned a unique location in the grid.
28. Define variable? Give example.(2020)
A variable in Python is a named location in memory that can store a value. Variables are used to store data that we need to use later in our program.
Example :
var_name = value name = “Bard”
29. What are ranges?
In Python, a range is a sequence of numbers. It is used to iterate over a set of numbers.The range() function is used to create a range.
The syntax for the range() function is as follows:
range(start, stop, step)
example:
range(0, 11)
This range will include the numbers 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, and 10.
example :
range(2, 11, 2)
This range will include the numbers 2, 4, 6, 8, and 10.
30. Define IDE’s of python.
An IDE (Integrated Development Environment) is a software application that provides a comprehensive set of tools for writing, running, and debugging code. IDEs typically include a code editor, a debugger, a compiler or interpreter, and a project manager.
31. Define single query.
A single query in Python is a single SELECT statement that is executed against a database. A SELECT statement is used to retrieve data from a database.
syntax :
SELECT column_names
FROM table_name
WHERE condition
32. Define multiline query.
A multiline query in Python is a SELECT statement that spans multiple lines. This is useful when the query is too long to fit on a single line.
To create a multiline query, you can use the triple quotes (“”” or ”’) to enclose the
query.
“””
SELECT *
FROM products
“””
33. Define strings in python. Give syntax.
A string in Python is a sequence of characters. It is enclosed in single quotes (‘) or double quotes (“). For example, the following are strings:
example :
‘This is a string’
“This is also a string”
34.define private instance variable in python?
A private instance variable is a variable that is prefixed with an underscore (_). Private instance variables are not accessible from outside the class in which they are defined.
class Person:
def __init__(self, name):
self._name = name
def get_name(self):
return self._name
def set_name(self, name):
self._name = name
The _name variable is a private instance variable. It can only be accessed from within the Person class. The get_name() and set_name() methods are used to get and set the value of the _name variable.
Private instance variables are used to hide implementation details from the user. They can also be used to prevent accidental modification of data.
35.Define multipath inheritance in python?
multipath inheritance is a type of inheritance in which a class inherits from multiple parent classes. This is different from single inheritance, where a class inherits from only one parent class.
Multipath inheritance is implemented in Python using the multiple_inheritance keyword.
Syntax:
class DerivedClass(BaseClass1, BaseClass2, BaseClass3):
# methods and attributes of the derived class
36.Operator overloading in python?
Operator overloading is a feature of Python that allows you to redefine the meaning of operators for custom classes. This can be used to make your code more concise and readable.
37.Define command line mode in python?
In Python, command line mode is a mode in which the interpreter reads and executes code from the command line. This is different from interactive mode, in which the interpreter reads and executes code from a prompt.
38.List the python importing libraries with example?
– import math
– import pandas
– import numpy
– import matplotlib
– import tkinter
39.Define console input and output in python?
Console input and output in Python refers to the way that data is entered and displayedin the console.
The input() function:
The input() function prompts the user to enter some text and returns the text that the user entered. For example, the following code prompts the user to enter their name and then prints the name that the user entered:
name = input(“What is your name? “)
print(“Your name is”, name)
The print() function:
The print() function prints the specified text to the console. For example, the following
code prints the message “Hello, world!” to the console:
print(“Hello, world!”)
40.Define Operator precedence and association in python?
Operator precedence is a rule that determines the order in which operators are evaluated in an expression. Operators with higher precedence are evaluated before operators with lower precedence.
For example, in the expression 10 + 2 * 3, the multiplication 2 * 3 is evaluated first because multiplication has higher precedence than addition. The expression is then
evaluated as 10 + 6, which equals 16.
Operator associativity is a rule that determines the order in which operators with the same precedence are evaluated. Most operators in Python are left-associative, which means that the expression is evaluated from left to right. For example, in the expression 10 ** 2 ** 3, the first exponentiation 10 ** 2 is evaluated first, followed by the second exponentiation (10 ** 2) ** 3.
41. Define exit() function in python?
Sure. The exit() function in Python is used to exit or terminate the current running script or program. It can be used to stop the execution of the program at any point.
42.List the types exceptions errors in python?
– Syntax errors
– ZeroDivisionError
– ValueError
– IndexError
– KeyError
– TypeError
– NameError
– AttributeError
43.Write syntax and example to create a function in python?
Syntax
def function_name(parameters):
"""docstring for function_name"""
# body of the function
return value
Example
def add_numbers(x, y):
"""Adds two numbers."""
return x + y
44.Define command line arguments in python?
The arguments that are given after the name of the program in the command line shell of the operating system are known as Command Line Arguments.
45.Define key word arguments in python?
Keyword arguments are arguments that are passed to a function by their name, rather than their position. This makes it easier to read and write function calls, especially when there are many arguments.
In Python, keyword arguments are preceded by a colon (:) and the name of the
argument.
46.What is the scope and lifetime of variables of functions in python?
The scope of a variable is the part of a program where the variable is known. The lifetime of a variable is the period throughout which the variable exists in the memory of your Python program.
There are two types of scopes in Python:
Global scope: Variables declared outside of any function have a global scope. This means that they are accessible from anywhere in the program.
Local scope: Variables declared inside a function have a local scope. This means that they are only accessible from within the function.
47.What is the use of str() function in python?
The str() function in Python is used to convert an object to its string representation. It is a built-in function that can be used to convert objects of different data types, such as integers, and floats.
48.List the python string methods?
1. capitalize(): Converts the first letter of the string to uppercase.
2. lower(): Converts the entire string to lowercase.
3. upper(): Converts the entire string to uppercase.
4. replace(): Replaces all occurrences of a substring with another substring.
5. split(): Splits the string into a list of substrings based on a delimiter.
6. find(): Finds the first occurrence of a substring in the string and returns its index.
7. rfind(): Finds the last occurrence of a substring in the string and returns its index.
8. len(): Returns the length of the string.
9. isalpha(): Returns True if the string consists only of alphabetic characters.
10.isdigit(): Returns True if the string consists only of numeric characters.
11.isalnum(): Returns True if the string consists of alphanumeric characters.
12.startswith(): Returns True if the string starts with a substring.
13.endswith(): Returns True if the string ends with a substring.
49.Define nested list in python?
A nested list in Python is a list that contains one or more other lists. The inner lists are
called sublists.
To create a nested list, you can use the square brackets [] to enclose the lists. For
example, the following code creates a nested list with two sublists:
list1 = [[1, 2, 3], [4, 5, 6]]
50.Define populating and traversing in python?
– In the context of programming, “populating” refers to the process of filling data into
data structures like lists, arrays, dictionaries, or any other container. You populate a
data structure by adding elements or values to it, making it ready for manipulation and
processing.
– “Traversing” in programming means moving through each element or item of a data
structure and performing some operation on each of them. It’s a way to iterate over the elements to access or modify them.
51.What is format operator in file handling ?
The format operator in Python is not specifically related to file handling. It is a generalpurpose formatting operator that can be used to format strings, numbers, and other data types.
52.Define constructor method with syntax in python?
A constructor method in Python is a special method that is called when an object of a class is created. It is used to initialize the object’s data members.
The syntax for a constructor method in Python is:
def __init__(self, parameters):
“””docstring for __init__”””
# body of the constructor method
example
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
53.What is GUI in python?
A GUI or Graphical User Interface in Python is a way to interact with a computer program using graphical elements such as buttons, text boxes, and menus. GUIs are used in most modern software applications, and they make it easy for users to interact with the program without having to learn complex commands.
54.Define dataframe with syntax in python?
A DataFrame in Python is a two-dimensional data structure that is used to store data in rows and columns. It is a powerful tool for data analysis and manipulation, and it is used by data scientists and analysts all over the world.
The syntax for creating a DataFrame in Python is:
import pandas as pd
df = pd.DataFrame({
“Name”: [“John Doe”, “Jane Doe”, “Mary Smith”],
“Age”: [30, 25, 40],
“Country”: [“USA”, “Canada”, “UK”]
})
55.List the different types of charts in data visualization?
– Bar chart
– Line chart
– Pie chart
– Scatter plot
– Histogram
– Box plot
– Area chart
– Bubble chart
56.List the operations on dataframes in python?
– Selection
– Aggregation
– Grouping
– Merging
– Joining
– Filtering
– Slicing
– Renaming
– Sorting
57.Describe the steps to create a database in python?
– Import the sqlite3 module.
– Create a connection object to the database.
– Create a cursor object.
– Use the cursor object to create the database tables.
– Close the connection object.
example
import sqlite3
# Create a connection object to the database.
conn = sqlite3.connect('my_database.db')
# Create a cursor object.
cursor = conn.cursor()
# Create the database tables.
cursor.execute(‘CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, age
INTEGER)’)
cursor.execute(‘CREATE TABLE products (id INTEGER PRIMARY KEY, name TEXT, price
INTEGER)’)
# Close the connection object.
conn.close()
58.Define Pyplot in data visualization.
Pyplot is a plotting library in Python that provides a MATLAB-like interface for creating plots. It is a submodule of the Matplotlib library, which is a comprehensive library for creating static, animated, and interactive visualizations in Python.
59.Write a syntax to create a class and objects in python?
syntax :
class ClassName:
# class attributes
def __init__(self, parameters):
# constructor method
# methods
object1 = ClassName(parameters)
object2 = ClassName(parameters)
example :
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def say_hello(self):
print("Hello, my name is {} and I am {} years old.".format(self.name, self.age))
60.Write a syntax to create a table in sqlite?
syntax :
CREATE TABLE table_name (
column_name1 data_type,
column_name2 data_type,
...
);
Show this in small size because it not looking all sentences, it’s half