0% found this document useful (0 votes)
17 views95 pages

Python Important Questions AI and ML For Sem II Osmania University

The document outlines a comprehensive Python programming syllabus divided into five units covering basics, conditionals, loops, functions, strings, file I/O, iterators, and recursion. It includes key concepts, definitions, and important questions related to each unit, providing a foundational understanding of Python programming. Additionally, it compares Python with Java, discusses Python features, and highlights various data types and operators.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views95 pages

Python Important Questions AI and ML For Sem II Osmania University

The document outlines a comprehensive Python programming syllabus divided into five units covering basics, conditionals, loops, functions, strings, file I/O, iterators, and recursion. It includes key concepts, definitions, and important questions related to each unit, providing a foundational understanding of Python programming. Additionally, it compares Python with Java, discusses Python features, and highlights various data types and operators.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 95

Table Of Contents

1 UNIT-1: INTRODUCTION AND BASICS

2 UNIT-2: CONDITIONALS AND LOOPS

3 UNIT-3: FUNCTION AND STRINGS

4 UNIT-4: SIEVE OF ERATOSTHENES & FILE I/0

5 UNIT-5 : ITERATORS & RECURSION

6 Python Programming Important Links:

7 AKTU Important Links | Btech Syllabus

8 Important Links-Btech (AKTU) | Python Programming syllabus

UNIT-1: INTRODUCTION AND BASICS

 Introduction:

 The Programming Cycle for Python,

 Python IDE,

 Interacting with Python Programs,

 Elements of Python,

 Type Conversion.

 Basics:

 Expressions,

 Assignment Statement,

 Arithmetic Operators,

 Operator Precedence,

 Boolean Expression.

UNIT-2: CONDITIONALS AND LOOPS

 Conditionals:

 Conditional statement in Python (if-else statement, its working and execution),

 Nested-if statement and Elif statement in Python,

 Expression Evaluation & Float Representation.

 Loops:

 Purpose and working of loops,

 While loop including its working,

 For Loop,

 Nested Loops,

 Break and Continue.


UNIT-3: FUNCTION AND STRINGS

 Function:

 Parts of A Function,

 Execution of A Function,

 Keyword and Default Arguments,

 Scope Rules.

 Strings :

 Length of the string and perform Concatenation and Repeat operations in it,

 Indexing and Slicing of Strings.

 Python Data Structure:

 Tuples,

 Unpacking Sequences,

 Lists,

 Mutable Sequences,

 List Comprehension,

 Sets,

 Dictionaries.

 Higher Order Functions:

 Treat functions as first-class Objects,

 Lambda Expressions.

UNIT-4: SIEVE OF ERATOSTHENES & FILE I/0

 Sieve of Eratosthenes:

 generate prime numbers with the help of an algorithm given by the Greek Mathematician named
Eratosthenes,

 whose algorithm is known as Sieve of Eratosthenes.

 File I/O:

 File input and output operations in Python Programming.

 Exceptions and Assertions Modules :

 Introduction, Importing Modules.

 Abstract Data Types:

 Abstract data types and ADT interface in Python Programming.

 Classes:

 Class definition and other operations in the classes,

 Special Methods (such as init, str, comparison methods and Arithmetic methods etc.),
 Class Example,

 Inheritance,

 Inheritance and OOP.

UNIT-5 : ITERATORS & RECURSION

 Iterators & Recursion:

 Recursive Fibonacci,

 Tower Of Hanoi.

 Search :

 Simple Search and Estimating Search Time,

 Binary Search and Estimating Binary Search Time.

 Sorting & Merging:

 Selection Sort,

 Merge List,

 Merge Sort,

 Higher Order Sort.

UNIT-1: INTRODUCTION AND BASICS | Short important

Q1. What is Python?

Ans. Python is a high-level, interpreted, interactive and object-oriented scripting language. It is a highly readable
language. Unlike other programming languages, Python provides an interactive mode similar to that of a calculator.

Q2. What are the difference between Java and Python?

Ans.

ure Java Python

The syntax of Java is complex than Python. The syntax of Python is easier than Java

ed Java is statically typed programming, makes it faster Python is manually typed, makes it slower.

e Longer lines of code than python Shorter lines of code than Java.

Q3. What are the features of Python?

Ans. Features of Python :

 1. The code written in Python is automatically compiled to byte code and executed.

 2. Python can be used as a scripting language, as a language for implementing web applications, etc.

 3. Python supports many features such as nested code blocks, functions, classes, modules and packages.

 4. Python makes use of an object oriented programming approach.


 5. It has many built-in data types such as strings, lists, tuples, dictionaries, etc.

Q4. What are the different ways of starting Python?

Ans. There are three different ways of starting Python :

 1. Running a script written in Python.

 2. Using a graphical user interface (GUI) from an Integrated Development Environment (IDE),

 3. Employing an interactive approach.

Q5. Which character is used for commenting in Python?

Ans. Hash mark (#) is used for commenting in Python.

Q6. How is Python an interpreted language?

Ans. Python is called an interpreted language because it goes through an interpreter, which turns the Python code
into the language understood by processor of the computer.

Q7. What type of language is python?

Ans. Python is an interpreted, object-oriented, high-level programming language with dynamic semantics.

Q8. Define the type () function.

Ans. Type () function in Python programming language is a built-in function which returns the datatype of any
arbitrary object. The object is passed as an argument to the type() function. Type() function can take anything as an
argument and return its datatype, such as integers, strings, dictionaries, lists, classes, module, tuple, functions, etc.

Q9. Define the unary operator.

Ans. Unary operators are operators with only one operand. These operators are basically used to provide sign to the
operand.
+, -, are some unary operators.

Q10. What do you mean by binary operator ?

Ans: Binary operators are operators with two operands that are manipulated to get the result. They are also used to
compare numeric values and string values.

**, %, <<, >>, &, |, ^, <, >, <=, >=, ==, !=, <> are some binary operators.

Q11. What is the purpose of the PYTHONPATH environment variable?

Ans. Pythonpath has a role similar to PATH. This variable tells Python Interpreter where to locate the module files
imported into a program. It should include the Python source library directory and the directories containing Python
source code. PYTHONPATH is sometimes preset by Python Installer.
Q12. What is the difference between list and tuples in Python?

Ans.

List Tuples

Lists are mutable, i.e., they can be edited. Tuples are immutable (they are lists that cannot be edited).

Lists are usually slower than tuples. Tuples are faster than lists.

Syntax :list_ 1 [10, bachelorExam, 20] Syntax :tup 1 (10, bachelorExam, 20)

Q13. What is the difference between Python arrays and lists.

Ans

Arrays Lists

Arrays can only store homogeneous data (data of the same type). Lists can store heterogeneous and arbitrary d

Arrays use less memory to store data. Lists require more memory to store data.

The length of an array is pre-fixed while creating it, so more elements cannot The length of a list is not fixed, so more elem
be added. added.

Q14. Can we make multiline comments in Python?

Ans. Python does not have a specific syntax for including multiline comments like other programming languages.
However, programmers can use triple-quoted strings (docstrings) for making multiline comments as when a docstring
is not used as the first statement inside a method, it is ignored by Python parser.

Q15. Do we need to declare variables with data types in Python?

Ans. No. Python is a dynamically typed language, i.e., Python Interpreter automatically identifies the data type of a
variable based on the type of value assigned to the variable.

Q16. In some languages, every statement ends with a semicolon (;). What happens if you put a semicolon at the
end of a Python statement ?

Ans. Python allows semicolon to use as a line terminator. So no error will occur if we put a semicolon; at the end of
python statement.

Q17. Mention five benefits of using Python.

Ans. Benefits of Python :


 1. Python is easy to learn.

 2. Most automation, data mining, and big data platforms depend on Python. This is because it is the ideal
language to work with for general purpose tasks.

 3. Python provides productive coding environment.

 4. It supports extensive libraries.

 5. Python uses different frameworks to simplify the development process.

Q18. Define floor division with example.

Ans. Floor division returns the quotient in which the digits after the

decimal point are removed. But if one of the operands (dividend and divisor) is negative, then the result is floored,
i.e., rounded away from zero (means, towards the negative of infinity). It is denoted by “//”.

For example:

5.0 // 2

2.0

Q19. List some Python IDEs.

Ans. Some Python IDEs are:

 1. PyCharm

 2. Spyder

 3. PyDev

Q20. Mention some of the reserved keyword in Python.

Ans.

 1. and

 2. false

 3. is

 4. pass 5. return

 6. def

Q21. Give an example of assigning one variable value to another.

Ans.

>>> name1 = ‘Albert’

>>> name2 = name1

>>> name2

‘Albert’ # Output
>>>

Q22. Give an example of different types of values to the same variable.

Ans.

>>> amount = 50

>>> amount

50 # Output

>>> amount = ‘Fifty’

>>> amount

‘Fifty’ # Output

>>>

Q23. What are the types of type conversion?

Ans. Two types of type conversion are:

 1. Implicit type conversion

 2. Explicit type conversion

Q24. What are types of assignment statements?

Ans. Three type of assignment statements are:

 1. Value-based expression on RHS

 2. Current variable on RHS

 3. Operation on RHS

Q25. List the categories of operators.

Ans. Following are the seven categories of operators :

 1. Arithmetic operators.

 2. Assignment operators.

 3. Bitwise operators.

 4. Comparison operators.

 5. Identity operators.

 6. Logical operators.

 7. Membership operators.

Q26. Name the tools that are used for static analysis.
Ans.

 1. Pychecker

 2. Pylint

Q27. What are the different data types used in Python?

Ans. Python has six basic data types which are as follows:

 1. Numeric

 2. String

 3. List

 4. Tuple

 5. Dictionary

 6. Boolean

Q28. Define operator associativity with its type.

Ans.

 1. Associativity decides the order in which the operators with the same precedence are executed.

 2. There are two types of associativity :

 a. Left to right: In left-to-right associativity, the operator of the same precedence are executed from
the left side first.

 b. Right to left: In right-to-left associativity, the operator of the same precedence are executed from
the right side first.

UNIT-2: CONDITIONALS AND LOOPS | Important Short Question

1. What are the factors for expression evaluation?

Ans.

 1. Precedence: It is applied to two different class of operators. That is,+ and*, and *, AND & OR, etc.

 2. Associativity: It is applied to operators of same class. That is, * and *,+ and -, * and /, etc.

 3. Order: Precedence and associativity identify the operands for each operator. While evaluating an
assignment, the RHS is evaluated before LHS.

Q2. What is the range () function?

Ans. The range () function is a built-in function in Python that helps us to iterate over a sequence of numbers. It
produces an iterator that follows an arithmetic progression.

Q3. Give an example of range () function.

Ans.
>>> range (8)

[0, 1, 2, 3, 4, 5, 6, 7]

range (8) provides a sequence of number 0-7. That is to say range (n) generates a sequence of number that starts
with 0 and end with (n – 1).

Q.4. Explain begin and end arguments passed by range () function.

Ans.

>>> range (3, 9)

[3, 4, 5, 6, 7, 8]

We provided the begin index with 3 and the end index with 9. Hence, the range function generates a sequence
iterator of number that starts from 3 and ends at 8.

Q5. Define the term alternative execution.

Ans. The alternative execution provides two possibilities and the condition determines which one is to be executed.
This is the second form of the if statement.

Q6. What do you mean by block?

Ans. The intended statements that follow the conditional statements are called block. The first unintended statement
marks the end of the block.

Q7. What will be the output of the following code:

Str [0:4] if str=”Hello”

Ans. ‘Hello’

Q8. What are control statements?

Ans. A control statement is a statement that determines the control flow of a set of instructions. There are three
fundamental forms of control that programming languages provide: sequential control, selection control, and
iterative control.

Q9. What is short-circuit evaluation ?

Ans. In short-circuit (lazy) evaluation, the second operand of Boolean operators AND and OR is not evaluated if the
value of the Boolean expression can be determined from the first operand alone.

Q10. Define the terms: header, suite and clause.

Ans. A header in Python starts with a keyword and ends with a colon. The group of statements following a header is
called a suite. A header and its associated suite are together referred to as a clause.
Q11. What do you mean by iterative control ?

Ans. An iterative control statement is a control statement providing the repeated execution of a set of instructions.
An iterative control structure is a set of instructions and the iterative control statement(s) controlling their execution.

Q12. What do you mean by definite loop?

Ans. A definite loop is a program loop in which the number of times the loop will iterate can be determined before
the loop is executed.

Q13. What do you mean by indefinite loop?

Ans. An indefinite loop is a program loop in which the number of times that the loop will iterate cannot be
determined before the loop is executed.

Q14. Is indentation optional in Python?

Ans. No indentation in Python is compulsory and is part of its syntax. Indentation is a way of defining the scope and
extent of the block of codes. Indentation provides better readability to the code.

Q15. What happen if break statement is used in for loop?

Ans. If the break statement in a for loop is executed then the else part of that for loop is skipped.

Q16. What is raw_input() function?

Ans. Raw_input() takes the input from the user but it does not interpret the input and also it returns the input of the
user without doing any changes.

Q17. Differentiate fruitful functions and void functions.

Ans. The main difference between void and fruitful functions in python is:

 1. Void does not return any value

 2. Fruitful function returns some value

UNIT-3: FUNCTION AND STRINGS

Q1. Define traversing of string. Give an example.

Ans. Traversal is a process in which we access all the elements of the string one by one using some conditional
statements such as for
loop, while loop, etc.

Q2. What are escape characters ?

Ans. The backslash character (/) is used to escape characters. It converts difficult-to-type characters into a string. For
example, we need the escaping character concept when we want to print a string with double quotes or single
quotes. When single or double quotes are used with the string, Python normally neglects them and prints only the
string.

Q.3. What do you mean by tuple assignment?

Ans. Tuple assignment allows the assignment of values to a tuple of variables on the left side of assignment from the
tuple of values on the right side of the assignment.

Q.4. What do you mean by “Lists are mutable”?

Ans. Lists are mutable means that we can change the value of any elements inside the list at any point of time. The
element inside the list are accessible with their index value. The index will always start with 0 and end with n-1, if the
list contains n elements.

Q5. What do you understand by traversing a list?

Ans. Traversing of the list refers to accessing all the elements or items of the list. Traversing can be done using any
conditional statement of Python, but it is preferable to use for loop.

Q.6. What are the different methods used in deleting elements from dictionary?

Ans. Methods used in deleting elements from dictionary are :

 1. pop(): pop() method removes that item from the dictionary for which the key is provided. It also returns
the value of the item.
 2. popitem(): popitem() method is used to remove or delete and return an arbitrary item from the dictionary.

 3. clear(): clear() method removes all the items or elements from a dictionary at the same time.

Q.7. What are the two properties of key in the dictionary?

Ans. Properties of key:

 1. One key in a dictionary cannot have two values, i.e., duplicate keys are not allowed in the dictionary; they
must be unique.

 2. Keys are immutable, i.e., we can use string, integers or tuples for dictionary keys, but cannot use
something like [‘key’].

Q8. Why we use functions?

Ans.

 1. Break up complex problem into small sub-programs.

 2. Solve each of the sub-problems separately as a function, and combine them together in another function.

 3. Hide the details and shows the functionality.

Q9. What are mathematical functions? How are they used in Python?

Ans. Python provides us a math module containing most of the familiar and important mathematical functions. A
module is a file that contain some predefine Python codes. A module can define functions, classes and variables. It is
a collection of related functions grouped together.

Before using a module in Python, we have to import it

For example, to import the math module, we use:

>>> import math

Q10. What are user-defined functions? Give the syntax.

Ans. Python also allows users to define their own functions. To use their own functions in Python, users have to
define the functions first; this is known as function definition. In a function definition, users have to define a name for
the new function and also the list of the statements that will execute when the function will be called.

Syntax :

Q11. Define the return statement in a function. Give the syntax.


Ans. The return statement is used to exit a function. A function may or may not return a value. If a function returns a
value, it is passed back by the return statement as argument to the caller. If it does not return a value, we simply
write return with no arguments.

Syntax;

return [expression]

Q12. Define anonymous function.

Ans. The anonymous functions are the functions created using a lambda keyword.

Q13. You have been given a string ‘I live in Cochin. I love pets.’ Divide this string in such a very that the two
sentences in it are separated and stored in different variables. Print them.

Ans.

Q14. An email address is provided : hello@python. org. Using tuple assignment, split the username and domain
from the email address.

Ans.

Q15. Write a function called sumall that takes any number of arguments and returns their sum.

Ans.
Q16. Write a function called circleinfo which takes the radius of circle as argument and returns the area and
circumference of the circle.

Ans.

Q17. Give examples for len, max and min methods.

Ans.

Q.18. Give examples for all, any, len and sorted methods in

dictionary.

Ans.

Q.19. Give the syntax required to convert an integer number into string and a float to an integer.
Ans.

Q20. Write a program to print the calendar for the month of

March 1991.

Ans.

Q21. Write a function which accepts two numbers and returns

their sum.

Ans.
Q22. What are the types of arguments used for calling a function?

Ans. Four types of arguments used for calling a function:

 i. Required argument

 ii. Keyword argument

 iii. Default argument

 iv. Variable length argument

Q23. What is the output of print list[2] when list = [‘abcd’, 2.23,

john’] ?

Ans. john

Q24. What is slicing?

Ans. In Python, we can extract a substring by using a colon inside the square bracket [:]. The resultant substring is a
part of the long string.

Q25. What is the use of docstring?

Ans. Docstring command is use to know about a function using triple- quoted string.

Q26. What are local variables and global variables in Python?

Ans.

i. Global variables:

1. Global variables are the variables that are defined outside a function body.

2. Global variables can be accessed throughout the program body by all functions.

ii. Local variables:

1. Local variables are the variables that are defined inside a function body.

2. Local variables can be accessed only inside the function in which they are declared.

3. When we call a function, the variables declared inside it are brought into scope.

UNIT-4: SIEVE OF ERATOSTHENES & FILE I/0

Q1. What is class variable?

Ans. A variable that is defined in the class and can be used by all the instances of that class is called class variable.

Q.2. Define instance variable.

Ans. A variable that is defined in the method; its scope is only within the object that defines it.
Q3. Define the term instance.

Ans. An object is an instance of the class.

Q4. What do you mean by instantiation?

Ans. The process of creating an object is called instantiation.

Q5. Define function overloading.

Ans. A function defined more than one time with different behaviours is called function overloading.

Q6. What do you mean by methods?

Ans. Methods are the functions defined in the definition of class and are used by various instances of the class.

Q7. How are the objects created in Python? Give an example.

Ans. Objects can be used to access the attributes of the class. The syntax for creating an object in Python is similar to
that for calling a

function.

Syntax :

obj_name = class_name()

For example:

Q8. What do you understand by “Objects are mutable” ?

Ans. Objects are mutable means that the state of an object can be changed at any point in time by making changes
to its attributes.

Q9. What do you understand by arguments “Instances as return values”?

Ans. The instances of a class can also be returned by a function i.e., function can return the instances or objects.

Q10. Define__dict__,___bases__,__name__built-in class attributes.Give example.

Ans.

__dict__: It displays the dictionary in which the namespace of class is stored.


__name__ : It displays the name of the class.

_bases__: It displays the tuple that contains the base classes, possibly empty. It displays them in the order in which
they occur in the base class list.

For example:

Q11. Give the advantage of inheritance.

Ans. The main advantage of inheritance is that the code can be written once in the base class and then reused
repeatedly in the subclasses.

Q12. Define subclass.

Ans. The class which inherits the feature of another class is called subclass.

Q13. List the order of file operations in Python.

Ans. The order is as follows:

 1. Opening a file

 2. Perform read or write operation

 3. Closing a file

Q14. Explain any four modes of opening the file.

Ans. Modes of opening the file:

i. r : It opens a file in reading mode. The file pointer is placed at the starting of the file.

ii. r + : It opens the file in both reading and writing mode. The file

pointer is placed at the starting of the file.

iii. w: It opens the file in writing mode. If a file exists, it overwrites the existing file; otherwise, it creates a new file.

iv. w +: It opens the file in both reading and writing mode. If a file exists, it overwrites the existing file; otherwise, it
creates a new file.

Q15. Explain the file object attributes in detail.

Ans.
Attribute Description

file.closed It will return true if the file is closed; it will otherwise return false.

file.mode It will return the access mode with which the file is opened.

file.name It will return name of the file

file.softspace It will return false if space explicitly required with print; otherwise it will return true.

Q16. Give the syntax for reading from a file. What is the work of the readline() function?

Ans. Syntax:

fileobject.read([size])

The count parameter size gives the number of bytes to be read from an opened file. It starts reading from the
beginning of the file until the size given. If no size is provided, it ends up reading until the end of the file.

Q17. How are renaming and deleting performed on a file ? Give the syntax for each.

Ans.

Renaming a file: Renaming a file in Python is done with the help of the rename() method. The rename() method is
passed with two argument, the current filename and the new filename.

Syntax :

os.rename(current_filename, new_filename)

Deleting a file: Deleting a file in Python is done with the help of the remove() method. The remove() method takes
the filename as an argument to be deleted.

Syntax :

os.remove(filename)

Q18. What are the various file positions methods?

Ans. In Python, the tell() method tells us about the current position of the pointer. The current position tells us where
reading will starts from at present.

We can also change the position of the pointer with the help of the seek() method. We pass the number of bytes to
be moved by the pointer as arguments to the seek() method.

Q19. What are directories?

Ans. If there is a large number of files, then related files are placed in different directories. The directory can be said
to be a collection of files

and sub-directories. The module in Python enables us to use various methods to work with directories.
Q20. What are the basic methods performed on directories ?

Ans. Following are the four basic methods that are performed on directories:

 i. mkdir () method (Creating a directory)

 ii. chdir() method (Changing the current directory)

 iii. getcwd () method (Displaying the current directory)

 iv. rmdir () method (Deleting the directory).

Q21. What are user-defined exceptions? Give one example.

Ans. Python allows users to define their own exceptions by creating a new class. Exception needs to be derived,
directly or indirectly from exception class.

For example:

>>> class error(Exception)


pass

Q22. Write some built-in exception in Python.

Ans.

 i. AssertionError

 ii. FloatingPointError

 iii. SystemError

 iv. RunTimeError

 v. ZeroDivisionError

Q23. Define ADT interface.

Ans. ADT interface only defines what operations are to be performed

but not how these operations will be implemented. It does not specify how data will be organized in memory and
what algorithms will be used for implementing the operations. It is called “abstract” because it gives an
implementation-independent view.

UNIT-5 : ITERATORS & RECURSION

Q1. What are the properties of recursive functions? ]

Ans. Properties of recursive function:

 1. The arguments of function change between the recursive calls.

 2. The change in arguments should be toward a case for which the solution is known and we call it as a base
case. There can be more than one base case.

Q2. What are the advantages of recursion?


Ans.

 1. It requires few variables.

 2. The programs are easy to implement if the problem has a recursive definition.

Q3. Give some disadvantages of recursion.

Ans.

 1. Debugging is difficult.

 2. It is not easy to write the program in a recursive form.

 3. It can be inefficient as it requires more time and space.

Q4. What are the applications of Tower of Hanoi problem?

Ans.

 1. The Tower of Hanoi is frequently used in psychological research on problem solving.

 2. There also exists a variant of this task called Tower of London for neuropsychological diagnosis and
treatment of executive functions.

 3. The Tower of Hanoi is also used as a Backup rotation scheme when performing computer data Backups
where multiple tapes/media are involved.

 4. The Tower of Hanoi is also used as a test by neuropsychologists trying to evaluate frontal lobe deficits.

Q5. What are the advantages and drawbacks of simple search?

Ans: Advantages:

 1. It is a very simple search and easy to program.

 2. In the best-case scenario, the item we are searching for may be at the start of the list in which case we get
it on the very first try.

Drawbacks :

 1. Its drawback is that if our list is large, it may take time to go through the list.

 2. In the worst-case scenario, the item we are searching for may not be in the list, or it may be at the
opposite end of the list.
Q6. Write algorithm of simple search.

Ans.

Q7. Give the algorithm for binary search.

Ans

Q8. Define the term sorting.

Ans.

 1. Sorting is the arrangement of a given list in ascending order or descending order.

 2. In sorting, searching for an element is very fast.

 3. Example of sorting in real world are: Contact list in mobile phones, ordering marks before assignment of
grades, etc.

Q9. Which operation is used to implement merge sort?

Ans: Merge operation is used to implement merge sort.

Q10. List some sorting algorithm.

Ans.

 1. Insertion sort

 2. Selection sort
 3. Bubble sort

 4. Merge sort

Q11. What is binary search?

Ans. Binary search is a search algorithm that finds the position of a target value within a sorted list.

Q12. Which method is used to sort a list ?

Ans. Sort() method is used to sort a list.

Q13. What are the possibilities while sorting a list of string?

Ans. Possibilities while sorting a list of string are:

 1. Sorting in alphabetical/reverse order.

 2. Based on length of string character.

 3. Sorting the integer values in list of string.

Unit-1 Important Question-Python Programming | INTRODUCTION AND BASICS

Table Of Contents

1 Q1. Explain the programming cycle for Python.

2 Q2. What is Python? How is Python interpreted? What are the tools that help to find bugs or perform static
analysis? What Are Python decorators?

3 Q3. What do you mean by data types? Explain numeric and string data type with examples.

4 Q4. Discuss list and tuple data types in detail.

5 Q5. What do you mean by Boolean expression?ORWrite short notes with example: The programming cycle for
Python, elements of Python, type conversion in Python, operator precedence, and Boolean expression.

6 Q5. How memory is managed in Python? Explain PEP 8. Write a Python program to print even length words in a
string.

7 Python Programming Important Links:

Q1. Explain the programming cycle for Python.

Ans.

1. Python’s programming cycle is dramatically shorter than that of traditional programming cycle.

2. In Python, there are no compile or link steps.

3. Python programs simply import modules at runtime and use the objects they contain.Because of this, Python
programs run immediately after changes are made.

4. In cases where dynamic module reloading can be used, it is even possible to change and reload parts of a
running program without stopping it at all.

5. Fig. 1 shows Python’s impact on the programming cycle.


6. Since Python is interpreted, there is a rapid turnaround after program changes. And because Python’s parser
is embedded in Python-based systems, it is easy to modify programs at runtime.

Q2. What is Python? How is Python interpreted? What are the tools that help to find bugs or perform static
analysis? What Are Python decorators?

Ans.

Python: Python is a high-level, interpreted, interactive and object-oriented scripting language. It is a highly readable
language. Unlike other programming languages, Python provides an interactive mode similar to that of a calculator.

Interpretation of Python :

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

 2. When we write Python programs, it converts source code written by the developer into an intermediate
language which is again translated into the machine language that is executed.

 3. The python code we write is compiled into python bytecode, which creates a file with the extension .pyc.

 4. The bytecode compilation happened internally and was almost completely hidden from the developer.

 5. Compilation is simply a translation step, and byte code is a lower-level, and platform-independent,
representation of source code.

 6. Each of the source statements is translated into a group of bytecode instructions. This bytecode translation
is performed to speed execution. Bytecode can be run much quicker than the original source code

 statements.

 7. The .pyc file, created in the compilation step, is then executed by appropriate virtual machines.

 8. The Virtual Machine iterates through bytecode instructions, one by one, to carry out their operations.

 9. The Virtual Machine is the runtime engine of Python and it is always present as part of the Python system,
and is the component that actually runs the Python scripts.

 10. It is the last step of the Python interpreter.

The following tools are the static analysis tools that help to find bugs in python :

1.Pychecker: Pychecker is an open source tool for static analysis that detects the bugs from source code and warns
about the style and complexity of the bug.
2. Pylint:

 a.Pylint is highly configurable and it acts like special programs to control warnings and errors, it is an
extensive configuration file

 b. It is an open source tool for static code analysis and it looks for programming errors and is used for coding
standard.

 c. It also integrates with Python IDEs such as Pycharm, Spyder, Eclipse, and Jupyter.

Python decorators:

1. Decorators are very powerful and useful tool in Python since it allows programmers to modify the behavior
of function or class.

2. Decorators allow us to wrap another function in order to extend the behavior of wrapped function, without
permanently modifying it.

3. In decorators, functions are taken as the argument into another function and then called inside the wrapper
function.

4. Syntax :
@gfg_decorator
def hello_decorator():
print(“Gfg”)

5. gfg_decorator is a callable function, will add some code on the top of some another callable function,
hello_decorator function and return the wrapper function.

Q3. What do you mean by data types? Explain numeric and string data type with examples.

Ans.
Data types:

 The data stored in the memory can be of many types. For example, a person’s name is stored as an
alphabetic value and his address is stored as an alphanumeric value.

 Python has six basic data types which are as follows:

 Numeric

 String

 List

 Tuple

 Dictionary

 Boolean

 Numeric

 Numeric data can be broadly divided into integers and real numbers (i.e., fractional numbers).
Integers can be positive or negative.

 The real numbers or fractional numbers are called, floating point numbers in programming
languages. Such floating point numbers contain a decimal and a fractional part.

For example:
 String

 Single quotes or double quotes are used to represent strings.

 A string in Python can be a series or a sequence of alphabets, numerals and special characters.

 For Example

Q4. Discuss list and tuple data types in detail.

Ans.

List:

1. A list can contain the same type of items.

2. Alternatively, a list can also contain different types of items.

3. A list is an ordered and indexable sequence.

4. To declare a list in Python, we need to separate the items using commas and enclose them within square
brackets ([ ]).
5. Operations such as concatenation, repetition and sub-list are done on list using plus (+), asterisk (*) and
slicing (:) operator.

Tuple:

1. A tuple is also used to store sequence of items.

2. Like a list, a tuple consists of items separated by commas.

3. Tuples are enclosed within parentheses rather than within square brackets.

Q5. What do you mean by Boolean expression?


OR
Write short notes with example: The programming cycle for Python, elements of Python, type conversion in
Python, operator precedence, and Boolean expression.

Ans.

Programming cycle for Python :

 Python’s programming cycle is dramatically shorter than that of traditional programming cycle.

 In Python, there are no compile or link steps.

 Python programs simply import modules at runtime and use the objects they contain.Because of this, Python
programs run immediately after changes are made.

 In cases where dynamic module reloading can be used, it is even possible to change and reload parts of a
running program without stopping it at all.

 Fig. 1 shows Python’s impact on the programming cycle.

Since Python is interpreted, there is a rapid turnaround after program changes. And because Python’s parser is
embedded in Python-based systems, it is easy to modify programs at runtime.
Elements of Python :

Data types:

 The data stored in the memory can be of many types. For example, a person’s name is stored as an
alphabetic value and his address is stored as an alphanumeric value.

 Python has six basic data types which are as follows:

 Numeric

 String

 List

 Tuple

 Dictionary

 Boolean

 Numeric

 Numeric data can be broadly divided into integers and real numbers (i.e., fractional numbers).
Integers can be positive or negative.

 The real numbers or fractional numbers are called, floating point numbers in programming
languages. Such floating point numbers contain a decimal and a fractional part.

For example:
 String

 Single quotes or double quotes are used to represent strings.

 A string in Python can be a series or a sequence of alphabets, numerals and special characters.

 For Example

List:

6. A list can contain the same type of items.

7. Alternatively, a list can also contain different types of items.

8. A list is an ordered and indexable sequence.

9. To declare a list in Python, we need to separate the items using commas and enclose them within square
brackets ([ ]).

10. Operations such as concatenation, repetition and sub-list are done on list using plus (+), asterisk (*) and
slicing (:) operator.
Tuple:

4. A tuple is also used to store sequence of items.

5. Like a list, a tuple consists of items separated by commas.

6. Tuples are enclosed within parentheses rather than within square brackets.

Dictionary:

1. A Python dictionary is an unordered collection of key-value pairs.

2. When we have the large amount of data, the dictionary data type is used.

3. Keys and values can be of any type in a dictionary.

4. Items in dictionary are enclosed in the curly-braces () and separated by the comma (,).

5. A colon (:) is used to separate key from value. A key inside the square bracket [ ] is used for accessing the
dictionary items.

6. For example:

Boolean :

 1. In a programming language, mostly data is stored in the form of alphanumeric but sometimes we need to
store the data in the form of ‘Yes’ or ‘No’.

 2. In terms of programming language, Yes is similar to True and No is similar to False.

 3. This True and False data is known as Boolean data and the data types which stores this Boolean data are
known as Boolean data types.

Type conversion in Python :

 1. The process of converting one data type into another data type is known as type conversion.

 2. There are mainly two types of type conversion methods in Python :

a. Implicit type conversion :


 When the data type conversion takes place during compilation or during the run time, then it called an
implicit data type conversion.

 Python handles the implicit data type conversion, so we do not have to explicitly convert the data type into
another data type

 In the given example, we have taken two variables of integer and float data types and added them.

 Further, we have declared another variable named ‘sum’ and stored the result of the addition in it.

 When we checked the data type of the sum variable, we can see that the data type of the sum variable has
been automatically converted into the float data type by the Python compiler. This is called implicit type
conversion.

b. Explicit type conversion:

 Explicit type conversion is also known as type casting.

 Explicit type conversion takes place when the programmer clearly and explicitly defines the variables in the
program.

For example:
 In the given example, the variable a is of the number data type and variable b is of the string data type.

Operator precedence:

 1. When an expression has two or more operator, we need to identify the correct sequence to evaluate these
operators. This is because result of the expression changes depending on the precedence.
For example : Consider a mathematical expression: 10+ 5/5
When the given expression is evaluated left to right, the final answer becomes 3.

 2. However, if the expression is evaluated right to left, the final answer becomes 11. This shows that changing
the sequence in which the operators are evaluated in the given expression also changes the solution.
 3. Precedence is the condition that specifies the importance of each operator relative to the other.

Boolean expression: A boolean expression may have only one of two values: True or False.

For example: In the given example comparison operator (==) is used which compares two operands and prints true if
they are equal otherwise print false :

>>> 5 == 5

True #Output

>>> 5 == 6

False #Output

Q5. How memory is managed in Python? Explain PEP 8. Write a Python program to print even length words in a
string.

Ans. Memory management :

1. Memory management in Python involves a private heap containing all Python objects and data structures.

2. The management of this private heap is ensured internally by the Python memory manager.

3. The Python memory manager has different components which deal with various dynamic storage
management aspects, like sharing, segmentation, preallocation or caching.

4. At the lowest level, a raw memory allocator ensures that there is enough room in the private heap for storing
all Python-related data by interacting with the memory manager of the operating system.

5. On top of the raw memory allocator, several object-specific allocators operate on the same heap and
implement distinct memory management policies adapted to the peculiarities of every object type.

6. For example, integer objects are managed differently within the heap than strings, tuples or dictionaries
because integers imply different storage requirements and speed/space tradeoffs.
7. Python memory manager thus delegates some of the work to the object-specific allocators, but ensures that
the latter operate within the bounds of the private heap.

PEP 8:

1. A PEP is a design document providing information to the Python community, or describing a new feature for
Python or its processes or environment.

2. The PEP should provide a concise technical specification of the feature.

3. PEP is actually an acronym that stands for Python Enhancement Proposal.

4. PEP 8 is Python’s style guide. It is a set of rules for how to format the Python code to maximize its
readability.

5. A PEP is a design document providing information to the Python community, or describing a new feature for
Python or its processes or environment.

Search

Courses

 Code World

 Ask your Questions

 Bachelor Exam


All Question paper with solution mean Bachelorexam.com

Facebook

Youtube

Instagram

Unit 2 – python programming | CONDITIONALS AND LOOPS

Last Updated on: April 4, 2023 by Bachelor Exam

Table Of Contents

1 Q1. Explain elif statements in Python.ORExplain all the conditional statement in Python using small code example?

2 Q2. Explain expression evaluation and float representation with example. Write a Python program for how to check
if a given number is Fibonacci number.

3 Q3. Explain the purpose and working of loops. Discuss break and continue with examples. Write a Python program
to convert time from 12 hour to 24-hour format.

4 Q4. Differentiate between for and while loop.

5 Q5. Write a python program to print the numbers for a user provided range.

6 Python Programming Important Links:

Q1. Explain elif statements in Python.


OR
Explain all the conditional statement in Python using small code example?

Ans. Different types of conditional statement are:

1. If statement:
1. An if statement consists of a Boolean expression followed by one or more statements.

2. With an if clause, a condition is provided; if the condition is true then the block of statement written in the if
clause will be executed, otherwise not.

3. Syntax:

If (Boolean expression): Block of code #Set of statements to execute if the condition is true

2. If else statement:

1.An if statement can be followed by an optional else statement, which executes when the Boolean expression is
False.

2. The else condition is used when we have to judge one statement on the

basis of other.

3. Syntax: If (Boolean expression): Block of code #Set of statements to execute – if condition is true

else: Block of code #Set of statements to execute if condition is false

4. Working and execution:

 The condition will be evaluated to a Boolean expression (true or false).

 If the condition is true then the statements or program present inside the if block will be executed

 If the condition is false then the statements or program present inside else block will be executed.
3.Nested-if statement:

 Nested-if statements are nested inside other if statements. That is, a nested-if statement is the body of
another if statement.

 We use nested if statements when we need to check secondary conditions only if the fist condition executes
as true.

4. Elif statement:
1. Elif stands for else if in Python.

2. We use elif statements when we need to check multiple conditions only if the given if condition executes as
false.

3. Working and execution:

1. If the first if condition is true, the program will execute the body of the if statement. Otherwise, the
program will go to the elif block (else if in Python) which basically checks for another if statement.

2. Again, if the condition is true, the program will execute the body of the elif statement, and if the
condition is found to be false, the program will go to the next else block and execute the body of the
else block.

4. Syntax
Q2. Explain expression evaluation and float representation with example. Write a Python program for how to
check if a given number is Fibonacci number.

Ans. Expression evaluation:

 In Python actions are performed in two forms:

 Expression evaluation,

 Statement execution.

 The key difference between these two forms is that expression evaluation returns a value whereas statement
execution does not return any value.

 A Python program contains one or more statements. A statement contains zero or more expressions.

 Python executes a statement by evaluating its expressions to values one by one.

 Python evaluates an expression by evaluating the sub-expressions and substituting their values.

 For example:

 An expression is not always a mathematical expression in Python. A value by itself is a simple expression, and
so is a variable.

 In the given example, we assigned a value “Hello Python” to the variable program. Now, when we type only
program, we get the output ‘Hello Python’. This is the term we typed when we assigned a value to the
variable. When we use a print statement with program it gives the value of the variable i.e., the value after
removing quotes.

Float representation:

1. Floating point representations vary from machine to machine.

2. The float type in Python represents the floating-point number.

3. Float is used to represent real numbers and is written with a decimal point dividing the integer and fractional
parts.

4. For example: 97.98, 32.3+e18, -32.54e100 all are floating point numbers.

5. Python float values are represented as 64-bit double-precision values. The maximum value any floating-point
number can be is approx 1.8 × 10308

6. Any number greater than this will be indicated by the string inf in Python.

7. Floating-point numbers are represented in computer hardware as base 2 (binary) fractions.

8. For example, the decimal fraction 0.125 has value 1/10+2/100+ 5/1000, and in the same way the binary
fraction 0.001 has value 0/2 + 0/4 + 1/8.
9. For example: # Python code to demonstrate float values.

Program:

Q3. Explain the purpose and working of loops. Discuss break and continue with examples. Write a Python program
to convert time from 12 hour to 24-hour format.

Ans.

Purpose and working of loops :

 A loop is a programming structure that repeats a sequence of instructions until a specific condition is met.

 A loop statement allows us to execute a statement or group of statements multiple times.

 a. For

 b. While

 C.Nested
 Python programming language provides following types of loops to handle looping requirements:

 Purpose: The purpose of loops is to repeat the same, or similar, code a number of times. This number of
times could be specified to a certain number, or the number of times could be dictated by a certain condition
being met.

 Working: Consider the flow chart for a loop execution:

 In the flow chart if the test condition is true, then the loop is executed, and if it is false then the
execution breaks out of the loop.

 After the loop is successfully executed the execution again starts from the loop entry and again
checks for the test condition, and this keeps on repeating until the condition is false.

Break statement:

 The break keyword terminates the loop and transfers the control to the end of the loop.

 While loops, for loops can also be prematurely terminated using the break statement.

 The break statement exits from the loop and transfers the execution from the loop to the statement that is
immediately following the loop.
 For example:

Continue statement:

 The continue statement causes execution to immediately continue at the start of the loop, it skips the
execution of the remaining body part of the loop.

 The continue keyword terminates the ongoing iteration and transfers the control to the top of the loop and
the loop condition is evaluated again. If the condition is true, then the next iteration takes place.

 Just as with while loops, the continue statement can also be used in Python for loops

 For Example:

Output

 2

 4

 6

 8

Program:
Q4. Differentiate between for and while loop.

Ans.

Properties For While

Initialization, condition checking, iteration


Format Only initialization and condition checking is done at top
statements are written at the top of the loop.

The ‘For’ loop is used only when we already knew The ‘while’ loop is used only when the number of iterati
Use
the number of iterations exactly known.

If the condition is not given in the ‘for’ loop then If the condition is not given in the ‘while’ loop, it provide
Condition
the loop iterates infinite times. compilation error.

Initializatio In ‘for’ loop the initialization once done is never In the ‘while’ loop if initialization is done during conditio
n repeated. then initialization is done each time the loop iterates.

Q5. Write a python program to print the numbers for a user provided range.

Ans.
Unit3-FUNCTION AND STRINGS | Python programming Important Question with solution

Last Updated on: April 4, 2023 by Bachelor Exam

Table Of Contents

1 Q1. Explain unpacking sequences, and mutable sequences, and list comprehension with examples. Write a program
to sort the list of dictionaries by values in Python – Using the lambda function.

2 Q2. Explain higher order function with respect to lambda expression. Write a Python code to count occurrences of
an element in a list

3 Q3. Explain Lambda Expression.

4 Q4. What do you mean by sets? Explain the operations performed on sets.
5 Q5. Define tuples. How are tuples created in Python?

6 Python Programming Important Links:

Q1. Explain unpacking sequences, and mutable sequences, and list comprehension with examples. Write a
program to sort the list of dictionaries by values in Python – Using the lambda function.

Ans.

Unpacking sequences:

 Unpacking allows us to extract the components of the sequence into individual variables.

 Several different assignments can be performed simultaneously.

 We have multiple assignments in Python where we can have multiple LHS assigned from corresponding
values at the RHS. This is an example of unpacking sequences.

 There is one restriction, the LHS and RHS must have equal length. That is, every value that is created at RHS
should be assigned to LHS.

 Strings and tuples are examples of sequences. Operations applicable on sequences are: Indexing, repetition,
concatenation.

 Since strings are also sequences, we can also get individual characters in the string using unpacking
operation.

Mutable sequences:

1. Python represents all its data as objects. Mutability of object is determined by its type.

2. Some of these objects like lists and dictionaries are mutable, meaning we can change their content without
changing their identity.

3. Other objects like integers, floats, strings and tuples are immutable, meaning we cannot change their
contents.
4. Dictionaries are mutable in Python :

1. Dictionaries in Python are mutable.

2. The values in a dictionary can be changed, added or deleted.

3. If the key is present in the dictionary, then the associated value with that key is updated or changed;
otherwise a new key: value pair is added.

For example:

4. In the given example, we tried to reassign the value ’30’ to the key ‘age’, Python interpreter first searches the
key in the dictionary and then updates it. Hence, the value of ‘age’ is updated to 30. However, in the next
statement, it does not find the key ‘address’; hence, the key: value ‘address’: ‘Alaska’ is added to the
dictionary.

5. Strings are immutable:

1. String are immutable which means that we cannot change any element of a string.

2. If we want to change an element of a string, we have to create a new string.

3. For example:

4.

5. Output:

Type error: ‘str’ object does not support item assignment


Here, we try to change the 0th index of the string to a character p, but the python interpreter generates an error.
Now, the solution to this problem is to generator a new string rather than change the old string.

In the given example, we cut the slice from the original string and concatenate it with the character we want to insert
in the string. It does not have any effect on the original string.

6. Lists are mutable :


1. Lists are mutable means that the value of any element inside the list can be changed at any point of
time.

2. The elements of the list are accessible with their index value.

3. The index always starts with 0 and ends with n – 1, if the list contains n elements.

4. The syntax for accessing the elements of a list is the same as in the case of a string. We use square
brackets around the variable and index number.

5. For example:

In the given example, we access the 2nd element of the list that has 1 as index number and the
interpreter prints 20.
Now, if we want to change a value in the list given in the example:

List comprehension :

1. List comprehension is used to create a new list from existing sequences.

2. It is a tool for transforming a given list into another list.

3. Using list comprehension, we can replace the loop with a single expression that produces the same result.

4. The syntax of list comprehension is based on set builder notation in mathematics.

5. Set builder notation is a notation is a mathematical notation for describing a set by stating the property that
its members should satisfy. The syntax is

1. [<expression> for <element> in <sequence> if <conditional>]


The syntax is read as “Compute the expression for each element in the sequence, if the conditional is
true”.
2.

6. In the given example, the output for both without list comprehension and using list comprehension is the
same.

7. The use of list comprehension requires lesser code and also runs faster.

8. From above example we can say that list comprehension contains:

1. An input sequence

2. A variable referencing the input sequence

3. An optional expression

4. An output expression or output variable


Q2. Explain higher order function with respect to lambda expression. Write a Python code to count occurrences of
an element in a list

Ans.

1. Reduce(), filter(), map() are higher order functions used in Python.

2. Lambda definition does not include a “return” statement, it always contains an expression which is returned.

3. We can also put a lambda definition anywhere a function is expected, and we do not have to assign it to a
variable at all.

4. Lambda functions can be used along with built-in higher order functions like filter(), map() and reduce().

Use of lambda with filter():

1. The filter() function in Python takes in a function and a list as arguments.

2. This function helps to filter out all the elements of a sequence “sequence”, for which the function returns
true.
1. For example: Python program that returns the odd numbers from an input list:

Use of lambda() with reduce():

1. The reduce() function in Python takes in a function and a list as arguments.

2. The function is called with a lambda function and a list and a new reduced result is returned. This performs a
repetitive operation over the pairs of the list.

3.This is a part of the functools module.

For example:

Here the results of previous two elements are added to the next element and this goes on till the end of the list like
(((((5+8)+10)+20)+50)+100).

Program to count occurrences of an element in a list :


Q3. Explain Lambda Expression.

Ans.

1. Lambda expressions is used to create the anonymous function.

2. The anonymous functions are the functions created using a lambda keyword.

3. They are not defined by using the def keyword. For this reason, they are called anonymous functions.

4. We can pass any number of arguments to a lambda form functions, but still they return only one value in the
form of expression.

5. An anonymous function cannot directly call print command as the lambda needs an expression.

6. It cannot access the parameters that are not defined in its own namespace.

7. An anonymous function is a single line statement function.

8. Syntax :


9. In the given example, the lambda function is defined with two arguments vall and val2. The expression
val1*va12 does the multiplication of the two values. Now, in function call, we can directly call the mult
function with two valid values as arguments and produce the output as shown in given example.

Q4. What do you mean by sets? Explain the operations performed on sets.

Ans.

 1. In Python we also have one data type which is an unordered collection of data known as set.

 2.A set does not contain any duplicate values or elements.

Operations performed on sets are:

 i.Union: Union operation performed on two sets returns all the elements from both the sets. It is performed
by using and operator.

 ii. Intersection: Intersection operation performed on two sets returns all the elements which are common or
in both the sets. It is performed by using ‘|’ operator.

 iii. Difference: Difference operation performed on two sets set1 and set2 returns the elements which are
present on set1 but not in set2. It is performed by using the ‘-‘ operator.

 iv. Symmetric difference: Symmetric difference operation performed on two sets returns the element which
are present in either set1 or set2 but not in both. It is performed by using an operator.

Q5. Define tuples. How are tuples created in Python?

Ans.
 1. Tuples are the sequence or series values of different types separated by commas (,).

 2. Values in tuples can also be accessed by their index values, which are integers starting from 0.

For example:

The names of the months in a year can be defined in a tuple:

>>> months = (‘January’, February’, March’, April’, ‘May’, ‘June’, ‘July’, ‘August’, ‘September’, ‘October’, ‘November’,
‘December’)

Creating tuples in Python :

1. To create a tuple, all the items or elements are placed inside parentheses separated by commas and assigned to a
variable.

2. Tuples can have any number of different data items (that is, integer, float, string, list, etc.).

For examples:

1. A tuple with integer data items:

>>> tuple = (4, 2, 9, 1)

>>> print tuple

(4, 2, 9, 1) # Output

2. A tuple with items of different data types:

>>>tuple_mix = (2, 30, “Python”, 5.8, “Program”)

>>>print tuple_mix

(2, 30, ‘Python’, 5.8, ‘Program’) # Output

3. Nested tuple:

>>>nested_tuple = (“Python”, [1, 4, 2], [“john”, 3.9])

>>> print nested_tuple

(‘Python’, [1, 4, 2], [‘john’, 3.9]) # Output

4. Tuple can also be created without parenthesis:

>>>tuple = 4.9, 6, ‘house’

>>>print tuple

(4.9, 6, ‘house’) # Output

UNIT-4: SIEVE OF ERATOSTHENES & FILE I/O | Python programming Important questions with solution

Last Updated on: April 4, 2023 by Bachelor Exam

Table Of Contents

1 Q1. Discuss file I/O in Python. How to perform open, read, write, and close into a file? Write a Python program to
read a file line-by-line store it into a variable.

2 Q2. Discuss exceptions and assertions in Python. How to

3 Q3. Define Class Object with Examples?

4 Q4. Explain data encapsulation with example.


5 Q5. What do you mean by multiple inheritance? Explain in detail.

6 Python Programming Important Links:

Q1. Discuss file I/O in Python. How to perform open, read, write, and close into a file? Write a Python program to
read a file line-by-line store it into a variable.

Ans.

File I/O:

1. A file in a computer is a location for storing some related data.

2. It has a specific name.

3. The files are used to store data permanently on to a non-volatile memory (such as hard disks).

4. As we know, the Random Access Memory (RAM) is a volatile memory type because the data in it is lost when
we turn off the computer. Hence, we use files for storing of useful information or data for future reference.

Open, read, write and close into a file:

Open into a file

1. Python has a built-in open() function to open files from the directory.

2. Two arguments that are mainly needed by the open() function are:

1. File name: It contains a string type value containing the name of the file which we want to access.

2. Access_mode: The value of access_mode specifies the mode in which we want to open the file, i.e.,
read, write, append etc.

3. Syntax:

1.

close into a file

1. When the operations that are to be performed on an opened file are finished, we have to close the file in
order to release the resources.

2. Python comes with a garbage collector responsible for cleaning up the unreferenced objects from the
memory, we must not rely on it to close a file.

3. Proper closing of a file frees up the resources held with the file.

4. The closing of file is done with a built-in function close().


5. Syntax:

write into a file

1. After opening a file, we have to perform some operations on the file. Here we will perform the write
operation.

2. In order to write into a file, we have to open it with w mode or a mode, on any writing-enabling mode.

3. We should be careful when using the w mode because in this mode overwriting persists in case the file
already exists.

4. For example:

The given example creates a file named test.txt if it does not exist, and overwrites into it if it exists. If we
open the file, we will find the following content in it.

Output:
Writing to the file line 1
Writing to the file line 2
Writing to the file line 3
Writing to the file line 4

Reading into a file

1. In order to read from a file, we must open the file in the reading mode (r mode).

2. We can use read (size) method to read the data specified by size.

3. If no size is provided, it will end up reading to the end of the file.

4. The read() method enables us to read the strings from an opened file.

5. Syntax :
file object. read ([size])
For example:
# open the file

Q2. Discuss exceptions and assertions in Python. How to

handle exceptions with try-finally? Explain five built-in exceptions with example?

Ans.

Exception:

1. While writing a program, we often end up making some errors. There are many types of error that can occur
in a program.

2. The error caused by writing an improper syntax is termed syntax error or parsing error; these are also called
compile time errors.

3. Errors can also occur at runtime and these runtime errors are known as exceptions.

4. There are various types of runtime errors in Python.

5. For example, when a file we try to open does not exist, we get a FileNotFoundError. When a division by zero
happens, we get a ZeroDivisionError. When the module we are trying to import does not exist, we get an
ImportError.

6. Python creates an exception object for every occurrence of these run- time errors.

7. The user must write a piece of code that can handle the error.
8. If it is not capable of handling the error, the program prints a trace back to that error along with the details of
why the error has occurred.

Assertions:

1. An assertion is a sanity-check that we can turn on or turn off when we are done with our testing of the
program. An expression is tested, and if the result is false, an exception is raised.

2. Assertions are carried out by the assert statement.

3. Programmers often place assertions at the start of a function to check for valid input, and after a function call
to check for valid output.

4. An AssertionError exception is raised if the condition evaluates to false.

5. The syntax for assert is: assert Expression [, Arguments]

6. If the assertion fails, Python uses ArgumentExpression as the argument for the AssertionError.
Handle exceptions:

1. Whenever an exception occurs in Python, it stops the current process and passes it to the calling process
until it is handled.

2. If there is no piece of code in our program that can handle the exception, then the program will crash.

3. For example, assume that a function X calls the function Y, which in turn calls the function Z, and an
exception occurs in Z. If this exception is not handled in Z itself, then the exception is passed to Y and then to
X. If this exception is not handled, then an error message will be displayed and our program will suddenly
halt.

1. Try…except:

1. Python provides a try statement for handling exceptions.

2. An operation in the program that can cause the exception is placed in the try clause while
the block of code that handles the exception is placed in the except clause.

3. The block of code for handling the exception is written by the user and it is for him to decide
which operation he wants to perform after the exception has been identified.
4. Syntax:

2. Try finally :

1. The try statement in Python has an optional finally clause that can be associated with it.

2. The statements written in the finally clause will always be executed by the interpreter,
whether the try statement raises an exception or not.

3. With the try clause, we can use either except or finally, but not both.

4. We cannot use the else clause along with the final clause.

Five built-in exceptions:

1. exception LookupError: This is the base class for those exceptions that are raised when a key or index used
on a mapping or sequence is invalid or not found. The exceptions raised are:

1. KeyError

2. IndexError
2. TypeError: TypeError is thrown when an operation or function is applied to an object of an inappropriate
type.

3. exception ArithmeticError: This class is the base class for those built-in exceptions that are raised for various
arithmetic errors such as:

1. OverflowError

2. ZeroDivisionError

3. Floating PointError

4. For example:

4. exception AssertionError: An AssertionError is raised when an assert statement fails.

5. exception AttributeError: An AttributeError is raised when an attribute reference or assignment fails such as
when a non-existent attribute is referenced.

Q3. Define Class Object with Examples?

Ans.

Class:

1. A class can be defined as a blue print or a previously defined structure from which objects are made.
2. Classes are defined by the user; the class provides the basic structure for an object.

3. It consists of data members and method members that are used by the instances of the class.

4. In Python, a class is defined by a keyword Class.

5. Syntax: class class_name;

6. For example: Fruit is a class, and apple, mango and banana are its objects. Attribute of these objects are
color, taste, etc.

In the given example, we have created a class Student that contains two methods: fill_details and print_details. The
first method fill_details takes four arguments: self, name, branch and year. The second method print_details takes
exactly one argument: self.

Objects:

1. An object is an instance of a class that has some attributes and behavior.

2. The object behaves according to the class of which it is an object.

3. Objects can be used to access the attributes of the class.

4. The syntax of creating an object in Python is similar to that for calling a function.

5. Syntax :
obj_name = class_name()
For example:
s1 = Student ()
In the given example, Python will create an object s1 of the class student.
Q4. Explain data encapsulation with example.

Ans.
1. In Python programming language, encapsulation is a process to restrict the access of data members. This
means that the internal details of an object may not be visible from outside of the object definition.

2. The members in a class can be assigned in three ways i.e., public, protected and private.

3. If the name of a member is preceded by single underscore, it is assigned as a protected member.

4. If the name of a member is preceded by double underscore, it is assigned as a private member.

5. If the name is not preceded by anything then it is a public member.

Name Notation Behavior

varname Public Can be accessed from anywhere

_varname Protected They are like the public member buy they cannot be directly accessed from outside

__varname Private They cannot be seen and accessed from outside the class
Q5. What do you mean by multiple inheritance? Explain in detail.

Ans.

1. In multiple inheritance, a subclass is derived from more than one base class.

2. The subclass inherits the properties of all the base classes.

3. In Fig. subclass C inherits the properties of two base classes A and B.


4. Syntax

UNIT-5 : ITERATORS & RECURSION | Python Programming Important Questions

Last Updated on: April 4, 2023 by Bachelor Exam

Table Of Contents

1 Q1. Explain Tower of Hanoi problem in detail OR Explain iterator. Write a program to demonstrate the Tower of
Hanoi using function.

2 Q2.Differentiate between recursion and iteration. OR Discuss and differentiate iterators and recursion. Write a
program for recursive Fibonacci series.

3 Q3.Define recursion. Also, give example.

4 Q4. Discuss sorting and merging. Explain different types of sorting with example. Write a Python program for Sieve
of Eratosthenes.]

5 Q5. Discuss binary search in Python.


6 Python Programming Important Links:

Q1. Explain Tower of Hanoi problem in detail OR Explain iterator. Write a program to demonstrate the Tower of
Hanoi using function.

Ans.

Iterator:

1. An iterator is an object that contains a countable number of values.

2. An iterator is an object that can be iterated upon, meaning that we can traverse through all the values.

3. Python iterator, implicitly implemented in constructs like for-loops, comprehensions, and python generators.

4. Python lists, tuples, dictionary and sets are all examples of in-built iterators.

5. These types are iterators because they implement following methods:

1. __iter: This method is called on initialization of an iterator. This should return an object that has a
next() method.

2. next() (or_next_): The iterator next method should return the next value for the iterable. When an
iterator is used with a ‘for in’ loop, the for loop implicitly calls next() on the iterator object. This
method should raise a StopIteration to signal the end of the iteration.

3. For example:


Tower of Hanoi problem :

1. Tower of Hanoi is a mathematical puzzle which consists of three rods and a number of disks of different sizes,
which can slide onto any rod.

2. The puzzle starts with the disks in a neat stack in ascending order of size on one rod, the smallest at the top,
thus making a conical shape.

3. The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules:

1. Only one disk can be moved at a time.

2. Each move consists of taking the upper disk from one of the stacks and placing it on top of another
stack.

3. A disk can only be moved if it is the uppermost disk on a stack.

4. No disk may be placed on top of a smaller disk.


5. 3 Dick

4.
Q2.Differentiate between recursion and iteration. OR Discuss and differentiate iterators and recursion. Write a
program for recursive Fibonacci series.

Ans.

Property Recursion Iteration

Definition Function calls itself A set of instruction repeatedly executed

Application For functions For Loops

When the termination condition for the


Termination Through base case, where there will be no function call
ceases to be satisfied

Used when code size need to be small and time complexity is Used when time complexity needs to be
Usage
not an issue against an expanded code size

Code size Smaller code size Larger code size

Time Relatively Lower time complexity (gene


Very high (generally exponential) time complexity
complexity polynomial logarithmic)

The stack is used to store the set of new local variables and
Stack Does not use stack
parameters each time the function is called.

Overhead Recursion possesses the overhead of repeated function calls No overhead of repeated function call

Speed Slow in execution Fast in execution

Q3.Define recursion. Also, give example.

Answer

1. In Python, recursion occurs when a function is defined by itself.


2. When a function calls itself, directly or indirectly, then it is called a recursive function and this phenomenon is
known as recursion.

3. Recursion is the property how we write a function. A function which performs the same task can be written
either in a recursive form or in an iterative form.

4. Recursion is the process of repeating something self-similar way.

5. For example:

Q4. Discuss sorting and merging. Explain different types of sorting with example. Write a Python program for Sieve
of Eratosthenes.]

Ans.

Sorting:

1. Sorting refers to arranging data in a particular order.

2. Most common orders are in numerical or lexicographical order.

3. The importance of sorting lies in the fact that data searching can be optimized to a very high level, if data is
stored in a sorted manner.

4. Sorting is also used to represent data in more readable formats.

Merging:

1. Merging is defined as the process of creating a sorted list/array of data items from two other sorted array/list
of data items.

2. Merge list means to merge two sorted list into one list.

Code for merging two lists and sort it :

a=[ ]

c=[ ]
Different types of sorting are:

 Bubble sort: It is a comparison-based algorithm in which each pair of adjacent elements is compared and the
elements are swapped if they are not in order.

 Merge sort:

 Merge sort is a divide and conquer algorithm. It divides input array in two halves, calls itself for the
two halves and then merges the two sorted halves.

 The merge() function is used for merging two halves.

 The merge(arr, l, m, r) is key process that assumes that arr[l..m] and arr[m+1..r] are sorted and
merges the two sorted sub-arrays into one.

 Selection sort:

 The selection sort algorithm sorts an array by repeatedly finding the smallest element (considering
ascending order) from unsorted list and swapping it with the first element of the list.

 The algorithm maintains two sub-arrays in a given array:

 The sub-array which is already sorted.

 Remaining sub-array which is unsorted.

 In every iteration of selection sort, the smallest element from the unsorted sub-array is picked and
moved to the sorted sub-array.

 Higher order sort:

 Python also supports higher order functions, meaning that functions can accept other functions as
arguments and return functions to the caller.

 Sorting of higher order functions:

 In order to defined non-default sorting in Python, both the sorted() function and .sort()
method accept a key argument.

 The value passed to this argument needs to be a function object that returns the sorting key
for any item in the list or iterable.
 For example: Consider the given list of tuples, Python will sort by default on the first value in each
tuple. In order to sort on a different element from each tuple, a function can be passed that returns
that element.

 Insertion sort:

 Insertion sort involves finding the right place for a given element in a sorted list. So in beginning we
compare the first two elements and sort them by comparing them.

 Then we pick the third element and find its proper position among the previous two sorted
elements.

 This way we gradually go on adding more elements to the already sorted list by putting them in their
proper position.

Program:
Q5. Discuss binary search in Python.

Ans.

1. Binary search follows a divide and conquer approach. It is faster than linear search but requires that the array
be sorted before the algorithm is executed.

2. Binary search looks for a particular item by comparing the middle most item of the collection. If a match
occurs, then the index of item is returned.

3. If the middle item is greater than the item, then the item is searched in the sub-array to the left of the middle
item.

4. Otherwise, the item is searched for in the sub-array to the right of the middle item.

5. This process continues on the sub-array as well until the size of the sub-array reduces to zero.
6. Code:

Python Programming Question Paper -2021-22 |with solution

Last Updated on: July 5, 2023 by Bachelor Exam

Table Of Contents

1 Section-A (Important Question in Pyhton Programming)

2 Section-B Long Question Answer | Question Paper-2021-22

3 Section-c | important Question in Python Programming

4 Python Programming Important Links:

Section-A (Important Question in Pyhton Programming)

Q Explain the Programming cycle for Python?


Ans.

1. Python’s programming cycle is dramatically shorter than that of traditional programming Cycle.

2. In Python, there are no compile or link steps.

3. Python programs simply import modules at runtime and use the objects they contain. Because of this,
Python programs run immediately after changes are made.

4. In cases where dynamic module reloading can be used, it is even possible to change and reload parts of a
running program without stopping it at all.

5. Since Python is interpreted, there is a rapid turnaround after program changes. And because Python’s parser
is embedded in Python-based systems, it is easy to modify programs at runtime.

6. Fig. 1.1.1 shows Python’s impact on the programming cycle. Python’s programming cycle

Qb What will be the output of the following Python code?

Ans: Syntax error at else.


Correction in question:
Qc. What will be the output of the following Python code?

def cube(x):

return x * x * x

× = cube(3)

print(x)

Ans. Output: 27

Qd. How do we define an Interface for an ADT? OR Explain ADT interface in Python programming?

Ans:

1. ADT only defines as what operations are to be performed but not how these operations will be implemented.

2. It does not specify how data will be organized in memory and what algorithms will be used for implementing
the operations.

3. It is called “abstract” because it gives an implementation-independent vIew.

4. The process of providing only the essentials and hiding the details is known as abstraction.

5. The user of data type does not need to know how that data type is implemented, for example, we have been
using primitive values like int, float, char data types only with the knowledge that these data type can
operate and be performed on without any idea of how they are implemented.

6. So, a user only needs to know what a data type can do, but not how it will be implemented.
Qe. How do you perform a search in Python?

Ans: Searching in Python can be done in the following two ways:

 1. Linear search

 2. Binary search

Section-B Long Question Answer | Question Paper-2021-22

Qa.What do you mean by Python IDE? Explain in detail.

Ans:

1. IDE is a software package that consists of several tools for developing and testing the software.

2. An IDE helps the developer by automating the process.

3. IDEs integrate many tools that are designed for SDLC.

4. IDEs were introduced to diminish the coding and typing errors.

5. Some of the Python IDEs are:

1. PyCharm: PyCharm assists the developers to be more productive and provides smart suggestions. It saves
time by taking care of routine tasks, hence increases productivity.

1. Features of PyCharm:

1. It has smart code navigation, good code editor, a function for quick refactoring.

2. The integrated activities with PyCharm are profiling, testing, debugging, remote
development, and deployments.

3. PyCharm supports Python web development frameworks, Angular JS, JavaScript, CSS, HTML
and live editing functions.

2. Spyder: Spyder is widely used for data science works. It is mostly used to create a secure and scientific
environment for Python. Spyder Python uses PyQt (Python plug-in) which a developer can add as an
extension.

1. Features of Spyder:

1. It has good syntax highlighting and auto code completion features.

2. Spyder Python explores and edits variables directly from GUI.


3. It performs very well in multi-language editor.

3. PyDev: It is an external plug-in for Eclipse and is very popular as a Python interpreter.

1. Features of PyDev:

1. PyDev has strong parameters like refactoring, debugging, type hinting, code analysis, and
code coverage function.

2. PyDev supports tokens browser, PyLint integration, interactive console, remote debugger,
Unittest integration, etc.

4. IDLE: IDLE is a basic IDE mainly used by beginner level developers.

1. IDLE Python is a cross-platform IDE, hence it increases the flexibility for users.

2. It is developed only in Python in collaboration with Tkinter

3. GUI toolkit.

4. The feature of multi-window text editor in IDLE has some great functions like smart indentation, call
tips, Python colorizing, and undo option.

5. It also comes with a strong debugger along with continuous breakpoints, local spaces, and global
view.

6. It supports browsers, editable configurations, and dialog boxes.

5. Visual studio: It enables development for various platforms and has its own marketplace for extensions.

1. Features of visual studio:

1. It supports Python coding in visual studio, debugging, and other activities.

2. It has both paid and free versions in the market with great features.

Qb. How can you randomize the items of a list in place in Python ?

Ans: The method shuffle() can be used to randomize the items of a list in place However, this function is not
accessible directly and therefore we need to import or call this function using a random static object.

Syntax: shuffle (list_name)

Here. ‘list name’ is passed as a parameter which could be a list or tuple. The shuffle() returns a reshuffled list of
items.

For example:

import random

list = [20, 16, 10, 5];

random.shuffle(list)

print “Reshuffled list:”, list random.shuffle(list)

print “Reshuffled list:, list

Output :

Reshuffled list: (16, 10, 5, 20]

Reshuffled list : (5, 20, 10, 16]


Qc. Explain Tuples and Unpacking Sequences in Python Data Structure.

Ans:

1. Tuples are the sequence or series values of different types separated by commas (,).

2. Values in tuples can also be accessed by their index values, which are integers starting from 0.

For example:

The names of the months in a year can be defined in a tuple:

>>> months = (January, february, March, April, May, June, July,

August, September’, ‘October’, November, December)

Creating tuples in Python:

1. To create a tuple, all the items or elements are placed inside parentheses separated by commas and assigned
to a variable.

2. Tuples can have any number of different data items (that is, integer, float, string, list, etc.).

For examples:

1. A tuple with integer data items:

>>> tuple = (4, 2, 9, 1)

>>> print tuple

(4, 2, 9, 1) # Output

2. A tuple with items of different data types:

>>>tuple_mix = (2, 30, “Python”, 5.8, “Program”)

>>>print tuple_mix

(2, 30, ‘Python’, 5.8, ‘Program’) # Output

3. Nested tuple:

>>>nested_tuple = (“Python”, [1, 4, 2], [‘”john”, 3.9])

>>> print nested_tuple

(Python’, [1, 4, 2], [john’, 3.91) # Output

4. Tuple can also be created without parenthesis :

>>>tuple = 4.9, 6, ‘house’

>>>print tuple

(4.9, 6, house’)

# Output

Unpacking sequences:

1. Unpacking allows to extract the components of the sequence into individual variables.

2. Several different assignments can be performed simultaneously.


3. We have multiple assignments in Python where we can have multiple LHS assigned from corresponding
values at the RHS. This is an example of unpacking sequences.

4. There is one restriction, the LHS and RHS must have equal length. That is, every value that is created at RHS
should be assigned to LHS.

5. Strings and tuples are example of sequences. Operations applicable on sequences are: Indexing, repetition,
concatenation.

For example:

>>> student

(Aditya’, 27, (Python’, ‘Abha’, 303))

>>> name, roll, redcourse = student

>>> name

Output: Aditya

>>> roll

27

>>> redcourse

(Python’, ‘Abha’, 303)

6. Since strings are also sequences, we can also get individual characters in the string using unpacking
operation.

For example:

>>> x1, ×2, x3, ×4 = ‘Abha’

>>> print (×1, ×2, ×3, ×4)

Abha

Qd. What are file input and output operations in Python Programming?

Ans. Following are the file I/O operations in Python:

A. Open operation:

1. Python has a built-in open () function to open files from the directory.

2. Two arguments that are mainly needed by the open () function are:.

1. File name: It contains a string type value containing the name of the file which we want to access.

2. Access_mode: The value of access_mode specifies the mode in which we want to open the file, i.e.,
read, write, append etc.

3. Syntax:

file_object = open(file_name [, access_mode])

For example:

>>>f= open (“test.txt”)

#Opening file current directory


>>>f= open (“C:/Python27/README.txt”)

#Specifying full path #Output

>>>f

<open file ‘C:/Python27/README. txt’, mode ‘r’ at 0x02BC5128>

#Output

B. Close operation:

1. ‘When the operations that are to be performed on an opened file are finished, we have to close the file in
order to release the resources.

2. Python comes with a garbage collector responsible for cleaning up the unreferenced objects from the
memory, we must not rely on it to close a file.

3. Proper closing of a file frees up the resources held with the file.

4. The closing of file is done with a built-in function close 0).

5. Syntax:

fileObject. close ()

For example:

# open a file

>>> f=open (“test. txt”, “wb”)

# perform file operations

>>> f. close) # close the file

C. Write operation :

1. After opening a file, we have to perform some operations on the file. Here we will perform the write
operation.

2. In order to write into a file, we have to open it with w mode or a mode, on any writing-enabling mode.

3. We should be careful when using the w mode because in this mode overwriting persists in case the file
already exists.

For example:

# open the file with w mode

>>>f= open (*C :/Python27/test.txt”, “w”)

# perform write operation

>>>f. write (writing to the file line 1/n’)

>>>f. write (writing to the file line 2/n’)

>>>f. write (writing to the file line 3/n’)

>>>f. write (writing to the file line 4′)

# close the file after writing

>>> f.close ()
The given example creates a file named test. txt if it does not exist, and overwrites into it if it exists. If we open the
file, we will find the following content in it.

Output :

Writing to the file line 1

Writing to the file line 2

Writing to the file line 3

Writing to the file line 4

D. Read operation:

1. In order to read from a file, we must open the file in the reading mode (r mode).

2. We can use the read (size) method to read the data specified by size.

3. If no size is provided, it will end up reading to the end of the file.

4. The read() method enables us to read the strings from an opened file.

5. Syntax:

file object. read ([size])

For example:

# open the file

>>> f= open (“C:/Python27/test.txt”, “y”)

>>>f. read (7) # read from starting 7 bytes of data

‘writing’ # Output

>>>f. read (6) # read next 6 bytes of data to the

# Output

Qe. Solve the Tower of Hanoi problem for n= 3 disk and show all the steps.

Ans: Tower of Hanoi is a mathematical puzzle where we have three rods and n disks. The objective of the puzzle is to
move the entire stack to another rod, obeying the following rules:

 Only one disk can be moved at a time.

 Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack i.e.,
a disk can only be moved if it is the uppermost disk on a stack.

 No larger disk may be placed on top of a smaller disk.


Section-c | important Question in Python Programming

3a. Write a program in Python to execute the Selection sort algorithm.

Ans.

1. The selection sort algorithm sorts an array by repeatedly finding the smallest element (considering ascending
order) from an unsorted list and swapping it with the first element of the list.

2. The algorithm maintains two sub-arrays in a given array:

1. The sub-array which is already sorted.

2. Remaining sub-array which is unsorted.


3. In every iteration of selection sort, the smallest element from the unsorted sub-array is picked and moved to
the sorted sub-array.

4. Code:

Def slectionSort(nlist):

for fillslot in range(len(nlist) - 1, 0, - 1) :

maxpos = 0

for location in range(1, fillslot + 1) :

if nlist [location]>nlist [maxpos] :

maxpos = location

temp = nlist [fillslot]

nlist[fillslot] = nlist[maxpos]

nlist [maxpos] = temp

nlist = [14, 46, 43, 27, 57, 41, 45, 21, 70]

selectionSort(nlist)

print (nlist)

Output :

[14, 21, 27, 41, 43, 45, 46, 57, 70]

Output : [14, 21, 27, 41, 43, 45, 46, 57, 70]

5. Time complexity:

 i.Best case: O(n2)

 ii.Worst case: O(n2)

 iii. Average case: O(n2)

3b. Explain why Python is considered an interpreted language.

Ans. 1. Python is called an interpreted language because it goes through an interpreter, which turns code we write
into the language understood by computer’s processor.

2. Python is an interpreted language, which means the source code of a Python program is converted into bytecode
that is then executed by the Python virtual machine.

3. This distinction makes for two important points :

a. Python code is fast to develop: As the code is not needed to be compiled and built, Python code can be readily
changed and executed .This makes for a fast development cycle.

b. Python code is not as fast in execution: Since the code is not directly compiled and executed and an additional
layer of the Python virtual machine is responsible for execution, Python code runs a little slow as compared to
conventional languages like C, C++, etc.

4a. Write a Python program to construct the following pattern, using a nested for loop.
*

**

***

****

*****

****

***

**

Ans. Program :

n=5

for i in range(n):

for j in ranged (i):

print(“*”,end=””)

print()

for i in range (n):

for j in range (i,n):

print(“*”,end=””)

print()

4b Write a Program to display fibonacci sequence for n terms.

>>> number = int (input ("Enter the value for × (where x > 2) ?")

# first the terms

>>> x1 = 0

>>> x2 = 1

>>> count = 2

# check if the number of terms is valid

>>> if numbers < = 0 :

print ("Please enter positive integer")

elif numbers == 1:

print ("Fibonacci sequence is :")

print (x1)

else:

print ("Fibonacci sequence is :")


print (x1,"",", ×2)

while count < numbers:

xth = x1 + x2

print (xth)

#update values

xl = x2

×2 = xth

count + = 1

Output :

Enter the value for n (where n > 2) ? 10

Fibonacci sequence:

0, 1, 1, 2, 3, 5, 8, 13, 21, 34

5a. Write a Python program to change a given string to a new string where the first and last chars have been
exchanged.

Ans:

defchange_sring(str1):

return stril-1:] + stri[1:-1] + strif:1]

print(change_sring(abed’))

Output : dbca

5b. Write a Python program to add an item in a tuple.

Ans: Creating tuples in Python:

1. To create a tuple, all the items or elements are placed inside parentheses separated by commas and assigned
to a variable.

2. Tuples can have any number of different data items (that is, integer, float, string, list, etc.).

For examples:

1. A tuple with integer data items:

>>> tuple = (4, 2, 9, 1)

>>> print tuple

(4, 2, 9, 1)# Output

2. A tuple with items of different data types:

>>>tuple_mix = (2, 30, “Python”, 5.8, “Program”)


>>>print tuple

(2, 30, ‘Python’, 5.8, ‘Program’) # Output

3. Nested tuple:

>>>nested_tuple = (“Python”, [1, 4, 2],[“john”,3.9])

>>>print nested_tuple

(‘Python’, [1, 4, 2], [‘john’,3.9]) # Output

4. Tuple can also be created without parenthesis:

>>>tuple = 4.9, 6, ‘house’

>>>print tuple (4.9, 6, ‘house’) # Output

6a. How to create and import a module in Python?

Ans.

Create a Module:To create a module just save the code we want in a file with the file extension .py.

For example:

Save the given code in a file named mymodule.py def greeting(name);

print(“Hello,” + name)

Importing a module: Now we can use the newly created module or built-in module, by using the import statement:

For example:

Import the module named mymodule, and call the greeting function:

importmymodule

mymodule.greeting(“Aditya Kumar”)

Output: Hello, Aditya Kumar

Qb. Explain the algorithm Sieve of Eratosthenes used in Python Programming.

Ans:

1. Sieve of Eratosthenes is a simple and ingenious ancient algorithm for finding all prime numbers up to any
given limit.

2. It does so by iteratively marking as composite (i.e., not prime) the multiples of each prime, starting with the
first prime number, 2.

3. The multiples of a given prime are generated as a sequence of numbers starting from that prime, with
constant difference between them that is equal to that prime.

4. Following is the algorithm to find all the prime numbers less than or equal to a given integer n by
Eratosthenes’ method:

1. Create a list of consecutive integers from 2 to n : (2, 3, 4, …, n).

2. Initially, let p equal 2, the first prime number.


3. Starting from p°, count up in increments of p and mark each of these numbers greater than or equal
to p? itself in the list. These numbers will be p(p+1), p(p+2), p(p+3), etc.

4. Find the first number greater than p in the list that is not marked. If there was no such number, stop.
Otherwise, let p now equal this number (which is the next prime), and repeat from step c.

7a. Write a Recursive function in python Binary Search (Arr, I, R, X to search the given element X to be searched
from the List Arr having R elements, where 1 represent lower bound and R represents the upper bound.

Ans:

1. Binary search follows a divide and conquer approach. It is faster than linear search but requires that the array
be sorted before the algorithm is executed.

2. Binary search looks for a particular item by comparing the middle most item of the collection. If a match
occurs, then the index of item is returned.

3. If the middle item is greater than the item, then the item is searched in the sub-array to the left of the middle
item.

4. Otherwise, the item is searched for in the sub-array to the right of the middle item.

5. This process continues on the sub-array as well until the size of the sub-array reduces to zero.

6. Code:

def binarysearch(arr, 1, r, x) :

while 1 <=r:

mid = 1 + (r - 1)/2;

#Check if x is present at mid

if arr [mid] == x:

return mid

# If x is greater, ignore left half

elif arr [mid] < x :

1= mid + 1

# If x is smaller, ignore right half

else:

r = mid - 1

# If we reach here, then the element was not present

return - 1

# Test array

arr = [2, 3, 4, 10, 40]

X = 10

# Function call

result = binarySearch(arr, 0, len(arr) - 1, x)


if result! = - 1:

print "Element is present at index % d" % result

else:

print "Element is not present in array"

Output:

Element is present at index 3

7b. Explain the terms Merge List and Merge Sort in Python Programming.

Ans.

Merge List:

1. Merging is defined as the process of creating a sorted list/array of data items from two other sorted array/list of
data items.

2. Merge list means to merge two sorted list into one list.

Code for merging two lists and sort it:

a=[]

c=[]

n1=int(input("Enter number of elements:")) ;

for i in range(1, n1+1):

b=int (input("Enter element:"))

a.append(b)

n2=int(input("Enter number of elements:”))

for i in range(1, n2+1):

d=int(input("Enter element:"))

c.append(d)

new=a+c

new.sort()

print("Sorted list is:", new)

Merge Sort :

1. Merge sort is a divide and conquer algorithm. It divides input array in two halves, calls itself for the two
halves and then merges the two sorted halves.

2. The merge() function is used for merging two halves.

3. The merge(arr, I, m, r) is key process that assumes that arr[l..m] and arr [m + 1 ..r] are sorted and merges the
two sorted sub-arrays into one.

4. Code:
5.Time Complexity
Recurrence relation of merge sort is given by

Assume n = 2k for some k.

k = log2n

Then, I(n) = n*7(1) + Cn*log2n

Time complexity of Merge sort is On log n) in all three cases (worst, average and best) as merge sort always divides
the array into two halves and take linear time to merge two halves.

You might also like