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

GE8151 Python Programming Unit 2 Question Bank With Example Code

Python has two modes: script mode and interactive mode. Script mode runs entire programs while interactive mode runs code line-by-line. Data types in Python include numeric, string, list, tuple, and dictionary. Variables are created when a value is assigned and do not require explicit typing. Python uses indentation rather than brackets to define code blocks. The input() function pauses code execution to accept user input as a string. Basic operators in Python include arithmetic, relational, logical, bitwise, and assignment operators.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
761 views

GE8151 Python Programming Unit 2 Question Bank With Example Code

Python has two modes: script mode and interactive mode. Script mode runs entire programs while interactive mode runs code line-by-line. Data types in Python include numeric, string, list, tuple, and dictionary. Variables are created when a value is assigned and do not require explicit typing. Python uses indentation rather than brackets to define code blocks. The input() function pauses code execution to accept user input as a string. Basic operators in Python include arithmetic, relational, logical, bitwise, and assignment operators.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

GE8151 PROBLEM SOLVING AND PYTHON PROGRAMMING

UNIT 2 - DATA, EXPRESSIONS, STATEMENTS

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. Define the two modes in Python.


Python has two basic modes: script and interactive. The normal mode is the mode
where the scripted and finished .py files are run in the Python interpreter. 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.
Interactive mode is a good way to play around and try variations on syntax.
The basic differences between these two modes are as follows: Interactive mode is
used when an user wants to run one single line or one block of code. It runs very quickly and gives the output
instantly. Script Mode, on the other hand , is used when the user is working with more than one single code or a
block of code
2. Give the various data types in Python
Python Data Types
There are different types of python data types. Some built-in python data types are:
1. Python Data Type – Numeric
Python numeric data type is used to hold numeric values like;
1. int – holds signed integers of non-limited length.
2. long- holds long integers(exists in Python 2.x, deprecated in Python 3.x).
3. float- holds floating precision numbers and it’s accurate upto 15 decimal places.
4. complex- holds complex numbers.
In Python we need not to declare datatype while declaring a variable like C or C++. We can simply just assign
values in a variable.
2. Python Data Type – String
The string is a sequence of characters. Python supports Unicode characters. Generally, strings are represented by
either single or double quotes.
3. Python Data Type – List
The list is a versatile data type exclusive in Python. In a sense, it is the same as the array in C/C++. But the
interesting thing about the list in Python is it can simultaneously hold different types of data. Formally list is an
ordered sequence of some data written using square brackets([]) and commas(,).
4. Python Data Type – Tuple
Tuple is another data type which is a sequence of data similar to list. But it is immutable. That means data in a tuple
is write protected. Data in a tuple is
5. Dictionary
Python Dictionary is an unordered sequence of data of key-value pair form. It is similar to the hash table type.
Dictionaries are written within curly braces in the form key:value.
3. Point out the rules to be followed for naming any identifier
A Python identifier is a name used to identify a variable, function, class, module or other object.
An identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero or more letters, underscores
and digits (0 to 9).

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.

The following is a sample program used to assign and access variables :


# An integer assignment
age = 45

# A floating point
salary = 1456.8

# A string
name = "John"

print(age)
print(salary)
print(name)

Output:
45
1456.8
John

5. Compose the importance of indentation in Python

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

6. Select and assign how an input operation was done in Python.


input ( ) : This function first takes the input from the user and then evaluates the expression, which means Python
automatically identifies whether user entered a string or a number or list. If the input provided is not correct then
either syntax error or exception is raised by python. For example –
# Python program showing a use of input()

val = input("Enter your value: ")


print(val)

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.

7. Demonstrate the various operations in Python


Basic Operators in Python

1. Arithmetic operators: Arithmetic operators are used to perform mathematical operations like addition,
subtraction, multiplication and division.
OPERAT
OR DESCRIPTION SYNTAX

+ Addition: adds two operands x+y

- Subtraction: subtracts two operands x-y

* Multiplication: multiplies two operands x*y

/ Division (float): divides the first operand by the second x/y

// Division (floor): divides the first operand by the second x // y

Modulus: returns the remainder when first operand is divided by


% the second x%y

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

== Equal to: True if both operands are equal x == y

!= Not equal to - True if operands are not equal 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

or Logical OR: True if either of the operands is true x or y

not Logical NOT: True if operand is false not x

4. Bitwise operators: Bitwise operators acts on bits and performs bit by bit operation.
OPERATOR DESCRIPTION SYNTAX

& Bitwise AND x&y

| Bitwise OR x|y

~ Bitwise NOT ~x

^ Bitwise XOR x^y

>> Bitwise right shift x>>

<< Bitwise left shift x<<

5. Assignment operators: Assignment operators are used to assign values to the variables.

OPERATOR DESCRIPTION SYNTAX

Assign value of right side of expression to left side


= operand x=y+z

Add AND: Add right side operand with left side operand
+= and then assign to left operand a+=b a=a+b

Subtract AND: Subtract right operand from left operand


-= and then assign to left operand a-=b a=a-b

Multiply AND: Multiply right operand with left operand


*= and then assign to left operand a*=b a=a*b

Divide AND: Divide left operand with right operand and


/= then assign to left operand a/=b a=a/b

Modulus AND: Takes modulus using left and right


%= operands and assign result 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

Exponent AND: Calculate exponent(raise power) value


**= using operands and assign value to left operand a**=b a=a**b

Performs Bitwise AND on operands and assign value to


&= left operand a&=b a=a&b

Performs Bitwise OR on operands and assign value to left


|= operand a|=b a=a|b

Performs Bitwise xOR on operands and assign value to


^= left operand a^=b a=a^b

Performs Bitwise right shift on operands and assign value


>>= to left operand a>>=b a=a>>b

Performs Bitwise left shift on operands and assign value a <<= b a= a


<<= to left operand << b

6. Special operators: There are some special type of operators like-


 Identity operators-
is and is not are the identity operators both are used to check if two values are located on the same part
of the memory. Two variables that are equal does not imply that they are identical.
 is True if the operands are identical
is not True if the operands are not identical

8. Discover the difference between logical and bitwise


operator.

Logical operators
Logical operators are the and, or, not operators.

Operator Meaning Example

and True if both the operands are true x and y

or True if either of the operands is true x or y

not True if operand is false (complements the operand) not x

Logical operators in Python

Example #3: Logical Operators in Python


1. x = True
2. y = False
3.
4. # Output: x and y is False

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.

For example, 2 is 10 in binary and 7 is 111.


In the table below: Let x = 10 (0000 1010 in binary) and y = 4 (0000 0100 in binary)

Operator Meaning Example

& Bitwise AND x& y = 0 (0000 0000)

| Bitwise OR x | y = 14 (0000 1110)

~ Bitwise NOT ~x = -11 (1111 0101)

^ Bitwise XOR x ^ y = 14 (0000 1110)

>> Bitwise right shift x>> 2 = 2 (0000 0010)

<< Bitwise left shift x<< 2 = 40 (0010 1000)

Bitwise operators in Python

9. What is a tuple? How literals of type tuple are written?


Give examples.

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";

10. Give the operator precedence in Python.

The following table lists all operators from highest precedence to lowest.

6
Operator Description

** Exponentiation (raise to the power)

~+- Complement, unary plus and minus (method names for the last two are +@ and
-@)

* / % // Multiply, divide, modulo and floor division

+- Addition and subtraction

>> << Right and left bitwise shift

& Bitwise 'AND'td>

^| Bitwise exclusive `OR' and regular `OR'

<= < > >= Comparison operators

<> == != Equality operators

= %= /= //= -= += *= Assignment operators


**=

is is not Identity operators

in not in Membership operators

not or and Logical operators

Operator precedence affects how an expression is evaluated.


For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher precedence than +, so it first
multiplies 3*2 and then adds into 7.

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.

12. Point out the uses of default arguments in Python.

13. Generalize the uses of Python module.


Python Language Modules
1) What is Python Module?
2) Purpose of Modules
3) Types of Modules
4) How to use Modules
5) User defined Modules in Python

1) What is Python Module?


> A module is a file consisting of Python code. It can define functions, classes, and variables, and can also include
runnable code. Any Python file can be referenced as a module.

> A file containing Python code, for example: test.py, is called a module, and its name would be test..

Module vs. Function


Function: it’s a block of code that you can use/reuse by calling it with a keyword. Eg. print() is a function.

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.

4) How to use Modules


There is a Python Standard Library with dozens of built-in modules. From those, five important modules,

random, statistics, math, datetime, csv

Python math module,

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)

ii) import math as m


And then:

m.factorial(5)
m.pi
m.sqrt(5)
m.log(256, 2)

5) User defined Modules in Python


i) Create a module
# A simple module, calc.py

price=1000

def add(x, y):


return (x+y)

def sub(x, y):


return (x-y)

9
def mul(x, y):
return (x*y)

ii) Use Module


# importing module calc.py
import calc

print calc.add(10, 2)

# from calc import mul


print(add(10, 2))

14. Demonstrate how a function calls another function.

Justify your answer.

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.

>>> def hello_function():


... print 'Hello World, it\'s me. Function.'
...
>>> hello_function()
Hello World, it's me. Function.

10
Function call with arguments

# A simple Python function to check


# whether x is even or odd
def evenOdd( x ):
if (x % 2 == 0):
print "even"
else:
print "odd"

# Driver code
evenOdd(2)
evenOdd(3)
Output:
even
odd

16. Define recursive function


In programming, recursion is when a function calls itself.

1. >>> def factorial(n):


2. if n==1:
3. return 1
4. return n*factorial(n-1)
5. >>> factorial(5)
120

11
Python Recursion Function – Pros & Cons

a. Python Recursion Function Advantages

With Python recursion, there are some benefits we observe:

1. A recursive code has a cleaner-looking code.


2. Recursion makes it easier to code, as it breaks a task into smaller ones.
3. It is easier to generate a sequence using recursion than by using nested iteration.
b. Python Recursion Function Disadvantages

The flip side of the coin is easy to quote:

1. Although it makes code look cleaner, it may sometimes be hard to follow.


2. They may be simpler, but recursive calls are expensive. They take up a lot of memory and time.
3. Finally, it isn’t as easy to debug a recursive function.

17. Define the syntax for passing arguments


The special syntax *args in function definitions in python is used to pass a variable number of arguments to a
function. It is used to pass a non-keyworded, variable-length argument list.

 Example for usage of *arg:

# Python program to illustrate


# *args with first extra argument
def myFun(arg1, *argv):
print ("First argument :", arg1)
for arg in argv:
print("Next argument through *argv :", arg)

myFun('Hello', 'Welcome', 'to', 'GeeksforGeeks')


Output:
First argument : Hello
Next argument through *argv : Welcome
Next argument through *argv : to
Next argument through *argv : GeeksforGeeks

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.

Recursive vs. Iterative Algorithms

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 Iterative Approach

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 Recursive Approach

The following code uses a function that calls itself. This is the main characteristic of a recursive approach.

1 # Recursive Function (Returns the result of: 1 +2+3+4+5+...+n)


2 def recursiveSum(n):
3 if (n > 1):
4 return n + recursiveSum(n - 1)
5 else:
6 return n

13
OUTPUT
Using an interative approach
1+2+3+4+...+99+100=
5050

Using a recursive approach


1+2+3+4+...+99+100=
5050

20. Give the syntax for variable length arguments.

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)

When we run the above program, the output will be

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.

Python Data Types


A Data Type describes the characteristic of a variable.

14
Python has six standard Data Types:
 Numbers
 String
 List
 Tuple
 Set
 Dictionary

Data Type Example Output


#1) Numbers Example: Output: 5 is of type
In Numbers, there are mainly 3 1a=5 <class ‘int'>
types which include Integer, 2 print(a, "is of type", type(a))
Float, and Complex.

1 b = 2.5 Output: 2.5 is of type


2 print(b, "is of type", type(b)) <class ‘float'>

1 c = 6+2j Output: (6+2j) is a


2 print(c, "is a type", type(c)) type <class
‘complex'>

#2) String Example: Output: Welcome To


A string is an ordered sequence 1 String1 = "Welcome" Python
of characters. 2 String2 ="To Python"
3 print(String1+String2)

#3) List Example: Output: List[2] = 5.5


A list can contain a series of 1 List = [2,4,5.5,"Hi"]
values. 2 print("List[2] = ", List[2])

List variables are declared by


using brackets [ ]. A list is
mutable, which means we can
modify the list.

#4) Tuple Example: Output: Tuple[1]


A tuple is a sequence of Python 1 Tuple = (50,15,25.6,"Python") = 15
objects separated by commas. print("Tuple[1] = ", Tuple[1])
2
1 print("Tuple[0:3] =", Tuple[0:3])
Tuples are immutable, which
means tuples once created
Output: Tuple[0:3]
cannot be modified. Tuples are
= (50, 15, 25.6)
defined using parentheses ().

#5) Set Example: Output: {‘python', 1,


A set is an unordered 1 Set = {5,1,2.6,"python"} 5, 2.6}
collection of items. Set is

15
defined by values separated by 2 print(Set)
a comma inside braces { }.

#6) Dictionary Syntax: Output: {1: ‘Hi', 2:


Dictionaries items are stored Key:value 7.5, 3: ‘Class'}
and fetched by using the key. Example:
Dictionaries are used to store a 1 Dict = {1:'Hi',2:7.5, 3:'Class'}
huge amount of data. To print(Dict) Output: 7.5
retrieve the value we must
know the key. In Python, 2 Example:
dictionaries are defined within
1 print(Dict[2])
braces {}.

We use the key to retrieve the


respective value. But not the
other way around.

ii) Show how an input and output function is performed in Python with an example.

Python Input, Output and Import

Python provides functions input() and print() that are used for standard input and output operations respectively.

Python Output Using print() function


We use the print() function to output data to the standard output device (screen).

print('This sentence is output to the screen')


# Output: This sentence is output to the screen
a=5
print('The value of a is', a)
# Output: The value of a is 5

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

print('I love {0} and {1}'.format('bread','butter'))


# Output: I love bread and butter
print('I love {1} and {0}'.format('bread','butter'))
# Output: I love butter and bread

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])

where prompt is the string we wish to display on the screen. It is optional.


1. >>> num = input('Enter a number: ')
2. Enter a number: 10
3. >>> num
4. '10'
Here, we can see that the entered value 10 is a string, not a number. To convert this into a number we can
use int() or float() functions.
1. >>> int('10')
2. 10
3. >>> float('10')
4. 10.0
Python Import

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)

Bitwise operators #5: Membership


Assignment operators are used in operators in Python
Python to assign values to variables.
Bitwise operators act on operands as 1. x = 'Hello world'
if they were string of binary digits. It 2. y = {1:'a',2:'b'}
operates bit by bit, hence the name. a = 5 is a simple assignment operator 3.
that assigns the value 5 on the right to 4. # Output: True
the variable a on the left. 5. print('H' in x)
For example, 2 is 10 in binary and 7 There are various compound operators 6.
is 111. in Python like a += 5 that adds to the 7. # Output: True
In the table below: Let x = 10 (0000 variable and later assigns the same. It 8. print('hello' not in x)
1010 in binary) and y = 4 (0000 is equivalent to a = a + 5. 9.
0100 in binary)
10. # Output: True
Equivatent 11. print(1 in y)
Operator Meaning Example Operator Example to 12.
13. # Output: False
x& y = 0 = x=5 x=5 14. print('a' in y)
Bitwise (0000
& AND 0000) += x += 5 x=x+5

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

Bitwise x>> 2 = **= x **= 5 x = x ** 5


right 2 (0000
>> shift 0010) &= x &= 5 x=x&5

x<< 2 = |= x |= 5 x=x|5
Bitwise 40 (0010
<< left shift 1000)
^= x ^= 5 x=x^5

>>= x >>= 5 x = x >> 5

<<= 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

Items separated by commas are enclosed within brackets [ ].

1. >>> a = [1, 2.2, 'python']

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:])

Lists are mutable, meaning, value of elements of a list can be altered.

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

List Operations Examples

Adding and Appending # Adds List Element as value of List.


 append(): Used for List = ['Mathematics', 'chemistry', 1997, 2000]
appending and adding List.append(20544)
elements to List.It is print(List)
used to add elements to Output:
the last position of
List. ['Mathematics', 'chemistry', 1997, 2000, 20544]
Syntax:
list.append (element)
 insert(): Inserts an List = ['Mathematics', 'chemistry', 1997, 2000]
elements at specified # Insert at index 2 value 10087
position. List.insert(2,10087)
Syntax: print(List)
list.insert(<position, Output:
element)
['Mathematics', 'chemistry', 10087, 1997, 2000, 20544]

 extend(): Adds List1 = [1, 2, 3]


contents to List2 to the List2 = [2, 3, 4, 5]
end of List1.
Syntax: # Add List2 to List1
List1.extend(List2) List1.extend(List2)
print(List1)

#Add List1 to List2 now


List2.extend(List1)
print(List2)
Output:
[1, 2, 3, 2, 3, 4, 5]
[2, 3, 4, 5, 1, 2, 3, 2, 3, 4, 5]
 sum() : Calculates sum List = [1, 2, 3, 4, 5]
of all the elements of print(sum(List))
List. Output:
Syntax:
sum(List) 15

 count():Calculates List = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1]


total occurrence of print(List.count(1))
given element of List. Output:
Syntax:
List.count(element) 4

 length:Calculates total List = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1]


length of List. print(len(List))
Syntax:

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]])

 min() : Calculates List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]


minimum of all the print(min(List))
elements of List. Output:
Syntax:
min(List) 1.054

 max(): Calculates List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]


maximum of all the print(max(List))
elements of List. Output:
Syntax:
max(List) 5.33

 reverse(): Sort the List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]


given data structure
(both tuple and list) in #Reverse flag is set True
ascending order. Key List.sort(reverse=True)
and reverse_flag are
not necessary #List.sort().reverse(), reverses the sorted list
parameter and print(List)
reverse_flag is set to Output:
False, if nothing is
passed through [5.33, 4.445, 3, 2.5, 2.3, 1.054]
sorted().
Syntax:
 sorted([list[,key[,Rever List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]
se_Flag]]]) sorted(List)
print(List)
Output:
list.sort([key,[Reverse_
flag]]) [1.054, 2.3, 2.5, 3, 4.445, 5.33]

Deletion of List Elements  pop(): Index is not a necessary parameter,


To Delete one or more if not mentioned takes the last index.
elements, i.e. remove an Syntax:
element, many built in list.pop([index])
functions can be used, such
as pop() & remove() and List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]
keywords such as del. print(List.pop())

21
Output:
2.5

 del() : Element to be List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]


deleted is mentioned del List[0]
using list name and print(List)
index. Output:
Syntax:
del list.[index] [4.445, 3, 5.33, 1.054, 2.5]
List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]
List.remove(3)
 remove(): Element to print(List)
be deleted is Output:
mentioned using list
name and element. [2.3, 4.445, 5.33, 1.054, 2.5]
Syntax:
list.remove(element)

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

# One way of creation


tup = 'python', 'geeks'
print(tup)

# Another for doing the same


tup = ('python', 'geeks')
print(tup)
Output
('python', 'geeks')
('python', 'geeks')

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

# Code to create a tuple with repetition

tuple3 = ('python',)*3
print(tuple3)
Output
('python', 'python', 'python')

Using cmp(), max() , min()

# A python program to demonstrate the use of


# cmp(), max(), min()

tuple1 = ('python', 'geek')


tuple2 = ('coder', 1)

if (cmp(tuple1, tuple2) != 0):

# cmp() returns 0 if matched, 1 when not tuple1


# is longer and -1 when tuple1 is shoter
print('Not the same')
else:
print('Same')
print ('Maximum element in tuples 1,2: ' +
str(max(tuple1)) + ',' +
str(max(tuple2)))
print ('Minimum element in tuples 1,2: ' +
str(min(tuple1)) + ',' + str(min(tuple2)))
Output

23
Not the same
Maximum element in tuples 1,2: python,coder
Minimum element in tuples 1,2: geek,1

4. i) What is a numeric literal? Give examples.

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

1.23 # a floating point number

-1.23 # a negative floating point number

1.23E45; # scientific notation

0x7b; # hexadecimal notation (decimal 123)

0173; # octal notation (decimal 123)

12+3*j; # complex number 12 + 3i (Note that Python uses "j"!)

2147483648L # a long integer

ii) Describe the arithmetic operators in Python


with an example.

1. Arithmetic operators: Arithmetic operators are used to perform


mathematical operations like addition, subtraction,
multiplication and division.
OPERATOR DESCRIPTION SYNTAX

+ Addition: adds two operands x+y

- Subtraction: subtracts two operands x-y

* Multiplication: multiplies two operands x*y

/ Division (float): divides the first operand by x/y

the second

// Division (floor): divides the first operand by x // y

the second

24
% Modulus: returns the remainder when first x%y

operand is divided by the second

# Examples of Arithmetic # print results Output:


Operator print(add)
a=9 print(sub) 13
b=4 print(mul) 5
print(div1)
# Addition of numbers print(div2) 36
add = a + b print(mod) 2.25
# Subtraction of numbers
sub = a - b 2
# Multiplication of number
1
mul = a * b
# Division(float) of number
div1 = a / b
# Division(floor) of number
div2 = a // b
# Modulo of both number
mod = a % b

5. Demonstrate the various expressions in Python with


suitable examples.
An expression is an instruction that combines values and operators and always evaluates down to a
single value.

Statements and expressions


A statement is an instruction that the Python interpreter can execute. Examples of statements are , the
assignment statement ,

the import statement. S, if statements, while statements, and for statements.

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

area = length * breadth


print('Area is', area)
print('Perimeter is', 2 * (length + breadth))

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

ii) Write a program to perform addition, subtraction, multiplication, integer division,


floor division and modulo division on two integer and float.
# Examples of Arithmetic Operator

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

1. Relational Operators: Relational operators compares the values. It either


returns True or False according t

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.

Python code to demonstrate Type conversion


# using int(), float()

# initializing string
s = "10010"

# printing string converting to int base 2


c = int(s,2)
print ("After converting to integer base 2 : ", end="")
print (c)

# printing string converting to float


e = float(s)
print ("After converting to float : ", end="")
print (e)
Output:
After converting to integer base 2 : 18
After converting to float : 10010.0

ii) Write a program to print the digit at ones place and hundreds place of a number.

iii) Write a program to convert temperature in


degree Fahrenheit to Celsius.
8. i) Discuss the need and importance of function in Python.
Functions are an essential part of the Python programming language. Many important
functions are built-in in the Python language. However, as a Data Scientist, developers
constantly need to write their own functions to solve problems that their data poses.

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.

def my_function(country = "Norway"):


print("I am from " + country)

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

# Python program to swap two variables

num1 = input('Enter First Number: ')


num2 = input('Enter Second Number: ')

print("Value of num1 before swapping: ", num1)


print("Value of num2 before swapping: ", num2)

# swapping two numbers using temporary variable


temp = num1
num1 = num2
num2 = temp

print("Value of num1 after swapping: ", num1)


print("Value of num2 after swapping: ", num2)
Output:

Enter First Number: 101


Enter Second Number: 99
Value of num1 before swapping: 101
Value of num2 before swapping: 99
Value of num1 after swapping: 99
Value of num2 after swapping: 101
iii)

9. Briefly discuss in detail about function prototyping in


python with suitable example program
What is the purpose of a function prototype?

The Function prototype serves the following purposes –

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

# Variable 'a' is redefined as a local


def g():
a =2
print 'Inside g() : ',a

# Uses global keyword to modify global 'a'


def h():
global a
a =3
print 'Inside h() : ',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

ii) Explain with an example program to circulate the values of n variables.


#circulate the values of n variables

# Python program to right rotate a list by n

# Returns the rotated list


def rightRotate(lists, num):
output_list = []

30
# Will add values from n to the new list
for item in range(len(lists) - num, len(lists)):
output_list.append(lists[item])

# Will add the values before


# n to the end of new list
for item in range(0, len(lists) - num):
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]

11. i) Describe in detail about lambda functions or anonymous function.

What are lambda functions in Python?


In Python, anonymous function is a function that is defined without a name.
While normal functions are defined using the def keyword, in Python anonymous functions are
defined using the lambda keyword.

Hence, anonymous functions are also called lambda functions.

How to use lambda Functions in Python?

A lambda function in python has the following syntax.

Syntax of Lambda Function in python

lambda arguments: expression

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.

Example of Lambda Function in python

Here is an example of lambda function that doubles the input value.

# Program to show the use of lambda functions


double = lambda x: x * 2
# Output: 10
print(double(5))

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)

# Printing average of the list


print("Average of the list =", round(average, 2))
Output:
Average of the list = 35.75

# Python program to get average of a list


# Using mean()

# 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)

# Printing average of the list


print("Average of the list =", round(average, 2))

32
Output:
Average of the list = 35.75

def cal_average(num):
sum_num = 0
for t in num:
sum_num = sum_num + t

avg = sum_num / len(num)


return avg

print("The average is", cal_average([18,25,3,41,5]))


OUTPUT
The average is 18.4

ii) Explain the various features of functions in


Python

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

def functionname( parameters ):


"function_docstring"
function_suite
return [expression]

33
13. i) Describe the syntax and rules involved in the return statement in Python.

Python return statement

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 add(a, b):

# returning sum of a and b


return a + b

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

ii) Write a program to demonstrate the flow of


control after the return statement in Python.

A function that returns a list of the numbers of the Fibonacci series:

>>>
>>> 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]

14. i) Explain the operator precedence of arithmetic operators in Python.


Precedence of Python Operators
The combination of values, variables, operators and function calls is termed as an expression. Python
interpreter can evaluate a valid expression.

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.

For example, multiplication has higher precedence than subtraction.

# Multiplication has higher precedence


# than subtraction
# Output: 2
10 - 4 * 2

# Parentheses () has higher precendence


# Output: 12
(10 - 4) * 2

The operator precedence in Python are listed in the following table.


It is in descending order, upper group has higher precedence than
the lower ones.

Operator precedence rule in Python

Operators Meaning

() Parentheses

** Exponent

35
+x, -x, ~x Unary plus, Unary minus, Bitwise NOT

Multiplication, Division, Floor division,


*, /, //, % Modulus

+, - Addition, Subtraction

<<, >> Bitwise shift operators

& Bitwise AND

^ Bitwise XOR

| Bitwise OR

==, !=, >, >=, <, <=, is,


is not, in, not in Comparisions, Identity, Membership operators

not Logical NOT

and Logical AND

or Logical OR

Operator precedence rule in Python

Associativity of Python Operators

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

Exponent operator ** has right-to-left associativity in Python.


# Right-left associativity of ** exponent operator
# Output: 512
print(2 ** 3 ** 2)
# Shows the right-left associativity
# of **
# Output: 64
print((2 ** 3) ** 2)

36
ii) Write a Python program to exchange the value of two variables

1. # Python program to swap two variables


2.
3. x=5
4. y = 10
5.
6. # To take inputs from the user
7. #x = input('Enter value of x: ')
8. #y = input('Enter value of y: ')
9.
10. # create a temporary variable and swap the values
11. temp = x
12. x=y
13. y = temp
14.
15. print('The value of x after swapping: {}'.format(x))
16. print('The value of y after swapping: {}'.format(y))

iii) Write a Python program using function to find the sum of first ‘n’ even numbers
and print the result.

sum of Even numbers in python

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

You might also like