0% found this document useful (0 votes)
40 views24 pages

PPS Unit 1 & 2 QB With Solution

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

PPS Unit 1 & 2 QB With Solution

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

Unit 1

LOW Level

Q.1 What is problem? Explain problem solving steps.


Ans-
Problem is defined as a situation or issue or condition which need to be solved to achieve a
specific goal.
Steps in problem solving-
1.Identify the problem
2.Understand the problem
3. Identify the alternative way to solve a problem.

4. Select the best way to solve problem from the list to alternative solution

5. List instructions that enable you to solve the problem using selected solution

6.Evalute the Solution

Q.2 What is single line and multiline comment?


Comments:
 Program comments are explanatory statements that you can include in the
pythoncode.
 These comments help anyone reading the source code. All programming
languages allow for some form of comments.
 Comments are not executable statement in a program. They are just added to
describe the statement in the program code.
 In python, any statement written along with # (hash) symbol is known as a
comment. The interpreter does not interpret the comment.
The python supports two types of comments
1) Single line comments-
In case user wants to specify the singe line comments, then it must start with #.
e.g # This is a single line comment in python
2) Multi line comments-
This is given inside the triple quotes
e.g- ‘’’ This
is
Multi line comment in python’’’
Q.3 Write pseudo code for swapping of two numbers.
1) read value ,set as a
2) read value ,set as b
3) take temporary variable c
4) c=a
5)a=b
6)b=c
7)display value of a,b

Q.4. Explain numeric literal.


Ans: Literals are the notations for representing fix value in source code
Python has different types of literals:
String Literals,
Numeric Literals,
Boolean Literals,
Literal collection,
Numeric Literals:
Python supports three different numeric Literals :
Integer
Float
Complex
1) Integer: These are also called as Int’s which are positive or negative whole no.
With no decimal point.
2) Float: These are Floating point nos. written with decimals point dividng the integer &
fraction part.
3) Complex: The numarals will be in the form of a+bj ,
Where a is the real and b is complex part.
Eg. a = 10
b = 10.5
c = 10101010
d =10+5j
print(a,b,c,d)
Q.5 Explain following terms:
a)Indentation
b)Reserved Words
c)comment
Ans-
Reserved words-
Reserved words (also called keywords) are defined with predefined meaning an syntax in the
language. These keywords have to be used to develop programming instructions. Reserved
words can’t be used as identifiers for other programming elements like name of variable,
function etc.
Program :
import keyword
print(keyword.kwlist)
Output-
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del',
'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal',
'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
Indentation-
 Whitespaces at the beginning of line called indentation In python indentation is used
toassociate and group statement
 In a Python program, the leading whitespaces including spaces and
tabs at the beginning of the logical line determine the indentation level of that logical line

Comment-
 Comments are not executable statement in a program. They are just added to describe
the statement in the program code.
 In python, any statement written along with # (hash) symbol is
known as a comment. The interpreter does not interpret the comment.

Q.6 Draw flowchart for addition of two numbers.


Q.7 Explain mutable and immutable data types.

Python data type is categorized into two types:

 Mutable Data Type – A mutable data type is those whose values can be changed.

Example: List, Dictionaries, and Set

 Immutable Data Type – An immutable data type is one in which the values can’t be
changed or altered.

Example: String and Tuples

Q.8 Explain input and output operation with example.


Input Operation:
• In Python the input() function is used to take input from the user.

• To take input from users, Python makes use of input() function. The input() prompts
the user to provide some information on which the program can work and give the
result.

• However, we must always remember that the input() function takes input as a string.
So whether you input a number or a string, it is treated as a string only.

# Program to demonstrate input( ) function


val = input("Enter an value ")
• Output :

Enter an value
Example-1 String input
name = input("Enter your name: ")
print("Hello, " + name)

Output Operation:
Python provides the print() function to display output to the standard output devices.
Example-2 integer input
num = int(input("Enter a number: "))

add = num + 1

print(add)
Q.9 Define Algorithm. Explain different features of algorithm.
Answer:
1. The algorithm gives the logic of the program, that is, a step-by-step description of
how to arrive at a solution.
2. Algorithm provides a blueprint to writing a program to solve a particular problem.
3. It is considered to be an effective procedure for solving a problem in a finite
number of steps.
4. That is, a well-defined algorithm always provides an answer, and is guaranteed
to terminate.
Features of Algorithm-

1. Clear and Unambiguous.


2. Well-defined inputs.
3. Well-defined outputs.
4. Finite-ness
5. Feasible.
6. Language Independent

Q.10 Explain features of python programming language.


Ans-

• Features of Python:

• Simple – Simple and small language, feel like reading English.

• Easy to learn- Structure of program is simple, uses few keywords and clearly defined
syntax.

• Versatile-Supports development of wide range of application. Ex text processing,


games etc.

• Free and open source- Anyone freely distribute it, read the source code, edit, and use
the code to write new program

• High-level language- Programmer does not need to worry about low level details like
managing memory.
• Interactive- It provide interactive shell or environment where you can execute code
interactively and see immediate result.

• Portable- Program behaves same on the wide variety of hardware platform, Program
work on any of the operating system like Windows, Linux, Solaris etc.

• Function oriented and Object oriented- Support both object oriented (Encapsulate
data and functionalities within object) as well as procedure oriented (use functions)
style of programming.

• Compiled and Interpreted- We are not required to compile python program


explicitly. Internally python interpreter handles it.

• Dynamic- Python executes dynamically. Program can copy and used for flexible
development of application. If there are any error it is reported at run time.

• Extensible- We can use other language program in python.

• Embeddable- Programmer can embed python within C, C++, Java etc.

• Extensive libraries- Huge inbuilt library,

• Easy Maintenance- Easy to maintain.

• Secure- Secure from tampering.

• Robust- Handle errors, programmer cannot manipulate memory directly.

• Multi-threaded- Can execute more than one process.

• Garbage collection- Python run time environment handles garbage collection.

Q.11 Explain brief history of python programming


Ans-

 History of Python:

 Python released on February 20, 1991.

 Python is general-purpose high-level programming language.


 Python was developed by Guido Van Rossum in the late 80’s and early 90’s at the
National Research Institute for Mathematics and Computer Science in the
Netherlands.

 It has been derived from many languages such as ABC, Modula-3, C, C++, Algol-68,
SmallTalk, Unix shell, and other scripting languages.

 When he began implementing Python, Guido van Rossum was also reading the
published scripts from “Monty Python’s Flying Circus”, a BBC comedy series from
the 1970s. Van Rossum thought he needed a name that was short, unique, and slightly
mysterious, so he decided to call the language Python.

Q.12 What is identifier? Explain rules for naming identifier.


Ans-
• Variable are example of identifiers. Identifiers as the name suggests, are name given
to identify something. This something can be a variable, function, class, module, or
other object.
• For naming any identifier, there are some basic rules that you must follow.
 The first character of an identifier must be an underscore (‘_’) or a letter (upper or
lower case)
 The rest of identifier name can be underscore (_), letter (upper or lowercase), or digits
(0-9).
 Identifier names are case sensitive. For example, myvar and myVar are not same.
 Punctuation character such as @, $, and % are not allowed within identifiers.
 Keyword not allowed in variable name.
Ex- Valid Identifier- sum, _my_var, num1, r, var_20, First, etc.
Ex- Invalid identifier- 1num, my-var, %check, Basic Sal, H#R&A etc.

Q.13 Explain following operators in python


a) Arithmetic operators
b) Logical Operators
c) Membership operators
d) Relational operators
Operators are the construct that are used to manipulate the value of operands.
-Ex a+b -> Where a and b are operands and + is operator.
 Python provides a variety of operators described as follows :
• Arithmetic operators
• Comparison(Relational) operators
• Assignment operators
• Logical operators
• Unary Operator
• Bitwise operators
• Membership operators
• Identity operators

• Arithmetic Operator: Basic a arithmetic operators are +, - ,* ,/ ,%, **, //


Assume a=100, b=200

 Comparison Operator/ Relational Operator: Comparison operators are used to


comparing the value of the two operands and returns Boolean True or False
accordingly. ==, != , >, < , >=, <=
 Assignment Operator: =, +=, -=, *=, /=, %=, //=, **=

 Unary Operators- Unary + , Unary -, ~ Invert(Complement)


• It is act on single operand.
• Python support unary minus operator.
• Ex- b=10 #
a=-(b) #
If a number is positive, it becomes negative when preceded with unary minus operator.

 Bitwise Operators- It is applicable to int and Boolean type only. Bitwise AND,
Bitwise OR, Bitwise XOR, Bitwise NOT
• Bitwise AND- Ex- 1111 & 0010=0010-> 15 & 2->2
• Bitwise OR- Ex- 1111 | 0010=1111=-> 15 | 2-> 15

• Bitwise XOR- 1111 ^ 0010-> 15^2->13

• Bitwise NOT-, formula ~x= -x-1

• Shift – Bitwise Right Shift- 18>>2-> 4

Bitwise Left Shift- 18<<2-> 72

 Logical Operators- Logical and, Logical or, Logical not

• and- Logical and- (a>b) and (b>c)- If whole expression is true then only result is true.

• or- Logical or- (a>b) or (b>c)- Whole expression is true when any one condition is
true
• not- Logical not- Logical not take single expression and negates the value of the
expression.

 Membership Operators- The membership operators are useful to test for


membership in sequence such as string, lists tuple and dictionaries.

• in Operator- The operator returns true if a variable found in the specified sequence
otherwise false. Ex s="Python“ -> 'y' in s,->True

Ex- List=[1,2,"Python","Java"] ->2 in List-> True

• not in Operator- The operator return True if variable not found in specified sequence
otherwise false

Ex- List=[1,2,"Python","Java"]-> 2 in List-> False

 Identity Operator- Identity operator compare the memory locations of two objects.
To check two objects are same or not.

• is Operator- Returns True if operands or values on both sides or the operator point to
the same object otherwise false.

• is not Operator: Return True if operands or values on both sides of the operator does
not point to the same object otherwise false.

Q.14 Draw and explain flowchart symbols


• Start and End Symbols- Circles, Ovals, or Rounded rectangles
• Generic processing step- rectangles.
• Input/Output symbols-parallelogram
• A Conditional or Decision Symbols- Diamond
• Arrow
• Labelled Connector- Identifying label inside a circle.


Q.15 Explain Top Down design approach.
• Top-down design is a method of breaking a problem down into smaller, less complex
pieces from the initial overall problem. Most “good” problems are too complex to
solve in just one step, so we divide the problem up into smaller manageable pieces,
solve each one of them and then bring everything back together again.

Q.16 What are different types of problems?


Heuristic Solution :
Solution that can not be reached through a direct set of steps is called heuristic solution.
Ex. Expanding a Company
These solution require reasoning built on knowledge and experience and process of trial and
error.
Ex. The Problem of “Which stock should I buy”
Algorithmic Solution :
Algorithm is nothing but sequence of instruction carried out to solve some problem
Solutions that can be solved with a series of known actions are called Algorithmic Solutions.
Ex. To make a cup of coffee
Ex. To find largest of three numbers
Medium and High level

Q.17 Explain different data types used in python.


• Based on the data type of variable, the interpreter reserves memory for it and also
determines the type of data that can be stored in the reserved memory. The basic types
are numbers and strings. We can even create our own data types in python (like
classes).
• Python is a object-oriented language. It refers to everything as an object including
numbers and strings.
• Fundamental data types in python- int, float, complex, bool, str.
 Numbers:
 Numeric data type can belong to following different numerical types :
 Integers Numbers- int
• Both positive and negative number including 0.
• There Should not be any fraction part.
Ex- 3, -5, -7, 0, 100, 350
1. Decimal Integer(Base 10)-0 to 9
Ex- a=10
2. Binary Integer (Base-2)- 0 and 1
Ex- 0b10 or 0B10
3. Octal Integer(Base 8)- 0 to 7
Ex- c=0o10 or 0O10
4. Hexadecimal Integer (Base- 16)- 0 to 9, a to f or A to F
Ex- d=0x10 or 0X10

 Numbers- (float)These are real numbers having both integer and fraction parts.
-Ex- 1.4, -5.9, 3.1423
- These may be written in one of the two forms:
1. Fraction form: ex 2.5
2. Exponent form: In exponent form consist of two parts:
1. Mantissa
2. Exponent
-Ex- 2E3, 2 is mantissa, 3 is Exponent
2000.0 can be written as 2 × 103 Mantissa part is 2 and exponent part is 3

 Complex Numbers- complex


• In the forms of real part and imaginary part of complex number.
• The numerals will be in the form of a+bj, where a is the real part and b is the
imaginary part. Where a and b are int or float value.
• 1. e.g. a=10+20j, b= 2.3+3.14j
2. e.g. k=7j - real part is 0 here.
Other than j not allowed.
• We can perform operation on complex numbers- a+b, a-b, a*b, a/b.
 Boolean- bool
- There are only two Boolean type in Python. They are True and False.
- a = True - True represent value 1
- b = False - False represent value 0
 String- str
• A string is a group of characters. If you want to use text in python, you have to use a
string.
• Using single quotes- Ex. ‘Hello’
• Using double quotes- Ex. “Hello”
• Using triple single quotes or triple double quotes- ‘’’Hello ‘’’
-By using triple quotes we can write multi-line strings or display in the desired
way.
‘’’Hello,
How
are
You?’’’
 Advanced data types are- list, tuple, dict, set, frozenset, bytes, bytearray, range,
NoneType.
 None- NoneType
- ‘None’ is used to define a null variable.
- If ‘None’ is compared with anything else other than a ‘None’, it will return false.
- It is also used to indicate the end of lists in python
- The None value in python means “There is no useful information or there is nothing
here.”
 List :
• If we want group of items in single entity.
• Mutable.
• List is an ordered sequence of items.
• Insertion order is preserved and duplicates is allowed
• e. g. list = [10,20,30,’Python’,10]
 Tuple :
• Tuple is an ordered sequence of items same as list. The only difference is that tuples
are immutable. Tuples once created cannot be modified
• e. g. tuple = (1,2,3,1,2,”Python”)
 Python Set:
• Mutable
• Set is an unordered collection of unique items.
• Duplicates not allowed.
• e. g. set = {1,2,3,4,"Python",2.2}
 Python Dictionary :
• Mutable
• Dictionary is an unordered collection of key-value pairs.
• If we trying to insert an entry with duplicate key then old value will be replaced with
new value
• dict = {1: ‘Python’, 2:’Java’, 3:’c’}
• print("Complete Dictionary:”, dict)
Unit II
Low Level
Q.1 Explain else using loops.
Else statement with for and while Loop :
 However if the loop contains any of the break statement thenthe else statement
will not be executed.
 A for and while loop can have an optional else block as well.The else part is
executed if the items in the sequence used in for loop exhausts.
 else part will be executed only if all the iterations of for loopor while loop
completed without break.

Example :

Output-

Q.2 Explain while loop with example.


A while loop is used to execute a block of statements repeatedly until a given condition is
satisfied. And when the condition becomes false, the line immediately after the loop in the
program is executed.
Syntax:
while expression:
statement(s)

Example:
i=1
while i <= 3:
i= i + 1
print(“welcome to Python”)

Q.3 Explain nested if with example.


When one if condition is present inside another if then it is called nested if condition.
• Syntax:

if (condition1):
# Executes when condition1 is true
if (condition2):
# Executes when condition2 is true
# if Block is end here
# if Block is end here

Q.4 Describe following with example


a)break
b) continue
c) pass
a)break:
• Python break is used to terminate the execution of the loop.

• break statement in Python is used to bring the control out of the loop when some
external condition is triggered.

• break statement is put inside the loop body (generally after if condition).

• It terminates the current loop, i.e., the loop in which it appears, and resumes execution
at the next statement immediately after the end of that loop.

• If the break statement is inside a nested loop, the break will terminate the innermost
loop.
• Syntax:

break
• Example

for i in range(10):
print(i)
if i == 2:
break
b)continue
• It returns the control to the beginning of the loop.

• The continue statement rejects all the remaining statements in the current iteration of
the loop and moves the control back to the top of the loop.

• The continue statement can be used in both while and for loops.

Syntax:
continue

• Example 1

for letter in 'Python':


if letter == 'h':
continue
print ("Current Letter :", letter )
• Example 2

var = 5
while var > 0:
var = var -1
if var == 3:
continue
print ('Current variable value :‘,var )
c) pass

• The pass statement is used as a placeholder for future code.

• When the user does not know what code to write, So user simply places a pass at that
line.

• If we do not use pass or simply enter a comment or a blank here, we will receive
an IndentationError error message.

Example : 1
n = 26
if n > 26:
# write your code here
pass
print("Python")

Q.5 What is list? Explain following operations of list


a) create a list
b) display list
c) accessing an element in list
ANS-
List
1. A list is a collection of things, enclosed in ‘[]’ and separated by commas.
2. A list is a collection of different kinds of values or items.
3. Since, python lists are mutable, we can change their elements after forming.
4. List does not allow duplicate values.
1. Create list
L1 = [1,2,3,4,3.5,’John’]
2. Display list
L1 = [1,2,3,4,5]
Print(L1)
3. Accessing list elements
In order to access the list items refer to the index number.
Use index operator ‘[]’ to access an item in list.
e.g.
L1 = [10,20,30,’Python’]
Print(“Second element in list is :”,L1[1])

O/P:
Second element in list is : 20

Q.6 Explain if..elif..else statement


Answer:
1. Here, a user can decide among multiple options. The if statements executed from the top to
down.
2. As soon as one of the conditions controlling the if is true, statement associated with that if is
executed and the rest of the code is ignored.
3. If none of the conditions is true, then the final else statement is executed.
4. Syntax:
If condition :
statement
elif condition :
statement
.
.
.
else :
statement
Example :
a = 10
if a == 20 :
print(“a is 20”)
elif a == 10:
print(“a is 10”)
elif a == 30 :
print(“a is 30”)
else :
print(“Invalid Number”)

O/P:
a is 10
Q.7 What is range() function? Explain with example
Answer:
1. It returns a sequence of numbers, starting from 0 by default and increments by 1 and stops
before a specified number.
2. Syntax:
range(start, stop, step)
3. Start is optional parameter. It specify start position. By default it is 0.
4. Stop is required parameter. It specify the position to stop.
5. Step is optional parameter. It specify increment and by default it will increment by 1.

Example:

x = range(3, 6)
for n in x:
print(n)

O/P
3
4
5
Q.8 Explain different Dictionary methods.
Answer:
1. clear() : It removes all the elements from the dictionary.
e.g.
car = {‘brand’ : ’ford’, ’model’ : ’top’, ‘year’ : 2022}
print(car)
car.clear()
print(car)

O/P :
{'brand': 'ford', 'model': 'top', 'year': 2022}
{}

2. copy() : It returns a copy of the dictionary.


e.g.
car = {‘brand’ : ’ford’, ’model’ : ’top’, ‘year’ : 2022}
x = car.copy()
print(x)

O/P:
{'brand': 'ford', 'model': 'top', 'year': 2022}

3. fromkeys() : It returns a dictionary with the specified keys and values.


e.g.
x = (‘key1’, ‘key2’, ‘key3’)
y=0
z = dict.fromkeys(x,y)
print(z)

O/P:
{'key1': 0, 'key2': 0, 'key3': 0}

4. get() : It returns value of specified key.


e.g.
car = {‘brand’ : ’ford’, ’model’ : ’top’, ‘year’ : 2022}
x = car.get(‘model’)
print(x)

O/P
Top

5. update() : It updates the dictionary with key value pair.


e.g.
car = {‘brand’ : ’ford’, ’model’ : ’top’, ‘year’ : 2022}
car.update({‘colour’ : ‘White’})
print(car)

O/P:
{'brand': 'ford', 'model': 'top', 'year': 2022, 'colour': 'White'}

6. pop() : It removes the element with specified key.


e.g.
car = {‘brand’ : ’ford’, ’model’ : ’top’, ‘year’ : 2022}
car.pop(‘model’)
print(car)

O/P:
{'brand': 'ford', 'year': 2022}
7. popitem() : It removes last item from dictionary.
e.g.
car = {‘brand’ : ’ford’, ’model’ : ’top’, ‘year’ : 2022}
car.popitem()
print(car)

O/P:
{'brand': 'ford', 'model': 'top'}
Q.9 Explain following data types in python
a)List
b) Tuple

c) Dictionary

Ans-
 List :
• If we want group of items in single entity.
• Mutable.
• List is an ordered sequence of items.
• Insertion order is preserved and duplicates is allowed
• e. g. list = [10,20,30,’Python’,10]
 Tuple :
• Tuple is an ordered sequence of items same as list. The only difference is that tuples
are immutable. Tuples once created cannot be modified
• e. g. tuple = (1,2,3,1,2,”Python”)
 Python Dictionary :
• Mutable
• Dictionary is an unordered collection of key-value pairs.
• If we trying to insert an entry with duplicate key then old value will be replaced with
new value
• dict = {1: ‘Python’, 2:’Java’, 3:’c’}
• print("Complete Dictionary:”, dict)

Medium & High Level

Q.10 Write a python program to chech whether number is positive, negative or zero.
Q.11 Write a python program to print factorial of a number.

Output-

Q.13 Write a python program to print sum of 1-10 numbers.


i=1
sum=0
while i<=10:
sum=sum+i
i=i+1
print(sum)
Output:
55
Q.14 Write a python program to find maximum of three numbers.

num1 = 10
num2 = 14
num3 = 12
if (num1 >= num2) and (num1 >= num3):
largest = num1
elif (num2 >= num1) and (num2 >= num3):
largest = num2
else:
largest = num3

print("The largest number is", largest)

You might also like