Qbank Cs
Qbank Cs
QUESTION BANK
Q
U
E
S
T
I
I YEAR –B.E/B.TECH O
(Common to all Branches)
N
SEP 2023 to JAN 2023
B
PREPARED BY A
APPROVED BY
K
UNIT I
ALGORITHMIC PROBLEM SOLVING
PART- A (2 Marks)
2. Write the pseudocode to calculate the n number of students’ total marks and average.
INPUT cs, maths, phy
PRINT avg
PRINT percentage
Step 1: Start
Step 2: Read the three numbers A, B,
C Step 3: Compare A and B.
If A is minimum, go to step 4 else go to step 5.
Step 4: Compare A and C.
If A is minimum, output “A is minimum” else output “C is minimum”. Go to step 6.
Step 5: Compare B and C.
If B is minimum, output “B is minimum” else output “C is minimum”.
Step 6: Stop
Statements are instructions in Python designed as components for algorithmic problem Solving,
rather than as one-to-one translations of the underlying machine language instruction set of the
computer.
There are three types of high-level programming language statements Input/output statements
make up one type of statement. An input statement collects a specific value from the user for a
variable within the program. An output statement writes a message or the value of a program
variable to the user’s screen.
6. Write the pseudo code to calculate the sum and product of two numbers and display it.
Control flow (or flow of control) is the order in which individual statements, instructions or function
calls of an imperative program are executed or evaluated. A control flow statement is a statement in
which execution results in a choice being made as to which of two or more paths to follow.
8. What is a function?
Functions are "self-contained" modules of code that accomplish a specific task. Functions
usually "take in" data, process it, and "return" a result. Once a function is written, it can be used
over and over and over again. Functions can be "called" from the inside of other functions.
9. Write the pseudo code to calculate the sum and product displaying the answer on the
monitor screen.
Flowchart and Pseudo code are used to document and represent the algorithm. In other words, an
algorithm can be represented using a flowchart or a pseudo code. Flowchart is a graphical
representation of the algorithm. Pseudo code is a readable, formally styled English like language
representation of the algorithm.
A flowchart is a diagrammatic representation of the logic for solving a task. A flowchart is drawn
using boxes of different shapes with lines connecting them to show the flow of control. The purpose
of drawing a flowchart is to make the logic of the program clearer in a visual form.
a=0
for i from 1 to 3 // loop three times
{
a=a+i // add the current value of i to a
}
print a // the number 6 is printed (0 + 1; 1 + 2; 3 + 3)
Machine language is a collection of binary digits or bits that the computer reads and interprets. This
language is not easily understandable by the human.
An assembly language directly controls the physical hardware. A program written in assembly
language consists of a series of instructions mnemonics that correspond to a stream of executable
instructions, when translated by an assembler can be loaded into memory and executed. The programs
written in this language are not portable and the debugging process is also not very easy.
A high level language is much more abstract, that must be translated or compiled in to machine
language. It is easily understandable and the programs are portable. Debugging the code is easy and
the program written is not machine dependent.
An algorithm is a systematic logical approach used to solve problems in a computer while pseudo
code is the statement in plain English that may be translated later to a programming language.
Pseudo code is the intermediary between algorithm and program.
Recursion Iteration
Function calls itself until the base condition is Repetition of process until the condition fails.
reached.
Only base condition (terminating condition) is It involves four steps: initialization,
specified. condition,
It keeps our code short and simple. Iterative approach makes our code longer.
It is slower than iteration due to overhead of Iteration is faster.
maintaining stack.
It takes more memory than iteration due to Iteration takes less memory.
overhead of maintaining stack.
Advantages Disadvanta
Recursive functions make the code look clean Sometimes the logic behind recursion is hard
and elegant. to
follow through.
A complex task can be broken down into Recursive calls are expensive (inefficient)
simpler sub-problems using recursion. as
they take up a lot of memory and time.
Sequence generation is easier with recursion Recursive functions are hard to debug.
than using some nested iteration.
PART B (16 MARKS)
1. WHILE
2. FOR
Functions:
A function is a block of organized reusable code that is used to perform a single action.
1 The process is repeated until The function calls itself until the base condition
the is
condition fails. satisfied.
2 It consumes less memory. It consumes more memory
3 It is faster It is slower
4 The code is long . The code is short.
Step 1: Start
Step 2: Read number
n
Step 3: Call factorial(n)
Step 4: Print factorial f
Step 5: Stop
factorial(n)
Step 1: If n==1 then return 1
Step 2: Else
f=n*factorial(n-1)
Step 3: Return f
3. Explain in detail Algorithmic problem solving.
4
4. Write an algorithm and draw a flowchart to calculate 2 .
Algorithm:
Step 1: Start
Step 2: Initialize the value of result,
r=1. Step 3: Repeat step4 for 4
times Step 4: calculate r=r*2
Step 5: Print the value of r
Step 6: Stop
Flowchart:
8
5. a) Describe pseudo code with its guidelines.
Pseudo code consists of short, readable and formally-styled English language used for
explaining an algorithm. Pseudo code does not include details like variable declarations, subroutines
etc.
Preparing a Pseudo
Code
6. a) What is flowchart?
Algorithm:
step 1: Start the program
step 2: Read an 'n' n
umber step 3: Read
an Guess number
step 4: if Guess> n; print "Your Guess too high" Step 5: elif Guess <n ; print
"Your Guess too low" step 6: elif Guess = = n; print "Good job"
Step 7: else print"Nope "
Step :8 Stop the program
Pseudocode: BEGIN
READ n
READ Guess = 20
IF Guess> n
print"Your Guess too High" elif Guess< n
print "Your Guess too low" elif Gu
ess = = 20 print "Good Job"
ELSE
print"Nope"
Pseudocode:
BEGIN
SET numlist=[
] GET n
FOR i=1 to n
GET numlist elements
ENDFOR
SET minimum =
numlist[0] FOR i in
numlist
IF (n <
minimum)
minimum
=n
ENDI
F ENDFOR
PRINT minimum
END
UNIT II
CONTROL FLOW STATEMENTS
PART- A (2 Marks)
1. Write a program which accepts the user’s first and last number and prints them in reverse order
with a space between them.
First = input("Enter Your First Name = ")
The Python interpreter can be invoked by typing the command "python" without any
parameter followed by the "return" key at the shell prompt.
Interactive mode is a command line shell which gives immediate feedback for each statement,
while running previously fed statements in active memory. As new lines are fed into the interpreter,
the fed program is evaluated both in part and in whole.
In script mode:
>>> print "Hello World"
Hello World
In Interactive Mode:
>>> "Hello World"
'Hello World'
A value is one of the fundamental things – like a letter or a number – that a program manipulates. Its
types are: integer, float, boolean, strings and lists.
8. Define a variable and write down the rules for naming a variable.
A name that refers to a value is a variable. Variable names can be arbitrarily long. They can
contain both letters and numbers, but they have to begin with a letter. It is legal to use uppercase
letters, but it is good to begin variable names with a lowercase letter.
A keyword is a reserved word that is used by the compiler to parse a program. Keywords
cannot be used as variable names. Some of the keywords used in python are: and, del, from, not,
while, is, continue.
A statement is an instruction that the Python interpreter can execute. There are two types of
statements: print and assignment statement.
A tuple is a sequence of immutable Python objects. Tuples are sequences, like lists. The
differences between tuples and lists are, the tuples cannot be changed unlike lists and tuples use
parentheses, whereas lists use square brackets. Creating a tuple is as simple as putting different
comma- separated values. Comma-separated values between parentheses can also be used.
Example: tup1 = ('physics', 'chemistry', 1997, 2000);
An operator is a symbol that specifies an operation to be performed on the operands. The data
items that an operator acts upon are called operands. The operators +, -, *, / and ** perform addition,
subtraction, multiplication, division and exponentiation.
Example: 20+32
In this example, 20 and 32 are operands and + is an operator.
12. What is the order in which operations are evaluated? Give the order of precedence.
The set of rules that govern the order in which expressions involving multiple operators and
operands are evaluated is known as rule of precedence. Parentheses have the highest precedence
followed by exponentiation. Multiplication and division have the next highest precedence followed by
addition and subtraction.
The * operator performs repetition on strings and the + operator performs concatenation on strings.
Example:
>>> ‘Hello*3’
Output: HelloHelloHello
>>>’Hello+World’
Output: HelloWorld
A boolean expression is an expression that is either true or false. The values true and false are
called Boolean values.
Eg :
>>> 5 == 6
False
True and False are special values that belongs to the type bool; they are not strings:
The modulus operator works on integers and yields the remainder when the first operand is
divided by the second. In Python, the modulus operator is a percent sign (%). The syntax is the same
as for other operators:
Eg:
>>> remainder = 7 % 3
>>> print remainder
1
So 7 divided by 3 is 2 with 1 left over.
There are three logical operators: and, or, and not. For example, x > 0 and x < 10 is true only if
x is greater than 0 and less than 10. n%2 == 0 or n%3 == 0 is true if either of the conditions is true,
that is, if the number is divisible by 2 or 3. Finally, the not operator negates a Boolean expression, so
not(x > y) is true if x > y is false, that is, if x is less than or equal to y. Non-zero number is said to be
true in Boolean expressions.
The ability to check the condition and change the behavior of the program accordingly is called conditional
execution. Example:
If statement:
The simplest form of if statement is:
Syntax:
if
statement:
Eg:
if x > 0:
print 'x is positive'
The boolean expression after ‘if’ is called the condition. If it is true, then the indented
statement gets executed. If not, nothing happens.
A second form of if statement is alternative execution, that is, if …else, where there are two possibilities
and the condition determines which one to execute.
Eg:
if x%2 == 0:
print 'x is even'
else:
print 'x is odd'
22. What are chained conditionals?Sometimes there are more than two possibilities
and we need more than two branches. One way to express a computation like that is a chained
conditional:
Eg:
if x < y:
print 'x is less than y'
elif x > y:
print 'x is greater than y'
else:
print 'x and y are equal'elif is an abbreviation of “else if.” Again, exactly one branch will be
executed. There is no limit on the number of elif statements. If there is an else clause, it has to be at
the end, but there doesn’t have to be one.
Syntax:
for variable in sequence:
code block
Eg:
x=4
for i in range(0, x):
print i
When a break statement is encountered inside a loop, the loop is immediately terminated and
the program control resumes at the next statement following the loop.
Eg:
while True:
line = raw_input('>')
if line == 'done':
break
print line
print'Done!'
With the Python interactive interpreter it is easy to check Python commands. The Python interpreter
can be invoked by typing the command "python" without any parameter followed by the "return" key
at the shell prompt:
$ python
>>>
Once the Python interpreter is started, you can issue any command at the command prompt ">>>".
For example,let us print the "Hello World" statement:
>>> print "Hello World"
Hello World
In the interactive Python interpreter the print is not necessary:
Typing an end-of-file character (Ctrl+D on Unix, Ctrl+Z on Windows) at the primary prompt causes
the interpreter to exit with a zero exit status. If that doesn’t work, you can exit the interpreter by
typing the following command: quit().
When commands are read from a tty, the interpreter is said to be in interactive mode. In this mode it
prompts for the next command with the primary prompt, usually three greater-than signs (>>>); for
continuation lines it prompts with the secondary prompt, by default three dots (...). The interpreter
prints a welcome message stating its version number and a copyright notice before printing the first
prompt:
Continuation lines are needed when entering a multi-line construct. As an example, take a look at this
if statement: >>> the_world_is_flat = 1
>>> if the_world_is_flat:
... print "Be careful not to fall off!"
2. (a) List down the rules for naming the variable with example.
A variable is a name that refers to a value. An assignment statement creates new variables and gives
them values:
Variable names can be arbitrarily long. They can contain both letters and numbers, but they have to
begin with a letter. It is legal to use uppercase letters, but it is a good idea to
begin variable names with a lowercase letter .
The underscore character, _, can appear in a name. It is often used in names with multiple words,
such as my_name or variable_name.
If you give a variable an illegal name, you get a syntax error:
becomes true
Eg:
if x > 0:
print 'x is positive'
The boolean expression after ‘if’ is called the condition. If it is true, then the indented statement
gets executed. If not, nothing happens. if statements have the same structure as function
definitions: a header followed by an indented body. Statements like this are called compound
statements. There is no limit on the number of statements that can appear in the body, but there
has to be at least one. Occasionally, it is useful to have a body with no statements .In that case,
you can use the pass statement, which does nothing.
if x < 0:
pass # need to handle negative values!
Alternative execution (if-else):A second form of if statement is alternative execution, in which
there are two possibilities and the condition determines which one gets executed. The syntax
looks like this:
Eg:
if x%2 == 0:
print 'x is even'
else:
print 'x is odd'
If the remainder when x is divided by 2 is 0, then we know that x is even, and the program displays a
message to that effect. If the condition is false, the second set of statements is executed. Since the
condition must be true or false, exactly one of the alternatives will be executed. The alternatives are
called branches, because they are branches in the flow of execution.
Chained conditionals(if-elif-else):
Sometimes there are more than two possibilities and we need more than two branches. One
way to express a computation like that is a chained conditional:
Eg:
if x < y:
print 'x is less than y'
elif x > y:
print 'x is greater than y
else:
print 'x and y are equal'
elif is an abbreviation of “else if.” Again, exactly one branch will be executed. There is no limit on the
number of elif statements. If there is an else clause, it has to be at the end, but there doesn’t have to be
one.
Eg:
if choice == 'a':
draw_a()
Each condition is checked in order. If the first is false, the next is checked, and so on. If one of them
is true, the corresponding branch executes, and the statement ends. Even if more than one condition
is true, only the first true branch executes.
6. What do you mean by rule of precedence? List out the order of precedence and
demonstrate in detail with example.
When more than one operator appears in an expression, the order of evaluation depends on the rules
of precedence. For mathematical operators, Python follows mathematical convention. The acronym
PEMDAS is a useful way to remember the rules,
• Parentheses have the highest precedence and can be used to force an expression to evaluate in the
order you want. Since expressions in parentheses are evaluated first,
2 * (3-1) is 4, and (1+1)**(5-2) is 8.
You can also use parentheses to make an expression easier to read, as in (minute * 100) / 60, even if
it doesn’t change the result.
• Exponentiation has the next highest precedence, so 2**1+1 is 3, not 4 and 3*1**3 is 3, not 27.
• Multiplication and Division have the same precedence, which is higher than Addition and
Subtraction, which also have the same precedence. So 2*3-1 is 5, not 4, and 6+4/2 is 8, not 5.
• Operators with the same precedence are evaluated from left to right (except exponentiation).
So in the expression degrees / 2 * pi, the division happens first and the result is multiplied by pi. To divide
by 2π, you can use parentheses or write degrees / 2 / pi.
UNIT III
FUNCTIONS AND STRINGS
PART- A (2 Marks)
python programming
p
g
hon progr
hon programmi
A variable defined inside a function. A local variable can only be used inside its function.
a. float(32)
b. float("3.14159")
Output:
a. 32.0 The float function converts integers to floating-point numbers.
b. 3.14159 The float function converts strings to floating-point numbers.
In order to ensure that a function is defined before its first use, we have to know the order in
which statements are executed, which is called the flow of execution. Execution always begins at the
first statement of the program. Statements are executed one at a time, in order from top to bottom.
first = 'throat'
second = 'warbler'
print first + second
Output:
Throatwarbler
The operation that divides two numbers and chops off the fraction part is known as floor division.
Automatic method to convert between data types is called type coercion. For mathematical
operators, if any one operand is a float, the other is automatically converted to float.
Eg:
>>> minute = 59
>>> minute / 60.0
0.983333333333
A list of the functions that tells us what program file the error occurred in, and what line, and
what functions were executing at the time. It also shows the line of code that caused the error.
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.
Eg:
def my_local():
a=10
print(“This is local variable”)
Eg:
a=10
def my_global():
print(“This is global variable”)
Python strings are immutable. ‘a’ is not a string. It is a variable with string value. We can’t
mutate the string but can change what value of the variable to a new string.Program:
a = “foo”
# a now points to foo b=a# b now points to the same foo that a points to
a=a+a
# a points to the new string “foofoo”, but b points to the same old “foo”
print a
print bOutput:#foofoo #foo
It is observed that ‘b’ hasn’t changed even
though ‘a’ has changed.ention a few string
functions.
A method is similar to a function—it takes arguments and returns a value—but the syntax is
different. For example, the method upper takes a string and returns a new string with all uppercase
letters:
Instead of the function syntax upper(word), it uses the method syntax word.upper()
.>>> word = 'banana'
>>> new_word = word.upper()
>>> print new_word
BANANA
The string module contains number of useful constants and classes, as well as some
deprecated legacy functions that are also available as methods on strings.
Eg:
Program: Output:
import string upper => MONTY PYTHON'S FLYING
text = "Monty Python's Flying Circus" CIRCUS
print "upper", "=>", string.upper(text) lower => monty python's flying circus
print "lower", "=>", string.lower(text) split => ['Monty', "Python's", 'Flying', 'Circus']
print "split", "=>", string.split(text) join => Monty+Python's+Flying+Circus
print "join", "=>", string.join(string.split(text), replace => Monty Java's Flying Circus
"+") find => 6 -1
print "replace", "=>", string.replace(text, count => 3
"Python", "Java")
print "find", "=>", string.find(text, "Python"),
string.find(text, "Java")
print "count", "=>", string.count(text, "n")
2. Explain the role of function call and function definition with example.
A function is a named sequence of statements that performs a computation. When you define a
function, you specify the name and the sequence of statements. Later, you can “call” the function by
name.
>>> type(32)
<type 'int'>
The name of the function is type. The expression in parentheses is called the argument of the
function. The result, for this function, is the type of the argument. A function “takes” an argument
and “returns” a result. The result is called the return value.
Type conversion functions
Python provides built-in functions that convert values from one type to another. The int function
takes any value and converts it to an integer, if it can, or complains otherwise:
>>> int('32')
32
>>> int('Hello')
int can convert floating-point values to integers, but it doesn’t round off; it chops off the
fraction part:
>>> int(3.99999)
>>> int(-2.3)
-2
approx = 0.5 * n
better = 0.5 * (approx + n/approx)
while better != approx:
approx = better
better = 0.5 * (approx + n/approx)
print(approx)
Math functions
Python has a math module that provides most of the familiar mathematical functions. A
module is a file that contains a collection of related functions.
Before we can use the module, we have to import it:
This statement creates a module object named math. If you print the module object, you
get some information about it:
The module object contains the functions and variables defined in the module. To
access one of the functions,specify the name of the module and the name of the
function, separated by a dot (also as a period). This format is called dot notation.
The first example uses log10 to compute a signal-to-noise ratio in decibels (assuming that
signal_power and noise_power are defined). The math module also provides log, which
computes logarithms base e.
The second example finds the sine of radians. The name of the variable is a hint that sin
and the other trigonometric functions (cos, tan, etc.) take arguments in radians. To convert
from degrees to radians, divide by 360 and multiply by 2π:
>>> degrees = 45
>>> radians = degrees / 360.0 * 2 * math.pi
>>> math.sin(radians)
0.707106781187
The expression math.pi gets the variable pi from the math module. The value of this
variable is an approximation of π, accurate to about 15 digits.
5. Write a Python program to check whether a given year is a leap year or not.
celsius = 37.5
# calculate fahrenheit
fahrenheit = (celsius * 1.8) + 32
print('%0.1f degree Celsius is equal to %0.1f degree Fahrenheit' %(celsius,fahrenheit))
7. Explain RECURSION.
The process in which a function calls itself directly or indirectly is called recursion and the
corresponding function is called as recursive function. Using recursive algorithm, certain
problems can be solved quite easily. Examples of such problems are Towers of Hanoi (TOH),
Inorder/Preorder/Postorder Tree Traversals, DFS of Graph, etc.
Python program:
# take input from the user
num = int(input("Enter a number: "))
def fact(n):
if n == 1:
return n else:
return n*fact(n-1)
print(“Factorial of n numbers is :%d” %(fact(n)))
d1=int(input("Enter a number:"))
d2=int(input("Enter another number"))
rem=d1%d2
while rem!=0 :
print(rem)
d1=d2 d2=rem
rem=d1%d2
print("gcd of given numbers is : %d" %(d2))
The list is better for performing operations, such A Tuple data type is appropriate for
3
as insertion and deletion. accessing the elements
3.Let list = [’a’, ’b’, ’c’, ’d’, ’e’, ’f’]. Find a) list[1:3] b) t[:4] c) t[3:] .
>>> list = [’a’, ’b’, ’c’, ’d’, ’e’, ’f’]
>>> list[1:3] [’b’, ’c’]
>>> list[:4] [’a’, ’b’, ’c’, ’d’]
>>> list[3:] [’d’, ’e’, ’f’]
Python represents all its data as objects. Some of these objects like lists and dictionaries are mutable,
i.e., their content can be changed without changing their identity. Other objects like integers, floats,
strings and tuples are objects that cannot be changed.
Example:
>>> numbers = [17, 123]
>>> numbers[1] = 5
>>> print numbers [17, 5]
11. Write a program in Python returns a list that contains all but the first element of the
given list.
def tail(list):
return list[1:]
Here’s how tail is used:
>>> numbers = [1, 2, 3]
>>> rest = tail(numbers)
>>> print rest [2, 3]
12. What is the benefit of using tuple assignment in Python?
It is often useful to swap the values of two variables. With conventional assignments a temporary
variable would be used. For example, to swap a and b:
>>> temp = a
>>> a = b
>>> b = temp
This solution is cumbersome; tuple assignment is more elegant:
>>> a, b = b, a
The list comprehension starts with a '[' and ']', to help us remember that the result is going to be a
list. The basic syntax is [expression for item in list if conditional ].
The following list contains a string, a float, an integer, and (mirabile dictu) another list:
LIST SLICES
If we omit the first index, the slice starts at the beginning. If we omit the second, the slice goes to the end. So
if we omit both, the slice is a copy of the whole list.
Since lists are mutable, it is often useful to make a copy before performing operations that fold, spindle or
mutilate lists. A slice operator on the left side of an assignment can update multiple elements:
We can assign new values to slices of the lists, which don't even have to be the same
It's even possible to append items onto the start of lists by assigning to an empty
Similarly, you can append to the end of the list by specifying an empty slice after the end:
list:
With slicing you can create copy of list since slice returns a new list:
>>> list_copy
[1, 'element', []]
>>> list_copy.append('new element')
>>> list_copy
[1, 'element', [], 'new element']
>>> original
[1, 'element', []]
Note, however, that this is a shallow copy and contains references to elements from the original list, so be
careful with mutable types:
>>> list_copy[2].append('something')
>>> original
[1, 'element', ['something']]
Non-Continuous slices
It is also possible to get non-continuous parts of an array. If one wanted to get every n-th occurrence of a
list, one would use the :: operator. The syntax is a:b:n where a and b are the start and end of the slice to be
operated upon.
>>> list
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list[::2] [0, 2,
4, 6, 8]
>>> list[1:7:2]
[1, 3, 5]
2. Explain in detail about list methods and list loops with examples.
Python provides methods that operate on lists. Some of the methods are
Append()
Extend()
Sort()
Pop()
>>> t.append('d')
>>> print t ['a', 'b', 'c', 'd']
>>> t1.extend(t2)
This example leaves t2 unmodified. sort arranges the elements of the list from low to high:
>>> t.sort()
Remove the item in the list at the index i and return it. If i is not given, remove the the last item in the list
and return it.
>>> list
[2, 3, 4]
>>> a
List methods are all void; they modify the list and return None.
LIST LOOPS
Here are two functions that both generate ten million random numbers, and return the sum of the
numbers. They both work.
import random
joe =
random.Random() def
sum1():
""" Build a list of random numbers, then sum them """ # Generate one random
˓→number xs = []
for i in range(10000000): >>> list = [1, 2, 3, 4]
num = joe.randrange(1000 )
>>> a = list.pop(0)
xs.append(num) # Save it in our
list tot = sum(xs)
return tot def
sum2(): """ Sum
the random
numbers as we
generate them
""" tot = 0
for i in range(10000000): num
= joe.randrange(1000) tot +=
num
return tot
print(sum1())
print(sum2())
Unlike strings, lists are mutable, which means we can change their elements. Using the bracket operator
on the left side of an assignment, we can update one of the elements:
With the slice operator we can update several elements at once:>>> list = [’a’, ’b’, ’c’, ’d’, ’e’, ’f’]
We can also remove elements from a list by assigning the empty list to them:
>>> list[1:3] = []
And we can add elements to a list by squeezing them into an empty slice at the desired location:
It is often useful to swap the values of two variables. With conventional assignments, you have to use a
temporary variable. For example, to swap a and b:
>>> temp = a
>>> a = b
>>> b = temp
>>> a, b = b, a
The left side is a tuple of variables; the right side is a tuple of expressions. Each value is assigned to its
respective variable. All the expressions on the right side are evaluated before any of the assignments. The
number of variables on the left and the number of values on the right have to be the same:
>>> a, b = 1, 2, 3
ValueError: too many values to unpack More generally, the right side can be any kind of sequence (string,
list or tuple). For example, to split an email address into a user name and a domain, you could write:
The return value from split is a list with two elements; the first element is assigned to uname, the second to
domain.
>>> temp = a
>>> a = b
>>> b = temp
This solution is cumbersome; tuple assignment is more elegant:>>> a, b = b, a
The left side is a tuple of variables; the right side is a tuple of expressions. Each value is assigned to its
respective variable. All the expressions on the right side are evaluated before any of the assignments. The
number of variables on the left and the number of values on the right have to be the same:
>>> a, b = 1, 2, 3
ValueError: too many values to unpack More generally, the right side can be any kind of sequence (string,
list or tuple). For example, to split an email address into a user name and a domain, you could write:
The return value from split is a list with two elements; the first element is assigned to uname, the second to
domain.
return y, x
Then we can assign the return value to a tuple with two variables:
a, b = swap(a, b)
In this case, there is no great advantage in making swap a function. In fact, there is a danger in trying to
encapsulate swap, which is the following tempting mistake:
= y, x
If we call this function like this: swap(a, b) then a and x are aliases for the same value. Changing x inside
swap makes x refer to a different value, but it has no effect on a in main. Similarly, changing y has no effect
on b. This function runs without producing an error message, but it doesn’t do what we intended. This is an
example of a semantic error.
The built-in function divmod takes two arguments and returns a tuple of two values, the quotient and
remainder. You can store the result as a tuple:
>>> t = divmod(7, 3)
Here is an example of a function that returns a tuple: def min_max(t): return min(t), max(t) max and min are
built-in functions that find the largest and smallest elements of a sequence. min_max computes both and
returns a tuple of two values.
A dictionary is like a list, but more general. In a list, the indices have to be integers; in a dictionary they can
be (almost) any type. You can think of a dictionary as a mapping between a set of indices (which are called
keys) and a set of values. Each key maps to a value. The association of a key and a value is called a key-
value pair or sometimes an item. As an example, we’ll build a dictionary that maps from English to Spanish
words, so the keys and the values are all strings.
The function dict creates a new dictionary with no items. Because dict is the name of a built-in function,
you should avoid using it as a variable name.
The squiggly-brackets, {}, represent an empty dictionary. To add items to the dictionary, you can use
square brackets: >>> eng2sp['one'] = 'uno' This line creates an item that maps from the key 'one' to the
value 'uno'. If we print the dictionary again, we see a key-value pair with a colon between the key and
value:
This output format is also an input format. For example, you can create a new dictionary with three items:
>>> eng2sp = {'one': 'uno', 'two': 'dos', 'three': 'tres'} But
if you print eng2sp, you might be surprised:
>>> print eng2sp {'one': 'uno', 'three': 'tres', 'two': 'dos'}
The order of the key-value pairs is not the same. In fact, if you type the same example on your computer,
you might get a different result. In general, the order of items in a dictionary is unpredictable. But that’s not
a problem because the elements of a dictionary are never indexed with integer indices. Instead, you use the
keys to look up the corresponding values:
The key 'two' always maps to the value 'dos' so the order of the items doesn’t matter. If the key isn’t in the
dictionary, you get an exception:
The len function works on dictionaries; it returns the number of key-value pairs:
>>> len(eng2sp)
The in operator works on dictionaries; it tells you whether something appears as a key in the dictionary
(appearing as a value is not good enough).
To see whether something appears as a value in a dictionary, you can use the method values, which returns
the values as a list, and then use the in operator:
>>> 'uno' in
vals True
The in operator uses different algorithms for lists and dictionaries. For lists, it uses a search algorithm, as in
Section 8.6. As the list gets longer, the search time gets longer in direct proportion. For dictionaries, Python
uses an algorithm called a hashtable that has a remarkable property: the in operator takes about the same
amount of time no matter how many items there are in a dictionary
Dictionary operations
The del statement removes a key-value pair from a dictionary. For example, the following dictionary contains
the names of various fruits and the number of each fruit in stock:
>>> inventory = {’apples’: 430, ’bananas’: 312, ’oranges’: 525, ’pears’: 217}
>>> print inventory {’oranges’: 525, ’apples’: 430, ’pears’: 217, ’bananas’: 312}
If someone buys all of the pears, we can remove the entry from the dictionary:
Or if we’re expecting more pears soon, we might just change the value associated with pears:
>>> inventory[’pears’] = 0
>>> print inventory {’oranges’: 525, ’apples’: 430, ’pears’: 0, ’bananas’: 312}
The len function also works on dictionaries; it returns the number of key-value pairs:
>>> len(inventory) 4
A method is similar to a function—it takes arguments and returns a value— but the syntax is different. For
example, the keys method takes a dictionary and returns a list of the keys that appear, but instead of the
function syntax keys(eng2sp), we use the method syntax eng2sp.keys().
This form of dot notation specifies the name of the function, keys, and the name of the object to apply the
function to, eng2sp. The parentheses indicate that this method has no parameters. A method call is called an
invocation; in this case, we would say that we are invoking keys on the object eng2sp.
The values method is similar; it returns a list of the values in the dictionary:
The items method returns both, in the form of a list of tuples—one for each key-valuepair:
The syntax provides useful type information. The square brackets indicate that this is a list. The
parentheses indicate that the elements of the list are tuples. If a method takes an argument, it uses the
same syntax as a function call. For example, the method has key takes a key and returns true (1) if the
key appears in the dictionary:
>>> eng2sp.has_key(’deux’)
False
If you try to call a method without specifying an object, you get an error. In this case, the error message
is not very helpful:
List comprehensions
List comprehensions provide a concise way to create lists. It consists of brackets containing an expression
followed by a for clause, then zero or more for or if clauses. The expressions can be anything, i.e., all kinds
of objects can be in lists. The result will
>>> be a new list resulting from evaluating the expression in the context
eng2sp.has_key(’one’)
of the for and if clauses which follow it. The list comprehension always returns a result list.
True
Syntax
The list comprehension starts with a '[' and ']', to help you remember that the result is going
to be a list.
List comprehension is a method to describe the process using which the list should be created. To do that,
the list is broken into two pieces. The first is a picture of what each element will look like, and the second is
what is done to get it.
For instance, let's say we have a list of words:
listOfWords = ["this","is","a","list","of","words"]
To take the first letter of each word and make a list out of it using list comprehension:
List comprehension supports more than one for statement. It will evaluate the items in all of the objects
sequentially and will loop over the shorter objects if one object is longer than the rest.
List comprehension supports an if statement, to only include into the list that fulfill a certain
members condition:
PROGRAM:
least = i
A[y] = tmp
aList = [54,26,93,17,77,31,44,55,20]
selectionsort(aList)
print(aList)
Insertion sort:
def insertionSort(alist):
= index
1]>currentvalue: alist[position]=alist[position-1]
position = position-1
alist[position]=currentvalue
alist = [54,26,93,17,77,31,44,55,20]
insertionSort(alist)
print(alist)
Quicksort:
from random import randrange
= start
store_index += 1
return lst
pivot = randrange(start, end + 1)
def sort(lst):
quick_sort(lst, 0, len(lst) -
1) return lst
print sort([345,45,89,569,23,67,56,90,100])
'' times =
n
while( times > 0 ):
output += '*'
times = times - 1
print(output)
histogram([2, 3, 6,
5])
output =
UNIT V
FILES, EXCEPTIONS
PART- A (2 Marks)
A Python module is a file containing Python definitions and statements. A module can define functions,
classes, and variables. A module can also include runnable code. Grouping related code into a module
makes the code easier to understand and use. It also makes the code logically organized.
return (x+y)
return (x-y)
What are Command-Line Arguments? Command-line arguments are simple parameters that are given
on the system's command line, and the values of these arguments are passed on to your program during
program execution.
8. What is an exception?
Whenever a runtime error occurs, it creates an exception. The program stops
execution and prints an error message. For example, dividing by zero creates an
exception:
print 55/0
ZeroDivisionError: integer division or modulo
9. What are the error messages that are displayed for the following exceptions?
a. Accessing a non-existent
list item
b. Accessing a key that isn’t in the
dictionary
c. Trying to open a non-
existent file a. IndexError:
list index out of range b.
KeyError: what
c. IOError: [Errno 2] No such file or directory:
'filename'
11. How do you handle the exception inside a program when you try to open a non-
existent
file?
filename = raw_input('Enter a file name: ')
try:
f = open (filename,
"r") except IOError:
print 'There is no file named', filename
13. What is the function of raise statement? What are its two arguments?
The raise statement is used to raise an exception when the program detects an error. It
takes two arguments: the exception type and specific information about the error.
19. What is the special file that each package in Python must contain?
Each package in Python must contain a special file called init .py
21. How do you use command line arguments to give input to the program?
Python sys module provides access to any command-line arguments via sys.argv. sys.argv is
the list of command-line arguments. len(sys.argv) is the number of command-line
arguments.
def copyFile(oldFile,
newFile):
f1 = open(oldFile, "r")
f2 = open(newFile, "w")
while True:
text = f1.read(50) if text
== "": break
f2.write(text) f1.close()
f2.close()
return
5. Mention the commands and their syntax for the following: get current
directory, changing directory, list, directories and files, make a new
directory, renaming and removing directory.
(a) Get current directory:
getcwd() Syntax : import
os
os.getc
wd()
(a) Changing directory: chdir()
Syntax:
os.chdir(‘C:\\Users’)
os.getc
wd()
(b) List directories and files:
listdir() Syntax: os.listdir()
(c)
Making a new
directory: mkdir()
Syntax:
os.mkdir(‘Newdir’)
(d) Renaming a directory:
rename()
os.rename(‘Newdir’,’Newna
me’) os.listdir()
(e) Removing a directory:
remove()
os.remove(‘NewName’)
def getStack():
return[]
def isempty(s):
if
s==
[]:
return
True
else:
return
False def
top(s):
if isempty(s):
return
None
else:
return s[len(s)-1]
def push(s,item):
s.append(item)
def pop(s):
if isempty(s):
return
None
else:
item=s[len(s)-1]
del s[len(s)-1]
return item
Program to call stack :
import stack
def today():
mystack=stack.getStack()
for item in range(1,7):
stack.push(mystack,item)
print('Pushing',item,'to stack')
print ('Stack items')
while not stack.isempty(mystack):
item=stack.pop(mystack)
print('Poping',item,'from stack')
def test2():
ex12.inputNumber()
def test3():
ex97.fun()
ex97.py:
def fun():
try:
x = float(raw_input("Your number: "))
inverse = 1.0 / x
except ValueError:
print "You should have given either an int or a float"
except ZeroDivisionError:
print "Infinity"
ex12.py:
def inputNumber () :
x = input ('Pick a number: ')
if x == 17 :
raise ValueError, '17 is a bad number'
return x
wordcount.py:
def wordCount():
cl=0
cw=0
cc=0
f=open("ex88.txt","r")
for line in f:
words=line.split()
cl +=1
cw +=len(words)
cc +=len(line)
print('No. of lines:',cl)
print('No. of words:',cw)
print('No. of
characters:',cc) f.close()