0% found this document useful (0 votes)
5 views16 pages

2marks Question Bank (Model)

The document provides a comprehensive overview of algorithms, programming concepts, and Python syntax. It includes algorithms for finding the greatest of two numbers, accepting input, and performing operations like swapping variables and linear search. Additionally, it covers topics such as recursion, data structures like lists and dictionaries, and file handling in Python.

Uploaded by

priyaa16svv
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)
5 views16 pages

2marks Question Bank (Model)

The document provides a comprehensive overview of algorithms, programming concepts, and Python syntax. It includes algorithms for finding the greatest of two numbers, accepting input, and performing operations like swapping variables and linear search. Additionally, it covers topics such as recursion, data structures like lists and dictionaries, and file handling in Python.

Uploaded by

priyaa16svv
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/ 16

UNIT 1

1. Write an algorithm and draw a flowchart to


find the greatest of two numbers and print the
result.

Algorithm:

Step 1: Start.
Step 2: Read a, b . / * a, b two numbers */
Step 3: If a>b then /*Checking */
Display “a is the largest number”.
Otherwise.
Display “b is the largest number”.
Flowchart:

2. Distinguish between the algorithm and the


program.
3.Define: Algorithm and Mention the qualities of Good
Algorithm

It is defined as a sequence of instructions that describe a

method for solving a problem. In other words it is a step

by step procedure for solving a problem.

Time - To execute a program, the computer system takes some

amount of time.

The lesser is the time required, the better is the algorithm.

Memory - To execute a program, computer system takes some

amount of memory storage. The lesser is the memory required,

the better is the algorithm.

Accuracy - Multiple algorithms may provide suitable or correct

solutions to a

given problem, some of these may provide more accurate results


than others, such algorithms may be suitable.

4.Define Computational thinking.

Computational thinking is defined as the process of


identifying a clear, defined, step-by-step solution to
a complex problem. Its definition includes breaking
down a problem into smaller pieces, recognizing
patterns and eliminating extraneous details so that
the step-by-step solution can be replicated by
humans or computers.

5.Write an algorithm to accept two numbers, compute the sum and


print the result.

Step 1: Start

Step 2: Declare variables num1, num2 and sum.

Step 3: Read values for num1 and num2.

Step 4: Add num1 and num2 and assign the result to sum.

S sum=num1+num2

Step 5: Display sum


Step 6: Stop

6.Define an iterative statement

In Python, an iterative statement (also known as a loop) is a control flow


statement that allows the programmer to execute a block of code repeatedly
until a certain condition is met. There are two types of iterative statements in
Python:

For loop

While loop

UNIT 2

1.Outline the logic to swap the contents of two identifiers without


using the third variable.

def swap(a, b):


return b, a
a=5
b = 10
a, b = swap(a, b)
print("a:", a)
print("b:", b)

2.State about the Logical operators available in python language


with examples

In Python, Logical operators are used on conditional statements (either True

or False). They perform Logical AND, Logical OR and Logical

operations.

OPERATOR DESCRIPTION SYNTAX

Logical AND: True if


and both the operands are x and y
true

Logical OR: True if


or either of the operands x or y
is true

Logical NOT: True if


not not x
operand is false

3.Write a python code to display the current date and time.

from datetime import datetime

# datetime object containing current date and time


now = datetime.now()

print("now =", now)

# dd/mm/YY H:M:S

dt_string = now.strftime("%d/%m/%Y %H:%M:%S")

print("date and time =", dt_string)

4.Distinguish Keywords and Variables. Give examples.


Keyword Identifier

Keywords are predefined and A particular name generated


specific reserved words, which by the programmer to
hold special meaning. define a variable, structure,
Keywords help in defining any class, or function is called
statement in the program. an identifier.

A keyword begins with In the identifier, the first


lowercase. character may begin with
uppercase, lowercase or
underscores.

It defines the type of entity. It classifies the name of the


entity.

It can only have alphabetical It can have numbers,


characters. alphabetical characters, and
underscores.

It should be lowercase. It can be both upper and


lowercase.

It helps in defining a particular It helps in locating the name


property that subsists in a of the entity.
computer language.

double, int, auto, char, break, Test, count1, high_speed,


and more are examples of etc are examples of
keywords. identifiers.

Are comments executable statements in a python program?


How comments are included in a python program?

Comments in Python are non-executable statements. Comments are intended


human understanding, not for the compiler or PVM. Therefore they are called
non-executable statements. Two types of commenting features are
available in Python: single-line and multiline comments.
Example:
# declare and initialize two variables
num1 = 6
num2 = 9
# print the output
print('This is output')

identify the operand(s) and operator(s) in the following


expression: Sum=a+b
Operators refer to special symbols that perform operations on values and
variables.
operands in python, refer to the values on which the operator operates.

Operator: +,=
Operand: sum,a,b
Unit 3

1.Find the syntax error in the code given: while


True print(“Hello world”)
Correct syntax:
while True:
print(“Hello world”)

2.Write a Python Program for sum of cube of first n


natural numbers

def sumOfSeries(n):
sum = 0
for i in range(1, n + 1):
sum += i * i*i
return sum
n=5
print(sumOfSeries(n))

3.Name the two types of iterative statements


supported by python.

Iteration statements or loop statements allow us to


execute a block of statements as long as the condition is
true.

In Python Iteration (Loops) statements are :

1. While Loop
2. For Loop

While Loop Syntax

while (condition):

statements

For Loop Syntax

for val in sequence:

statements

4.Comment: with an example on the use of local and global variable


with the same identifier name.

The scope of a variable refers to the places that we can see


or access a variable. If we define a variable on the top of the
script or module, the variable is called global variable. The
variables that are defined inside a class or function is called
local variable.
Example:

The function will print the local x, and then the code will print
the global x:

x = 300 #global variable


def myfunc():
x = 200 #local variable
print(x)
myfunc()
print(x)

output:

200
300

5.List out any five string functions


6.Describe Recursion and list out the advantages & disadvantages.

Recursion is the technique of making a function call itself. This


technique provides a way to break complicated problems down into
simple problems which are easier to solve.

Advantages of recursion

 The code may be easier to write


 Reduce unnecessary calling of function.
 Extremely useful when applying the same solution.
 Recursion reduce the length of code.
 It is very useful in solving the data structure problem.
 Stacks evolutions and infix, prefix, postfix evaluations etc.

Disadvantages of recursion

1. Recursive functions are generally slower than non-recursive


function.
2. It may require a lot of memory space to hold intermediate results on
the system stacks.
3. Hard to analyze or understand the code.
4. It is not more efficient in terms of space and time complexity.
5. The computer may run out of memory if the recursive calls are not
properly checked.

7.Write a Python program to perform linear Search using function.


linear search output

a=[20,30,40,50,60,70,89]

print(a)

search=eval(input("enter a element to search:")) for i in range(0,len(a),1):

if(search==a[i]):

print("element found at",i+1)

break

else:

print("not found")

output

[20, 30, 40, 50, 60, 70, 89]

enter a element to search:30

element found at 2

UNIT 4

1.What is a list? How the lists differ from tuples?


Lists are used to store multiple items in a single variable. List
items are ordered, changeable, and allow duplicate values.

List items are indexed, the first item has index [0], the second
item has index [1] etc.

Difference:

 The primary difference between tuples and lists is


that tuples are immutable as opposed to lists which are
mutable.
 Therefore, it is possible to change a list but not a tuple.
 The contents of a tuple cannot change once they have
been created in Python due to the immutability of tuples.

2.Give a function that can take a value and return the first
key mapping to that value in a dictionary.

# function to return key for any value


def get_key(val):
for key, value in my_dict.items():
if val == value:
return key
return "key doesn't exist"
my_dict ={"java":100, "python":112, "c":11}
print(get_key(100))
print(get_key(11))
o/p:
java
c

3.Depict list comprehension. Give example.

A Python list comprehension consists of brackets containing the


expression, which is executed for each element along with the for
loop to iterate over each element in the Python list.

newList = [ expression(element) for element in oldList if condition ]

numbers = [1, 2, 3, 4, 5]
squared = [x ** 2 for x in numbers]
print(squared)

4.In python, how the values stored in a list are accessed?


Should the elements of a list be of the same data type?

Elements stored in the lists are associated with a unique


integer number known as an index. The first element is
indexed as 0, and the second is 1, and so on

Another way we can access elements/values from the list in


python is using a negative index. The negative index starts
at -1 for the last element, -2 for the last second element,
and so on.

Lists can contain heterogeneous data types and objects.


For instance, integers, strings, and even functions can be
stored within the same list.

# list with elements of different data types


list1 = [1, "Hello", 3.4]

5.How python’s dictionaries store data? Give example.


 Dictionary in Python is a collection of keys values, used
to store data values like a map, which, unlike other data
types which hold only a single value as an element.
 Dictionary holds key:value pair. Key-Value is provided in
the dictionary to make it more optimized.
Example:
Dict={1:”apple”,2:”orange”,3:”banana”}
print(Dict)
Output:
{1:”apple”,2:”orange”,3:”banana”}

Unit 5

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


mode.

 Binary files are mostly the .bin files in your computer.


 Instead of storing data in plain text, they store it in the
binary form (0's and 1's).
 They can hold a higher amount of data, are not readable
easily, and provides better security than text files.

To create a binary file in Python, You need to open the file in


binary write mode ( wb ).
file_path = "path/to/file.bin"

with open(file_path, "wb") as file:


# Write binary data to the file

2.What are the different modules in python?

 Built-in Modules:
Python comes with a set of built-in modules that
provide essential functionalities.
math: Mathematical functions.
os: Operating system interfaces.
sys: System-specific parameters and functions.
datetime: Date and time manipulation.
 Third-party Modules: Developers often create and share
reusable code in the form of third-party modules. These can be
installed using package managers like pip.
numpy: Numerical computing with arrays.
requests: HTTP library for making web requests.
pandas: Data manipulation and analysis.
matplotlib: Plotting and data visualization.
 Custom Modules: Developers can organize their code by
creating custom modules. example, if you have a file named
my_module.py with a function my_function, you can import it
using import my_module and then use
my_module.my_function().

3.What is command line argument?

The arguments that are given after the name of the program in the
command line shell of the operating system are known as Command Line
Arguments. Python provides various ways of dealing with these types of
arguments. The three most common are:

Using sys.argv
Using getopt module
Using argparse module
.

You might also like