GE8151 Python Programming Unit 2 Question Bank With Example Code
GE8151 Python Programming Unit 2 Question Bank With Example Code
SYLLABUS
Python interpreter and interactive mode; values and types: int, float, boolean, string, and list; variables, expressions,
statements, tuple assignment, precedence of operators, comments; modules and functions, function definition and use, flow
of execution, parameters and arguments; Illustrative programs: exchange the values of two variables, circulate the values
of n variables, distance between two points.
PART-A
Q. Q&A
No.
1
4. Assess a program to assign and access variables
Python Variables
Python is not “statically typed”. We do not need to declare variables before using them, or declare their type. A
variable is created the moment we first assign a value to it.
# A floating point
salary = 1456.8
# A string
name = "John"
print(age)
print(salary)
print(name)
Output:
45
1456.8
John
Python Indentation
Most of the programming languages like C, C++, Java use braces { } to define a block of code. Python uses
indentation.
A code block (body of a function, loop etc.) starts with indentation and ends with the first unindented line. The
amount of indentation is up to you, but it must be consistent throughout that block.
Generally four whitespaces are used for indentation and is preferred over tabs. Here is an example.
Example code
for i in range(1,11):
print(i)
if i == 5:
break
Output:
2
How the input function works in Python :
When input() function executes program flow will be stopped until the user has given an input.
The text or message display on the output screen to ask a user to enter input value is optional i.e. the prompt,
will be printed on the screen is optional.
Whatever you enter as input, input function convert it into a string. if you enter an integer value
still input() function convert it into a string. You need to explicitly convert it into an integer in your code
using typecasting.
1. Arithmetic operators: Arithmetic operators are used to perform mathematical operations like addition,
subtraction, multiplication and division.
OPERAT
OR DESCRIPTION SYNTAX
2. Relational Operators: Relational operators compares the values. It either returns True or False according to
the condition.
OPERATOR DESCRIPTION SYNTAX
> Greater than: True if left operand is greater than the right x>y
< Less than: True if left operand is less than the right x<y
Greater than or equal to: True if left operand is greater than or equal to the
>= right x >= y
<= Less than or equal to: True if left operand is less than or equal to the right x <= y
3. Logical operators: Logical operators perform Logical AND, Logical OR and Logical NOT operations.
3
OPERATOR DESCRIPTION SYNTAX
and Logical AND: True if both the operands are true x and y
4. Bitwise operators: Bitwise operators acts on bits and performs bit by bit operation.
OPERATOR DESCRIPTION SYNTAX
| Bitwise OR x|y
~ Bitwise NOT ~x
5. Assignment operators: Assignment operators are used to assign values to the variables.
Add AND: Add right side operand with left side operand
+= and then assign to left operand a+=b a=a+b
//= Divide(floor) AND: Divide left operand with right a//=b a=a//b
4
operand and then assign the value(floor) to left operand
Logical operators
Logical operators are the and, or, not operators.
5
5. print('x and y is',x and y)
6.
7. # Output: x or y is True
8. print('x or y is',x or y)
9.
10. # Output: not x is False
11. print('not x is',not x)
Here is the truth table for these operators.
Bitwise operators
Bitwise operators act on operands as if they were string of binary digits. It operates bit by bit, hence the name.
A tuple is a sequence of immutable Python objects. Tuples are sequences, just 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. Optionally you can put these comma-
separated values between parentheses also. For example −
tup1 = ('physics', 'chemistry', 1997, 2000);
tup2 = (1, 2, 3, 4, 5 );
tup3 = "a", "b", "c", "d";
The following table lists all operators from highest precedence to lowest.
6
Operator Description
~+- Complement, unary plus and minus (method names for the last two are +@ and
-@)
7
11. Define the scope and lifetime of a variable in Python.
Variable scope and lifetime
Not all variables are accessible from all parts of our program, and not all variables exist for the same amount of
time. Where a variable is accessible and how long it exists depend on how it is defined. We call the part of a
program where a variable is accessible its scope, and the duration for which the variable exists its lifetime.
A variable which is defined in the main body of a file is called a global variable. It will be visible throughout the
file, and also inside any file which imports that file. Global variables can have unintended consequences because of
their wide-ranging effects – that is why we should almost never use them. Only objects which are intended to be
used globally, like functions and classes, should be put in the global namespace.
A variable which is defined inside a function is local to that function. It is accessible from the point at which it is
defined until the end of the function, and exists for as long as the function is executing.
> A file containing Python code, for example: test.py, is called a module, and its name would be test..
Module: it’s a .py file that contains a list of functions (it can also contain variables and classes). Eg. in
8
statistics.mean(a), mean is a function that is found in the statistics module.
2) Purpose of Modules
> As our program grows more in the size we may want to split it into several files for easier maintenance as well as
re-usability of the code. The solution to this is Modules.
> We can define your most used functions in a module and import it, instead of copying their definitions into
different programs. A module can be imported by another program to make use of its functionality. This is how you
can use the Python standard library as well.
3) Types of Modules
> Python provides us with some built-in modules, which can be imported by using the “import” keyword.
> Python also allows us to create your own modules and use them in your programs.
This contains factorial, power, and logarithmic functions, but also some trigonometry and constants.
i) import math
And then:
math.factorial(5)
math.pi
math.sqrt(5)
math.log(256, 2)
m.factorial(5)
m.pi
m.sqrt(5)
m.log(256, 2)
price=1000
9
def mul(x, y):
return (x*y)
print calc.add(10, 2)
15. List the syntax for function call with and without
Arguments
Functions in Python
A function in Python is defined with the def keyword. Functions do not have declared return types. A function
without an explicit return statement returns None. In the case of no arguments and no return value, the definition is
very simple.
Function call without arguments
Calling the function is performed by using the call operator () after the name of the function.
10
Function call with arguments
# Driver code
evenOdd(2)
evenOdd(3)
Output:
even
odd
11
Python Recursion Function – Pros & Cons
18. What are the two parts of function definition. Give its syntax.
'''Function definition and invocation.'''
def happyBirthdayEmily():
print("Happy Birthday to you!")
print("Happy Birthday to you!")
print("Happy Birthday, dear Emily.")
print("Happy Birthday to you!")
happyBirthdayEmily()
happyBirthdayEmily()
12
'''Function with parameter called in main'''
def happyBirthday(person):
print("Happy Birthday to you!")
print("Happy Birthday to you!")
print("Happy Birthday, dear " + person + ".")
print("Happy Birthday to you!")
def main():
happyBirthday('Emily')
happyBirthday('Andre')
main()
19. Point out the difference between recursive and iterative technique.
The following highlights the differnce between two types of algorithms: Iterative and Recursive algorithms.
The challenge we will focus on is to define a function that returns the result of 1+2+3+4+….+n where n is a
parameter.
The following code uses a loop – in this case a counting loop, aka a “For Loop”.
This is the main characteristic of iterative code: it uses loops.
Iterative Approach
Python
1 # iterative Function (Returns the result of: 1 +2+3+4+5+...+n)
2 def iterativeSum(n):
3 total=0
4 for i in range(1,n+1):
5 total += i
6 return total
The following code uses a function that calls itself. This is the main characteristic of a recursive approach.
13
OUTPUT
Using an interative approach
1+2+3+4+...+99+100=
5050
Python *args
Python has *args which allow us to pass the variable number of non keyword arguments to function.
In the function, we should use an asterisk * before the parameter name to pass variable length arguments.The
arguments are passed as a tuple and these passed arguments make tuple inside the function with same name as the
parameter excluding asterisk *.
Example : Using *args to pass the variable length arguments to the function
1. def adder(*num):
2. sum = 0
3.
4. for n in num:
5. sum = sum + n
6.
7. print("Sum:",sum)
8.
9. adder(3,5)
10. adder(4,5,6,7)
11. adder(1,2,3,5,6)
Sum: 8
Sum: 22
Sum: 17
In the above program, we used *num as a parameter which allows us to pass variable length argument list to
the adder() function. Inside the function, we have a loop which adds the passed argument and prints the result. We
passed 3 different tuples with variable length as an argument to the function.
PART-B
1. i) Illustrate a program to display different data types using variables and literals constants.
14
Python has six standard Data Types:
Numbers
String
List
Tuple
Set
Dictionary
15
defined by values separated by 2 print(Set)
a comma inside braces { }.
ii) Show how an input and output function is performed in Python with an example.
Python provides functions input() and print() that are used for standard input and output operations respectively.
print(1,2,3,4)
# Output: 1 2 3 4
print(1,2,3,4,sep='*')
# Output: 1*2*3*4
print(1,2,3,4,sep='#',end='&')
# Output: 1#2#3#4&
Output formatting
Sometimes we would like to format our output to make it look attractive. This can be done by using
the str.format() method. This method is visible to any string object.
1. >>> x = 5; y = 10
2. >>> print('The value of x is {} and y is {}'.format(x,y))
3. The value of x is 5 and y is 10
16
Here the curly braces {} are used as placeholders. We can specify the order in which it is printed by
Python Input
To allow flexibility we might want to take the input from the user.
In Python, we have the input() function to allow this. The syntax for input() is
input([prompt])
When our program grows bigger, it is a good idea to break it into different modules.
A module is a file containing Python definitions and statements. Python modules have a filename and end with the
extension .py.
Definitions inside a module can be imported to another module or the interactive interpreter in Python. We use
the import keyword to do this.
For example, we can import the math module by typing in import math.
import math
print(math.pi)
Now all the definitions inside math module are available in our scope. We can also import some specific attributes
and functions only, using the from keyword. For example:
1. >>> from math import pi
2. >>> pi
3. 3.141592653589793
2. Explain in detail about the various operators in python with suitable examples.
Operator in Python
#1: Arithmetic operators in Python #2: Comparison operators in Python #3: Logical Operators in
Python
17
1. x = True
2. y = False
1. x = 15 1. x = 10 3.
2. y=4 2. y = 12 4. # Output: x and y is
3. 3. False
4. # Output: x + y = 19 4. # Output: x > y is False 5. print('x and y is',x and y)
5. print('x + y =',x+y) 5. print('x > y is',x>y) 6.
6. 6. 7. # Output: x or y is True
7. # Output: x - y = 11 7. # Output: x < y is True 8. print('x or y is',x or y)
8. print('x - y =',x-y) 8. print('x < y is',x<y) 9.
9. 9. 10. # Output: not x is False
10. # Output: x * y = 60 10. # Output: x == y is False 11. print('not x is',not x)
11. print('x * y =',x*y) 11. print('x == y is',x==y)
12. 12.
13. # Output: x / y = 3.75 13. # Output: x != y is True
14. print('x / y =',x/y) 14. print('x != y is',x!=y)
15. 15.
16. # Output: x // y = 3 16. # Output: x >= y is False
17. print('x // y =',x//y) 17. print('x >= y is',x>=y)
18. 18.
19. # Output: x ** y = 50625 19. # Output: x <= y is True
20. print('x ** y =',x**y) 20. print('x <= y is',x<=y)
x | y = 14 -= x -= 5 x=x-5
Bitwise (0000
| OR 1110)
*= x *= 5 x=x*5
~x = -11
Bitwise (1111 /= x /= 5 x=x/5
~ NOT 0101)
18
x^y= %= x %= 5 x=x%5
Bitwise 14 (0000
^ XOR 1110) //= x //= 5 x = x // 5
x<< 2 = |= x |= 5 x=x|5
Bitwise 40 (0010
<< left shift 1000)
^= x ^= 5 x=x^5
3.
Python List
List is an ordered sequence of items. It is one of the most used datatype in Python and is very flexible. All the items
in a list do not need to be of the same type.
Declaring a list
We can use the slicing operator [ ] to extract an item or a range of items from a list. Index starts form 0 in Python.
a = [5,10,15,20,25,30,35,40]
# a[2] = 15
print("a[2] = ", a[2])
# a[0:3] = [5, 10, 15]
print("a[0:3] = ", a[0:3])
# a[5:] = [30, 35, 40]
print("a[5:] = ", a[5:])
1. >>> a = [1,2,3]
2. >>> a[2]=4
3. >>> a
4. [1, 2, 4]
19
ii) Discuss the various operation that can be
performed on a tuple and lists (minimum 5) with an example program
LIST OPERATIONS
20
len(list_name) Output:
10
index(): Returns the List = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1]
index of first print(List.index(2))
occurrence. Start and Output:
End index are not
necessary parameters. 1
Syntax:
List.index(element[,sta
rt[,end]])
21
Output:
2.5
Tuples in Python
A Tuple is a collection of Python objects separated by commas. In someways a tuple is similar to a list
in terms of indexing, nested objects and repetition
but a tuple is immutable unlike lists which are mutable.
Tuple Operation
Creating Tuples
# An empty tuple
empty_tuple = ()
print (empty_tuple)
Output:
()
# Creating non-empty tuples
Concatenation of Tuples
# Code for concatenating 2 tuples
22
tuple1 = (0, 1, 2, 3)
tuple2 = ('python', 'geek')
# Concatenating above two
print(tuple1 + tuple2)
Output:
(0, 1, 2, 3, 'python', 'geek')
Nesting of Tuples
# Code for creating nested tuples
tuple1 = (0, 1, 2, 3)
tuple2 = ('python', 'geek')
tuple3 = (tuple1, tuple2)
print(tuple3)
Output :
((0, 1, 2, 3), ('python', 'geek'))
Repetition in Tuples
tuple3 = ('python',)*3
print(tuple3)
Output
('python', 'python', 'python')
23
Not the same
Maximum element in tuples 1,2: python,coder
Minimum element in tuples 1,2: geek,1
Numeric Literals
You can refer to numeric values using integers, floating point numbers, scientific notation,
hexadecimal notation, octal, and complex numbers:
Python integers can be an size. Integers larger than 2147483647 are called "long" integers because
they can't be stored in 32 bits.
123 # an integer
the second
the second
24
% Modulus: returns the remainder when first x%y
When you type a statement on the command line, Python executes it.
An expression is a combination of values, variables, operators, and calls to functions. If you type an
expression at the Python prompt,
the interpreter evaluates it and displays the result, which is always a value:
Python expressions
length = 5
breadth = 2
25
6. i) What is membership and identity operators.
Python Membership(in, not in) & Identity Operators ( is, is not)
Membership Operators
Membership operators are operators used to validate the membership of a value.
It test for membership in a sequence, such as strings, lists, or tuples.
1. ‘not in’ operator- Evaluates to true if it does
not finds a variable in the specified sequence
1. in operator : The ‘in’ operator is and false otherwise.
used to check if a value exists in a # Python program to illustrate
sequence or not. Evaluates to true if # not 'in' operator
it finds a variable in the specified x = 24
sequence and false otherwise. y = 20
# Python program to illustrate list = [10, 20, 30, 40, 50 ];
# Finding common member in list
# using 'in' operator if ( x not in list ):
list1=[1,2,3,4,5] print "x is NOT present in given list"
list2=[6,7,8,9] else:
for item in list1: print "x is present in given list"
if item in list2:
print("overlapping") if ( y in list ):
else: print "y is present in given list"
print("not overlapping") else:
Output: print "y is NOT present in given list"
not overlapping
Identity operators
In Python are used to determine whether a value is of a certain class or type. They are
usually used to determine the type of data a certain variable contains.
There are different identity operators such as
1. ‘is’ operator – Evaluates to true if
the variables on either side of the
operator point to the same object 1. ‘is not’ operator – Evaluates to false
and false otherwise. 2. if the variables on either side of the operator
# Python program to illustrate the use 3. point to the same object and true otherwise.
# of 'is' identity operator # Python program to illustrate the
x=5 # use of 'is not' identity operator
if (type(x) is int): x = 5.2
print ("true") if (type(x) is not int):
else: print ("true")
print ("false") else:
Output: print ("false")
Output:
true
true
26
a=9
b=4
# Addition of numbers
add = a + b
# Subtraction of numbers
sub = a - b
# Multiplication of number
mul = a * b
# Division(float) of number
div1 = a / b
# Division(floor) of number
div2 = a // b
# Modulo of both number
mod = a % b
# print results
print(add)
print(sub)
print(mul)
print(div1)
print(div2)
print(mod)
13
5
36
2.25
2
1
Output:
13
5
36
2.25
2
1
27
7. i) Formulate the difference between type casting and type coercion with suitable
example.
Casting is when you convert a variable value from one type to another. This is, in Python,
done with functions
such as int() or float() or str() . A very common pattern is that you convert a number, currently
as a string into a proper number.
# initializing string
s = "10010"
ii) Write a program to print the digit at ones place and hundreds place of a number.
Functions in Python
You use functions in programming to bundle a set of instructions that you want to use repeatedly or
that, because of their complexity, are better self-contained in a sub-program and called when needed.
That means that a function is a piece of code written to carry out a specified task. To carry out that
specific task, the function might or might not need multiple inputs. When the task is carried out, the
function can or can not return one or more values.
There are three types of functions in Python:
Built-in functions, such as help() to ask for help, min() to get the minimum value, print() to
print an object to the terminal,… You can find an overview with more of these functions here.
User-Defined Functions (UDFs), which are functions that users create to help them out; And
Anonymous functions, which are also called lambda functions because they are not declared
with the standard def keyword.
28
my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
ii) Illustrate a program to exchange the value of two variables with temporary variables
# Program published on https://beginnersbook.com
1) It tells the return type of the data that the function will return.
2) It tells the number of arguments passed to the function.
3) It tells the data types of the each of the passed arguments.
4) Also it tells the order in which the arguments are passed to the function.
Therefore essentially, function prototype specifies the input/output interlace
to the function i.e. what to give to the function and what to expect from the function.
Prototype of a function is also called signature of the function.
.
10. i) Analyze the difference between local and global variables.
Example-1
# This function uses global variable s
def f():
print s
29
# Global scope
s = "I am Global variable"
f()
Output:
I am Global variable
a =1
Example-2
# Uses global because there is no local 'a'
def f():
print 'Inside f() : ', a
# Global scope
print 'global : ',a
f()
print 'global : ',a
g()
print 'global : ',a
h()
print 'global : ',a
Output:
global : 1
Inside f() : 1
global : 1
Inside g() : 2
global : 1
Inside h() : 3
global : 3
30
# Will add values from n to the new list
for item in range(len(lists) - num, len(lists)):
output_list.append(lists[item])
return output_list
# Driver Code
rotate_num = 3
list_1 = [1, 2, 3, 4, 5, 6]
print(rightRotate(list_1, rotate_num))
Output :
[4, 5, 6, 1, 2, 3]
Lambda functions can have any number of arguments but only one expression. The expression is
evaluated and returned. Lambda functions can be used wherever function objects are required.
31
In the above program, lambda x: x * 2 is the lambda function. Here x is the argument and x * 2 is the
expression that gets evaluated and returned.
ii) Describe in detail about the rules to be followed while using lambda function.
Python lambda (Anonymous Functions)
In Python, anonymous function means that a function is without a name. As we already know
that def keyword is used to define the normal functions and the lambda keyword is used to create
anonymous functions. It has the following syntax:
lambda arguments: expression
This function can have any number of arguments but only one expression, which is evaluated
and returned.
One is free to use lambda functions wherever function objects are required.
You need to keep in your knowledge that lambda functions are syntactically restricted to a
single expression.
It has various uses in particular fields of programming besides other types of expressions in
functions.
12. i) Explain with an example program to return the average of given number passed as
argument to a function.
# Python program to get average of a list
# Using reduce() and lambda
# importing reduce()
from functools import reduce
def Average(lst):
return reduce(lambda a, b: a + b, lst) / len(lst)
# Driver Code
lst = [15, 9, 55, 41, 35, 20, 62, 49]
average = Average(lst)
# importing mean()
from statistics import mean
def Average(lst):
return mean(lst)
# Driver Code
lst = [15, 9, 55, 41, 35, 20, 62, 49]
average = Average(lst)
32
Output:
Average of the list = 35.75
def cal_average(num):
sum_num = 0
for t in num:
sum_num = sum_num + t
A function is a block of organized, reusable code that is used to perform a single, related action.
Functions provide better modularity for your application and a high degree of code reusing.
As you already know, Python gives you many built-in functions like print(), etc. but you can also create
your own functions. These functions are called user-defined functions.
Defining a Function
You can define functions to provide the required functionality. Here are simple rules to define a
function in Python.
Function blocks begin with the keyword def followed by the function name and parentheses (
( ) ).
Any input parameters or arguments should be placed within these parentheses. You can also
define parameters inside these parentheses.
The first statement of a function can be an optional statement - the documentation string of the
function or docstring.
The code block within every function starts with a colon (:) and is indented.
The statement return [expression] exits a function, optionally passing back an expression to the
caller. A return statement with no arguments is the same as return None.
Syntax
33
13. i) Describe the syntax and rules involved in the return statement in Python.
A return statement is used to end the execution of the function call and “returns” the result (value of
the expression following the return keyword) to the caller. The statements after the return statements
are not executed. If the return statement is without any expression, then the special value None is
returned.
Syntax:
def fun():
statements
.
.
return [expression]
Example:
# Python program to
# demonstrate return statement
def is_true(a):
# returning boolean of a
return bool(a)
# calling function
res = add(2, 3)
print("Result of add function is {}".format(res))
res = is_true(2<5)
print("\nResult of is_true function is {}".format(res))
Output:
Result of add function is 5
Result of is_true function is True
>>>
>>> def fib2(n): # return Fibonacci series up to n
... """Return a list containing the Fibonacci series up to n."""
... result = []
34
... a, b = 0, 1
... while a < n:
... result.append(a) # see below
... a, b = b, a+b
... return result
...
>>> f100 = fib2(100) # call it
>>> f100 # write the result
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
For example:
1.
2. >>> 5 - 7
3. -2
Here 5 - 7 is an expression.
There can be more than one operator in an expression. To evaluate these type of expressions there is a
rule of precedence in Python. It guides the order in which operation are carried out.
Operators Meaning
() Parentheses
** Exponent
35
+x, -x, ~x Unary plus, Unary minus, Bitwise NOT
+, - Addition, Subtraction
^ Bitwise XOR
| Bitwise OR
or Logical OR
Associativity is the order in which an expression is evaluated that has multiple operator of the same
precedence. Almost all the operators have left-to-right associativity.
For example, multiplication and floor division have the same precedence. Hence, if
# Left-right associativity
# Output: 3
print(5 * 2 // 3)
# Shows left-right associativity
# Output: 0
print(5 * (2 // 3))
Run
Powered by DataCamp
36
ii) Write a Python program to exchange the value of two variables
iii) Write a Python program using function to find the sum of first ‘n’ even numbers
and print the result.
Python program to get input n and calculate the sum of even numbers till n
Solution
n=int(input("Enter n value:"))
sum=0
for i in range(2,n+1,2):
sum+=i
print(sum)
37