0% found this document useful (0 votes)
10 views

python QB (1)

Uploaded by

malathitagorecse
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

python QB (1)

Uploaded by

malathitagorecse
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 12

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

GE3151 /PROBLEM SOLVING AND PYTHON PROGRAMMING


YEAR\SEM: I\I BRANCH: ECE

PART-A

UNIT-I
1. Define Algorithm
An algorithm is a finite set of well-defined steps or rules to solve a specific
problem. It outlines a clear process for arriving at a solution. Algorithms are essential
in computer science and mathematics .

2. Distinguish between algorithm and program.


An algorithm is a theoretical concept that describes how to solve a problem.
A program is the actual implementation of that algorithm using a programming
language. Programs execute the steps defined in an algorithm.
3. Define recursion
Recursion is a technique in which a function calls itself to solve a problem. It
divides the problem into smaller, more manageable subproblems. Each call works
towards a base case to terminate the recursion.
4. List the different building blocks of algorithms.
The main building blocks include sequential operations, selection (if-else
statements), iteration (loops), and recursion. These components enable algorithms to
process data efficiently. They help structure the flow of logic.
5. What are flowcharts and list down their advantages?
Flowcharts are graphical representations of processes or algorithms. They
improve clarity and understanding of complex workflows. Advantages include visual
communication, easy debugging, and enhanced documentation.
6. Define an iterative statement.
An iterative statement is a programming construct that repeatedly executes a
block of code based on a condition. It allows for the execution of a loop until a
specified criterion is met. Common examples include "for" and "while" loops.
7. Draw a flowchart to find the maximum among the three numbers. (Description)
Start → Input A, B, C → If A > B and A > C then Max = A → Else if B > C
then Max = B → Else Max = C → Output Max → End. This flowchart helps
visualize the decision-making process.
8. What is the use of algorithm, Flowchart and Pseudocode in the perspective of
problem solving?
They provide structured methodologies to tackle problems effectively.
Algorithms define the logical steps, flowcharts visualize processes, and pseudocode
clarifies logic without language syntax. Together, they enhance problem-solving
efficiency.
9. What is a Pseudocode?
Pseudocode is a simplified, informal way to describe an algorithm using plain
language and basic programming constructs. It focuses on the logic rather than
syntax. Pseudocode is useful for planning and understanding algorithms before
coding.
10.What are the benefits of pseudocode?
Pseudocode is easy to read and understand, making it accessible to those
without programming expertise. It helps clarify logic and structure before actual
implementation. Additionally, it is language-agnostic, promoting versatility in
problem-solving.

11. What are Built-in Data Types in Python?


Built-in data types in Python include:
 int (integers)
 float (floating-point numbers)
 str (strings)
 list (lists).

12. What is a Variable?


A variable is a named location in memory that stores data and can change
during program execution. It is used to hold values that can be referenced and
manipulated.

13. What are Keywords in Python? Give an Example.


Keywords are reserved words in Python that have special meanings and
cannot be used as identifiers. Examples include if, else, for, and def.

14. Differentiate between Compiler and Interpreter.


A compiler translates the entire source code into machine code before
execution, while an interpreter translates and executes code line-by-line at runtime.
Python primarily uses an interpreter.

15. What is an Expression? Provide an Example.


An expression is a combination of values, variables, and operators that
computes to a single value. For example, 3 + 5 * 2 evaluates to 13

16. What is a Tuple in Python?


A tuple is an immutable sequence of elements, defined by placing values in
parentheses. For example, my _tuple = (1, 2, 3).

17. What is the Purpose of Functions in Programming?


Functions help in organizing code by encapsulating specific tasks, promoting
code reuse, improving readability, and simplifying debugging.

18. How do you Calculate Average of Three Numbers in Python?


To calculate the average, sum the numbers and divide by three:
Python code:
average = (num1 + num2 + num3) / 3 .

19. Describe the concept of a "solution space."


The solution space is the set of all possible solutions to a problem, from
which the best or most effective solution can be selected.

20. What is an algorithm's time complexity?


Time complexity is a measure of the amount of time an algorithm takes to complete
as a function of the length of the input.

PART B&C

1. State the Towers of Hanoi problem. Outline a solution to the Towers of Hanoi
problem with relevant diagrams.(JAN 2022)
2. i)Discuss about the building blocks of algorithms. (DEC/JAN 2019)
3. ii)Identify the simple strategies for developing an algorithm.(DEC/JAN 2019)
4. i)Draw a flow chart to accept three distinct numbers, find the greatest and print the
result. (JAN 2022)
5. ii)Draw a flow chart to find the sum of the series (JAN 2022)
a. 1+2+3+4+5+……+100.
6. 4. What is recursion ? Write and explain a python program to find a factorial of
number using recursion.(APRIL/MAY 2022)
7. 5. i)What is an algorithm? Summarize the characteristics of a good algorithm.
(APRIL/MAY 2019)
8. ii)Outline the algorithm for displaying the first n odd numbers. (APRIL/MAY 2019)
9. 6.Explain in detail about the Notation of Algorithm.(NOV/DEC 2022)

Unit-II

1. List any four build in data types in python.


Integer, Float, String, and List are common built-in data types. They allow for
various types of data manipulation.

2. What are keywords? Give example.


Keywords are reserved words in Python with special meanings. Examples
include if, else, and def.

3. Compare interpreter and compiler. What type of translator is used for python?
An interpreter translates and executes code line-by-line, while a compiler
translates the entire code at once. Python uses an interpreter.

4. State the reasons to divide programs in to functions


Dividing programs into functions enhances code reuse, improves readability,
and simplifies debugging processes.

5. What is a variables?
A variable is a named memory location that stores a value, which can be
changed during program execution.

6. Define expression with example


An expression is a combination of values and operators that evaluates to a
single value, such as 3 + 5.

7. Outline the logic to swap the content of two identifiers without using third
variable
Use arithmetic to swap without a third variable:
a = a + b, b = a - b, a = a - b.

8. Write a python script to calculate the average of three numbers.


nums = [float(input("Enter three numbers: ")) for _ in range(3)]
average = sum(nums) / len(nums)
print("Average:", average)

9. Give the precedence of operators in python.


Operator precedence from highest to lowest is:
Parentheses, Exponentiation, Multiplication/Division, Addition/Subtraction.

10. What is a tuple? How literals of type tuple are written? Give example.
A tuple is an immutable ordered collection defined with parentheses, like
my_tuple = (1, 2, 3).

11. What is a list in Python?


A list is a mutable, ordered collection of items, defined using square brackets,
e.g., my_list = [1, 2, 3].

12. How do you access elements in a Python dictionary?


Elements in a dictionary are accessed using keys, e.g., my_dict['key'] retrieves
the value associated with 'key'.

13. What is a string in Python?


A string is an immutable sequence of characters, defined with single or double
quotes, e.g., my_string = "Hello".

14. What is a set in Python?


A set is an unordered collection of unique elements, defined using curly
braces, e.g., my_set = {1, 2, 3}.

15. Explain the purpose of the len() function.


The len() function returns the number of items in an object, such as strings,
lists, or dictionaries.

16. What are list comprehensions in Python?


List comprehensions provide a concise way to create lists using a single line of
code, e.g., [x**2 for x in range(5)].

17. What is exception handling in Python?


Exception handling allows programmers to manage errors gracefully using try,
except, and finally blocks.

18. How can you create a function in Python?


A function is created using the def keyword followed by the function name
and parentheses, e.g., def my_function():.

19. What is the difference between == and is in Python?


== checks for value equality, while is checks for identity (whether two
variables refer to the same object).

20. What is a lambda function?

A lambda function is an anonymous, small function defined with the lambda


keyword, often used for short, single-expression functions.

PART B&C

1. Explain in detail about precedence of python operators and the associativity of python
operators. (NOV/DEC 2022)
2. Write and explain the python program to swap two numbers with and without temporary
variables. (APRIL/MAY 2022)
3. What is the role of an interpreter? Give a detailed note on python interpreter and
interactive mode of operation. Explain how python works in interactive mode and script
mode with examples. (NOV/DEC 2022)
4. What are statements and expressions? How are they constructed from variable and
expressions in Python? (APRIL/MAY 2019)
5. Explain about various datatypes used in python with examples. (NOV/DEC 2021)
6. Name the types of operators supported by python and outline any two with an example.
(NOV/DEC 2022)

UNIT-III
1. Name the two types of interative statements supported by python
Python supports for loops and while loops for iteration. for loops iterate over a
sequence, while while loops continue until a condition is false.

2. Differentiate while loop and for loop


A while loop repeats until a specified condition is false, while a for loop
iterates over a sequence or collection. for loops are generally used when the number
of iterations is known.

3. Do loop statements have else clause? When will it be executed?


Python does not have a traditional "do-while" loop, but while loops can have
an else clause. The else block executes when the loop terminates normally (not via a
break).

4. List the various types of operators in python.


Python has several operators, including arithmetic, relational, logical, bitwise,
assignment, and identity operators. Each type performs different operations on data.

5. What is slice? Give example.


Slicing refers to accessing a portion of a sequence (like a list or string). For
example, my_list[1:4] retrieves elements from index 1 to 3.

6. Define parameter and argument.


A parameter is a variable in a function definition, while an argument is the
value passed to the function when called. Parameters specify what inputs a function
accepts.

7. Define function and list any two advantages of using the function.
A function is a reusable block of code that performs a specific task.
Advantages include code reusability and improved readability, as well as easier
debugging.

8. Differentiate break and continue.


The break statement exits the loop entirely, while continue skips the current
iteration and proceeds to the next one. Both are used to control loop execution.

9. Write a python program to print sum of cubes of the values of n variables.


n = int(input("Enter the number of variables: "))
total = sum(int(input("Enter a number: "))**3 for _ in range(n))
print("Sum of cubes:", total)

10. What are the identity operators used in python?


The identity operators in Python are is and is not. They check whether two
variables refer to the same object in memory.
11. What is a class in Python?
A class is a blueprint for creating objects that encapsulates data (attributes)
and behavior (methods) related to that data.
12. Define inheritance in Python.
Inheritance allows a class (child) to inherit attributes and methods from
another class (parent), promoting code reuse and organization.

13. What is a module in Python?


A module is a file containing Python code (functions, classes, variables) that
can be imported and used in other Python programs.

14. Explain the purpose of the __init__ method.


The __init__ method is a special constructor method in Python classes that
initializes object attributes when a new object is created.

15. What is polymorphism in Python?


Polymorphism allows different classes to define methods that share the same
name but behave differently based on the calling object’s class.

16. How do you handle exceptions in Python?


Exceptions are handled using try, except, and optionally finally blocks,
allowing graceful recovery from runtime errors.

17. What is a lambda function?


A lambda function is an anonymous function defined with the lambda
keyword, used for short, single-expression functions, e.g., lambda x: x + 1.

18. Define a decorator in Python.


A decorator is a function that modifies or enhances another function’s
behavior without permanently changing it, often used for logging or access control.

19. What is the purpose of the self keyword in a class?


The self keyword refers to the instance of the class itself, allowing access to its
attributes and methods from within class methods.

20. Explain the difference between deep copy and shallow copy.
A shallow copy creates a new object but inserts references to the original
object's elements, while a deep copy creates a new object and recursively copies all
elements, resulting in independent copies.

PART B & C
1. Write a python program to find the square root of a number without using inbuilt function
and explain the same. (NOV/DEC 2022)
2. Write a python program for linear search and binary search and explain its implementation
in detail. (NOV/DEC 2022)
3. List the three types of conditional statements and explain them. (DEC/JAN 2019)
4. i) Python strings are immutable. Justify with an example. (DEC/JAN 2019)
ii) What is difference between break and continue in python? Explain with suitable
examples. (APRIL/MAY 2022)
5. Outline about function definition and function call with an example. (APRIL/MAY 2019)
6. What is string function in python? Explain any three python string methods with an
example. (APRIL/MAY 2022)

UNIT-IV
1. What is a list? How lists differ from tuples?
A list is a mutable, ordered collection of items defined with square brackets,
e.g., my_list = [1, 2, 3]. Unlike tuples, lists can be modified (items can be added or
removed), while tuples are immutable.

2. Relate strings and lists.


Both strings and lists are sequences in Python, allowing indexing and slicing.
However, strings are immutable collections of characters, while lists can hold varied
data types and are mutable.

3. Why list is a dynamic mutable type?


Lists are dynamic because their size can change during program execution;
items can be added or removed. They are mutable, meaning existing elements can
be modified.

4. What is meant by cloning?


Cloning refers to creating a copy of an object, ensuring that changes to the
copy do not affect the original. In Python, this can be done using the copy() method
or the copy module.

5. What is tuples? Give examples.


A tuple is an immutable ordered collection of elements defined with
parentheses, e.g., my_tuple = (1, 2, 3) or my_tuple = ('a', 'b', 'c').

6. Can function return tuples? If yes give example.


Yes, a function can return tuples. For example:
def return_tuple():
return (1, 2, 3)

7. Define dictionary? What is the main use of a dictionary?


A dictionary is an unordered collection of key-value pairs, defined with curly
braces, e.g., my_dict = {'a': 1, 'b': 2}. The main use is to enable fast lookups based
on unique keys.

8. Why python dictionaries are called mappings?


Python dictionaries are called mappings because they map unique keys to
values, allowing efficient retrieval of values based on their associated keys.

9. Give a function that can take a value and return the first key mapping to that
value in a dictionary.
def get_key_by_value(d, value):
for k, v in d.items():
if v == value:
return k
return None
10. Let list=[‘a’,’b’,’c’,’d’,’e’,’f’]. find the following.
(a)list [1:3] (b) t[:4] (c) t[3:]
(a) list[1:3] returns ['b', 'c'].
(b) t[:4] returns ['a', 'b', 'c', 'd'] (assuming t is defined as list).
(c) t[3:] returns ['d', 'e', 'f'].

11. What is file handling in Python?


File handling refers to the operations performed on files, such as reading,
writing, and closing files, allowing data storage and retrieval.

12. How do you open a file in Python?


A file is opened using the open() function, specifying the file name and mode,
e.g., file = open('myfile.txt', 'r') for reading.

13. What are the different modes for opening a file?


Common modes include 'r' (read), 'w' (write), 'a' (append), and 'r+' (read and
write). Each mode specifies how the file will be accessed.

14. How do you read the entire content of a file?


You can read the entire content of a file using the read() method, e.g., content
= file.read(). Ensure the file is opened in read mode.

15. What is exception handling?


Exception handling is a mechanism to manage errors gracefully in a program
using try, except, and finally blocks, preventing program crashes.

16. How do you handle multiple exceptions in Python?


Multiple exceptions can be handled by specifying multiple except clauses or
using a tuple, e.g., except (TypeError, ValueError):.

17. What is the purpose of the finally block?


The finally block is executed regardless of whether an exception occurs,
allowing for cleanup actions such as closing files or releasing resources.

18. How can you write to a file in Python?


To write to a file, open it in write mode using open('myfile.txt', 'w') and use
the write() method, e.g., file.write('Hello, World!').

19. What is the difference between read() and readline()?


read() reads the entire file content as a single string, while readline() reads one
line at a time, returning it as a string.

20. What are context managers in Python?


Context managers, implemented using the with statement, ensure proper
resource management, automatically handling file closure and cleanup when done.

PART B &C
1. Demonstrate with the code various operation that can be performed on Tuples.
(APRIL/MAY2018)
2. Define python lists. How to add the elements in the list. Explain with suitable example
programs. (APRIL/MAY2022)
3. Write a python program to create a Dictionary and sort the content based on values in
reverse order. (JANUARY2022)
4.i) Discuss the different options to traverse a list.
ii) Demonstrate the working of + and *and slice operators in
Python. (DEC/JAN2019)
5. Outline the algorithm and write a python program to sort the number in ascending order
using Merge sort.(APRIL/MAY 2018).
6.Write a python script to sort N numbers using insertion sort. (NOV/DEC 2021)

UNIT-V

1. Write the syntax for opening a file to write in binary mode.


To open a file in binary write mode, use the syntax:
file = open('filename.bin', 'wb')

2. What is command line arguments? How to use the command line arguments
in python?
Command line arguments are inputs passed to a script when executed
from the command line. In Python, they can be accessed using the sys.argv list
from the sys module.

3. What is a module? List their types and give example.


A module is a file containing Python code (functions, classes, variables).
Types include standard modules (e.g., math), third-party modules (e.g., requests),
and user-defined modules.

4. What are exceptions?


Exceptions are runtime errors that occur during program execution, disrupting
the normal flow of the program. They can be handled using try and except blocks.

5. What is format operator?


The format operator % is used for string formatting in Python, allowing
variables to be inserted into strings. Example:
formatted_string = "Hello, %s!" % name

6. What are packages? How to import modules from a packages?


Packages are namespaces that organize related modules into a directory
hierarchy. To import a module, use the syntax:
from package_name import module_name

7. How will you update the content of ome file to another file in python?
Open both files and read content from the source file, then write it to the
destination file:
with open('source.txt', 'r') as src, open('dest.txt', 'w') as dest:
dest.write(src.read())
8. Write methods to rename and delete files.
To rename a file, use os.rename('old_name.txt', 'new_name.txt'). To delete a
file, use os.remove('filename.txt') from the os module.

9. Find the syntax error in the code given:


While true print(‘Hello world’)
while True:
print('Hello world')

10. List any five build in exception in python.


Common built-in exceptions include ValueError, TypeError, IndexError,
KeyError, and ZeroDivisionError.

11. What is Object-Oriented Programming (OOP)?


OOP is a programming paradigm that uses "objects" to represent data and
methods, promoting modularity and reusability. It focuses on encapsulating data and
behavior together.

12. Define a class in Python.


A class is a blueprint for creating objects that encapsulates attributes (data)
and methods (functions). It defines the structure and behavior of the objects created
from it.

13. What is an object?


An object is an instance of a class that contains data and can perform methods
defined in its class. Objects represent real-world entities in a program.

14. Explain encapsulation in OOP.


Encapsulation is the bundling of data and methods that operate on that data
within a single unit (class). It restricts direct access to some components, promoting
data hiding.

15. What is inheritance in Python?


Inheritance allows a new class (child) to inherit attributes and methods from
an existing class (parent). This promotes code reuse and establishes a hierarchical
relationship between classes.

16. Define polymorphism in OOP.


Polymorphism allows different classes to define methods with the same name,
enabling the same function to behave differently based on the object invoking it.

17. What is the self parameter in class methods?


The self parameter refers to the instance of the class itself. It allows access to
attributes and methods of the class from within its methods.

18. What are class attributes and instance attributes?


Class attributes are shared across all instances of a class, while instance
attributes are unique to each object created from the class. Class attributes are defined
directly in the class body.
19. How do you create a constructor in Python?
A constructor is defined using the __init__ method. It initializes object
attributes when a new object is created. Example:
python
Copy code
def __init__(self, attribute):
self.attribute = attribute

20. What is method overriding?


Method overriding occurs when a child class provides a specific
implementation of a method that is already defined in its parent class. This allows
customization of inherited behavior.

PART B&C

1. Why does the python require file handling. Explain opening files in python with all modes.
(APRIL/MAY 2022)
2. Describe how exceptions are handled in python with necessary examples. (DEC/JAN 2019)
3. i) Design a python code to count the number of words in a file. (APRIL/MAY 2018)
ii) How to merge multiple files in to a new file using python. (NOV/DEC 2019)
4. i) Discuss about format operators in file processing. (DEC/JAN 2019)
ii)Write a python program to dump objects to a file using pickle. (NOV/DEC 2022)
5. Write a program to concatenate the content of two files into a single file. Get the input for
two files from the user and concatenate it. (JANUARY 2022)
6. What are modules in python.? How will you import them.? Explain the concept by
creating and importing modules in python. (NOV/DEC2019)

SUBJECT INCHARGE HOD IQAC PRINCIPAL

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy