Python Revision &functions

Download as pdf or txt
Download as pdf or txt
You are on page 1of 49

Unit-I Computational Thinking and Programming – 2

Revision of Python topics covered in class XI


PYTHON BASICS
Python is a simple, general purpose, high level, and object-oriented programming
language.Python is an interpreted scripting language also. Guido Van Rossum is the founder of
Python programming language.Guido was a fan of the popular BBC comedy show of that time,
"Monty Python's Flying Circus". So he decided to pick the name Python for his newly created
programming language.

Features of Python
• Python is a general purpose, dynamic, high-level, and interpreted programming language.
It supports Object Oriented programming approach to develop applications. It is simple
and easy to learn and provides lots of high-level data structures.
• Python is easy to learn yet powerful and versatile scripting language, which makes it
attractive for Application Development.
• Python's syntax and dynamic typing with its interpreted nature make it an ideal language
for scripting and rapid application development.
• Python supports multiple programming pattern, including object-oriented, imperative, and
functional or procedural programming styles.
• Python is not intended to work in a particular area, such as web programming. That is why
it is known as multipurpose programming language because it can be used with web,
enterprise, 3D CAD, etc.
• We don't need to use data types to declare variable because it is dynamically typed so we
can write a=10 to assign an integer value in an integer variable.
• Python makes the development and debugging fast because there is no compilation step
included in Python development, and edit-test-debug cycle is very fast.

Applications of Python Programming Language


• Data Science
• Date Mining
• Desktop Applications
• Console-based Applications
• Mobile Applications
• Software Development
• Artificial Intelligence
• Web Applications
• Enterprise Applications
• 3D CAD Applications
• Machine Learning

23
• Computer Vision or Image Processing Applications.
• Speech Recognitions

How To Use Python?


Python can be downloaded from www.python.org. (Standard Installation)
It is available in two versions-
• Python 2.x
• Python 3.x (It is in Syllabus)
Apart from above standard Python. We have various Python IDEs and Code Editors. Some of them
are as under:
(i) Anaconda Distribution: free and open-source distribution of the Python, having various inbuilt
libraries and tools like Jupyter Notebook, Spyder etc
(ii) PyCharm (iii) Canopy (iv) Thonny (v) Visual Studio Code (vi) Eclipse + PyDev
(vii) Sublime Text (viii) Atom (ix) GNU Emacs (x) Vim (xi) Spyder and many
more . .

Python Interpreter - Interactive And Script Mode:


We can work in Python in Two Ways:
(i) Interactive Mode: It works like a command interpreter as shell prompt works in DOS Prompt or
Linux. On each (>>>) symbol we can execute one by one command.
(ii) Script Mode: It used to execute the multiple instruction (complete program) at once.

Python Character Set:


Character Set is a group of letters or signs which are specific to a language. Character set includes
letter, sign, number and symbol.
• Letters: A-Z, a-z
• Digits: 0-9
• Special Symbols: _, +, -, *, /, (, #,@, {, } etc.
• White Spaces: blank space, tab, carriage return, newline, form feed etc.
• Other characters: Python can process all characters of ASCII and UNICODE.
Tokens
A token is the smallest individual unit in a python program. All statements and instructions in a
program are built with tokens.It is also known as Lexical Unit.
Types of token are
• Keywords
• Identifiers (Names)
• Literals
• Operators
• Punctuators

24
Keywords
Python keywords are unique words reserved with defined meanings and functions that we can only
apply for those functions.Python contains thirty-five keywords in the version, Python 3.9.
Identifiers
In programming languages, identifiers are names used to identify a variable, function, or other
entities in a program. The rules for naming an identifier in Python are as follows:
• The name should begin with an uppercase or lowercase alphabet or an underscore sign (_).
• This may be followed by any combination of characters a-z, A-Z, 0-9 or underscore (_).
Thus, an identifier cannot start with a digit.
• It can be of any length. (However, it is preferred to keep it short and meaningful).
• It should not be a keyword or reserved word.
• We cannot use special symbols like !, @, #, $, %, etc. in identifiers.
Legal Identifier Names Example:
Myvar my_var _my_var myVar myvar2
Illegal Identifier Names Example:-
2myvar my-var my var= 9salary

Literals or Values:
Literals are the fixed values or data items used in a source code. Python supports different types
of literals such as:
a. String literals - “Rishaan”
b. Numeric literals – 10, 13.5, 3+5i
c. Boolean literals – True or False
d. Special Literal None
e. Literal collections
Literal collections
Literals collections in python includes list, tuple, dictionary, and sets.
• List: It is a list of elements represented in square brackets with commas in between. These
variables can be of any data type and can be changed as well.
• Tuple: It is also a list of comma-separated elements or values in round brackets. The values
can be of any data type but can’t be changed.
• Dictionary: It is the unordered set of key-value pairs.
• Set: It is the unordered collection of elements in curly braces ‘{}’.

Operators
An operator is used to perform specific mathematical or logical operation on values. The values
that the operator works on are called operands.
• Arithmetic operators
• Assignment operators
• Comparison operators
• Logical operators

25
• Identity operators
• Membership operators
• Bitwise operators

Arithmetic operators: used with numeric values to perform common mathematical operations.
+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
% Modulus x%y
** Exponentiation x ** y
// Floor division x // y

Assignment operators: used to assign values to variables


= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3
&= x &= 3 x=x&3
|= x |= 3 x=x|3
^= x ^= 3 x=x^3
>>= x >>= 3 x = x >> 3
<<= x <<= 3 x = x << 3

Comparison Operators: Comparison operators are used to compare two values.


== Equal x == y
!= Not equal x != y
> Greater than x>y
< Less than x<y
>= Greater than or equal to x >= y
<= Less than or equal to x <= y

Logical Operators: Logical operators are used to combine conditional statements


and Returns True if both statements are true x < 5 and x < 10
or Returns True if one of the statements is true x < 5 or x < 4
not Reverse the result, returns False if the result is true not(x < 5 and x < 10)

Identity Operators: used to compare the objects, not if they are equal, but if they are actually the
26
same object, with the same memory location.
is Returns True if both variables are the same object x is y
is not Returns True if both variables are not the same object x is not y

Membership operators: used to test if a sequence is present in an object.


in Returns True if a sequence with the specified x in y
value is present in the object
not in Returns True if a sequence with the specified x not in y
value is not present in the object

Punctuators
Punctuators are symbols that are used in programming languages to organize sentence
structure, and indicate the rhythm and emphasis of expressions, statements, and program
structure. Common punctuators are: „ “ # $ @ []{}=:;(),

Python Variables
Variables are nothing but reserved memory locations to store values. This means that when
you create a variable you reserve some space in memory.
Based on the data type of a variable, the interpreter allocates memory and decides what can be
stored in the reserved memory. Therefore, by assigning different data types to variables, you
can store integers, decimals or characters in these variables.
• Variables are containers for storing data values.
• Unlike other programming languages, Python has no command for declaring a variable.
• A variable is created the moment you first assign a value to it.
Example:
x=5
y = "John"
print(x)
print(y)
• Variables do not need to be declared with any particular type and can even change type
after they have been set.
x = 4 # x is of type int
x = "Sally" # x is now of type str
print(x)
• String variables can be declared either by using single or double quotes:
x = "John"
# is the same as
x = 'John'
Output Variable:
The Python print statement is often used to output variables. To combine both text and a variable,
Python uses the, character:
x = "awesome"
27
print("Python is " , x)
Display Multiple variable:-
x = "awesome“
y=56
print(“Value of x and y is=" , x, y)

Assigning Values to Variables


Python variables do not need explicit declaration to reserve memory space. The declaration
happens automatically when you assign a value to a variable. The equal sign (=) is used to assign
values to variables. Also Python allows you to assign a single value to several variables
simultaneously.
The operand to the left of the = operator is the name of the variable and the operand to the right of the
= operator is the value stored in the variable
counter = 100 # An integer assignment
miles = 1000.0 # A floating point
name = "John" # A string

print (counter)
print (miles)
print (name)
a=b=c=1
a,b,c = 1,2,"john"

Data Types
The data stored in memory can be of many types, i.e., Every value belongs to a specific data type
in Python. Data type identifies the type of data which a variable can hold and the operations that
can be performed on those data.Python has various standard data types that are used to define the
operations possible on them and the storage method for each of them.

The different standard data types −


• Numbers

28
• String
• List
• Tuple
• Dictionary
• Boolean
• Set
Numbers
Number data types store numeric values. Number objects are created when you assign a value to
them. For example −
var1 = 1
var2 = 10

Python supports four different numerical types


• int (signed integers)
• long (long integers, they can also be represented in octal and hexadecimal)
• float (floating point real values)
• complex (complex numbers)
int long float complex
10 51924361L 0.0 3.14j
100 -0x19323L 15.20 45.j
-786 0122L -21.9 9.322e -36j
080 0xDEFABCECBDAE 32.3+e18 .876j
-0490 535633629843L -90. -.6545+0J
-0x260 -052318172735L -32.54e100 3e+26J
0x69 -4721885298529L 70.2-E12 4.53e-7j

You can also delete the reference to a number object by using the del statement. The syntax of
the del statement is −

del var1[,var2[,var3[....,varN]]]]
e.g. del var
del var_a, var_b

Strings
Strings in Python are identified as a contiguous set of characters represented in the quotation
marks. Python allows for either pairs of single or double quotes. Subsets of strings can be taken
using the slice operator ([ ] and [:] ).
str = 'Hello World!'

print str # Prints complete string Hello World!


print str[0] # Prints first character of the string H

29
print str[2:5] # Prints characters starting from 3rd to 5th llo
print str[2:] # Prints string starting from 3rd character llo World!
print str * 2 # Prints string two times Hello World!Hello World!
print str + "TEST" # Prints concatenated string Hello World!TEST

Lists
Lists are the most versatile of Python's compound data types. A list contains items separated by
commas and enclosed within square brackets ([]).
The values stored in a list can be accessed using the slice operator ([ ] and [:]) with indexes starting at
0 in the beginning of the list and working their way to end -1. The plus (+) sign is the list
concatenation operator, and the asterisk (*) is the repetition operator.
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tinylist = [123, 'john']
print list # Prints complete list ['abcd', 786, 2.23, 'john', 70.2]
print list[0] # Prints first element of the list- abcd
print list[1:3] # Prints elements starting from 2nd till 3rd - [786, 2.23]
print list[2:] # Prints elements starting from 3rd element -[2.23, 'john', 70.2]
print tinylist * 2 # Prints list two times-[123, 'john', 123, 'john']
print list + tinylist # Prints concatenated lists-['abcd', 786, 2.23, 'john', 70.2, 123, 'john']

Tuples
A tuple is another sequence data type that is similar to the list. A tuple consists of a number of
values separated by commas. Lists are enclosed in brackets ( [ ] ) and their elements and size can
be changed, while tuples are enclosed in parentheses ( ( ) ) and cannot be updated.
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
tinytuple = (123, 'john')

print tuple # Prints the complete tuple--('abcd', 786, 2.23, 'john', 70.2)
print tuple[0] # Prints first element of the tuple-- abcd
print tuple[1:3] # Prints elements of the tuple starting from 2nd till 3rd--(786, 2.23)
print tuple[2:] # Prints elements of the tuple starting from 3rd element--(2.23, 'john', 70.2)
print tinytuple * 2 # Prints the contents of the tuple twice--(123, 'john', 123, 'john')
print tuple + tinytuple # Prints concatenated tuples-- ('abcd', 786, 2.23, 'john', 70.2, 123, 'john')

Dictionary
Python's dictionaries are kind of hash table type. They consist of key-value pairs. A dictionary key
can be almost any Python type, but are usually numbers or strings. Values, on the other hand, can
be any arbitrary Python object.
Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed using square
braces ([]). For example −

dict = {}
30
dict['one'] = "This is one"
dict[2] = "This is two"
tinydict = {'name': 'john','code':6734, 'dept': 'sales'}
print dict['one'] # Prints value for 'one' key This is one
print dict[2] # Prints value for 2 key This is two
print tinydict # Prints complete dictionary {'dept': 'sales', 'code': 6734, 'name': 'john'}
print tinydict.keys() # Prints all the keys ['dept', 'code', 'name']
print tinydict.values() # Prints all the values ['sales', 6734, 'john']

Boolean
Boolean represent one of two values: True or False. When you compare two values, the expression
is evaluated and Python returns the Boolean answer.Also, almost any value is evaluated to True if
it has some sort of content.
print(10 > 9) True bool(None) False
print(10 == 9) False bool(0) False
print(10 < 9) False bool("") False
bool("abc") True bool(()) False
bool(123) True bool([]) False
bool(["apple", "cherry"]) True bool({}) False
bool(False) False

Mutable and Immutable Objects in Python


Everything in Python is an object. So, every variable holds an object instance. All objects in Python
can be either mutable or immutable. When an object is initiated, it is assigned a unique object id.
Its type is defined at runtime and once set can never change, however its state can be changed if it
is mutable. Generally, a mutable object can be changed after it is created, and an immutable object
can’t.

Mutable objects
Mutability means the ability to modify or edit a value. Mutable objects in Python enable the
programmers to have objects that can change their values. They generally are utilized to store
a collection of data. It can be regarded as something that has mutated, and the internal state applicable
within an object has changed.

31
In mutable data types, we can modify the already existing values of the data types (such as lists,
dictionaries, etc.). Or, we may add new values or remove the existing values from our data types.
Basically, we may perform any operation with our data without having to create a new copy of our
data type. Hence, the value assigned to any variable can be changed.
e.g. color = ["red", "blue", "green"]
print(color) Output:
color[0] = "pink" ['red', 'blue', 'green']
color[-1] = "orange" ['pink', 'blue', 'orange']
print(color)

Immutable Objects
Immutable objects in Python are objects wherein the instances do not change over the period.
Immutable instances of a specific type, once created, do not change, and this can be verified using
the id method of Python
e.g. message = "Welcome to GeeksforGeeks"
message[0] = 'p'
print(message)
Output
Traceback (most recent call last):
File "/home/ff856d3c5411909530c4d328eeca165b.py", line 3, in
message[0] = 'p'
TypeError: 'str' object does not support item assignment

❖ Exception: However, there is an exception in immutability as well.Tuple in python is


immutable. But the tuple consists of a sequence of names with unchangeable bindings to
objects.

32
Consider a tuple
tup = ([3, 4, 5], 'myname')
The tuple consists of a string and a list. Strings are immutable so we can’t change its value. But the
contents of the list can change. The tuple itself isn’t mutable but contain items that are mutable.

Expression in python:
A combination of constants, operands and operators is called an expression. The expression in
Python produces some value or result after being interpreted by the Python interpreter. The
expression in Python can be considered as a logical line of code that is evaluated to obtain some
result. If there are various operators in an expression then the operators are resolved based on their
precedence.
E.g. Expression 6-3*2+7-1 evaluated as 6

Types of Expression in Python


Constant Expressions x = 10 + 15
Arithmetic Expressions y=x**3+x-2+5/2
Integral Expressions x=10 y=5.00 result = x + int(y)
Floating Expressions result = float(x) + y
Relational Expressions 10+15>20
Logical Expressions r=x and y
Combinational Expressions result = x + (y << 1)

Type Casting in Python


Type Casting is the method to convert the variable data type into a certain data type in order to the
operation required to be performed by users.
There can be two types of Type Casting in Python –
• Implicit Type Casting
• Explicit Type Casting

Implicit Type Conversion


In this, methods, Python converts data type into another data type automatically, where users don’t
have to involve.

33
# Python automatically converts
# a to int
a=7
print(type(a))
# Python automatically converts
# b to float
b = 3.0
print(type(b))
# Python automatically converts
# c to float as it is a float addition
c=a+b
print(c)
print(type(c))
# Python automatically converts
# d to float as it is a float multiplication
d=a*b
print(d)
print(type(d))

Explicit Type Casting


In this method, Python need user involvement to convert the variable data type into certain data type
in order to the operation required.Mainly in type casting can be done with these data type function:

int() : int() function take float or string as an argument and return int type object.
float() : float() function take int or string as an argument and return float type object.
str() : str() function take float or int as an argument and return string type object.

E,g, # int variable


a=5
# typecast to float
n = float(a)
print(n)
print(type(n))

Precedence and Associativity of Operators


Operator Precedence: This is used in an expression with more than one operator with different
precedence to determine which operation to perform first.

34
Operator Associativity: If an expression contains two or more operators with the same precedence then
Operator Associativity is used to determine. It can either be Left to Right or from Right to Left.

Comments in python:
Comments are non-executable statements of python. It increases the readability and understandability
of code.
Types of comment:
i. Single line comment (#) – comments only single line.
e.g. a=7 # 7 is assigned to variable ‘a’
print(a) # displaying the value stored in ‘a’

ii. Multi-line comment (‘‘‘………..’’’) – Comments multiple line.


e.g. ‘‘‘Program -1
A program in python to store a value invariable ‘a’ and display the value stored in it.’’’
a=7
print(a)

Python Input and Output


Python executes code top to bottom, when written in the correct syntax.Once the interpreter is running
you can start typing in commands to get the result.

Input using the input( ) function


input (): This function first takes the input from the user and converts it into a string. The type of the
returned object always will be <type ‘str’>. It does not evaluate the expression it just returns the
complete statement as String. Python provides a built-in function called input which takes the input
from the user. When the input function is called it stops the program and waits for the user’s input.
When the user presses enter, the program resumes and returns what the user typed.
name = input('What is your name?\n')
What is your name?
Ram

Taking multiple inputs from user

35
Using split() method
Using List comprehension
split() method :
This function helps in getting multiple inputs from users. It breaks the given input by the specified
separator. If a separator is not provided then any white space is a separator. Generally, users use a
split() method to split a Python string but one can use it in taking multiple inputs.
input().split(separator, maxsplit)
List comprehension is an elegant way to define and create list in Python. We can create lists just like
mathematical statements in one line only. It is also used in getting multiple inputs from a user.
x, y, z = [int(x) for x in input("Enter three values: ").split()]

Output using print() function


print() : function prints the message on the screen or any other standard output device.

print(value(s), sep= ' ', end = '\n', file=file, flush=flush)

value(s) : Any value, and as many as you like. Will be converted to string before printed
sep=’separator’ : (Optional) Specify how to separate the objects, if there is more than
one.Default :’ ‘
end=’end’: (Optional) Specify what to print at the end.Default : ‘\n’
file : (Optional) An object with a write method. Default :sys.stdout
flush : (Optional) A Boolean, specifying if the output is flushed (True) or buffered (False).
Default: False

Debugging:-
Debugging is a process of locating and removing errors from program.
Errors in a program
An error or exception refers to an interruption in the execution of code due to which we cannot attain
the expected outcome to the end-users. These errors are classified on the basis of the event when the
program generate the error. The two types of errors are Compile Time Errors and Runtime Errors
and Logical errors

Compile Time Errors


These errors occur when we violate the rules present in a syntax. The compile-time error indicates
something that we need to fix before compiling the code. A compiler can easily detect these errors.
Eg Syntax error and Semantic Error.
Logic errors
These errors are not always easy to recognize immediately. This is due to the fact that such errors,
unlike that of syntax errors, are valid when considered in the language, but do not produce the
intended behavior. These can occur in both interpreted and compiled languages. It may occur due to
the logic of the program.
36
Runtime Errors
These errors occur during the run-time program execution after a successful compilation. Division
error is one of the most common errors (runtime). It occurs due to the division by zero. It is very
difficult for a compiler to find out a runtime error because it cannot point out the exact line at which
this particular error occurs.
---------------------------------------------------------------------------------------------------------------------
Control flow statements
The control flow of a Python program is regulated by conditional statements, loops, and function
calls. In order to control the flow of execution of a program there are three categories of statements
in python. They are:
1. Selection statements
2. Iteration statements
3. Jump statements / Transfer statements

Selection Statements
Decision making is valuable when something we want to do depends on some user input or some
other value that is not known when we write our program. This is quite often the case and Python,
along with all interesting programming languages, has the ability to compare values and then take
one action or another depending on that outcome.
Python have following types of selection statements
1. if statement
2. if else statement
3. Ladder if else statement (if-elif-else)
4. Nested if statement

if statements
This construct of python program consist of one if condition with one block of statements. When
condition becomes true then executes the block.

Syntax:
37
if ( condition):
Statement(s)
Example:
age=int(input(“Enter Age: “))
if ( age>=18):
print(“You are eligible for vote”)
if(age<0):
print(“You entered Negative Number”)

if - else statements
This construct of python program consist of one if condition with two blocks. When condition
becomes true then executes the block given below
Syntax:
if ( condition):
Statement(s)
else:
Statement(s)
Example
x = int(input("Please enter an integer: "))
y = int(input("Please enter another integer: "))
i f x > y:
print(x,"is greater than",y)
else:
print(y,"is greater than or equal to",x)

Ladder if else statements (if-elif-else)


The Python compound statement if, which uses if, elif, and else clauses, lets you conditionally
execute blocks of statements. Here’s the syntax for the if statement:
if expression:
statement(s)
elif expression:
statement(s)
elif expression:
statement(s)
...
else:
statement(s)
Example

i = 20
if (i == 10):

38
print("i is 10")
elif (i == 15):
print("i is 15")
elif (i == 20):
print("i is 20")
else:
print("i is not present")

Nested-if
Nested if statements mean an if statement inside another if statement.
if (condition1):
# Executes when condition1 is true
if (condition2):
# Executes when condition2 is true
# if Block is end here
# if Block is end here

Example

num=int(input(“Enter Number: “))


if ( num<=0):
if ( num<0):
print(“You entered Negative number”)
else:
print(“You entered Zero ”)
else:
print(“You entered Positive number”)

Python Iteration Statements

The iteration (Looping) constructs mean to execute the block of statements again and again
depending upon the result of condition. This repetition of statements continues till condition meets
True result. As soon as condition meets false result, the iteration stops.
Python supports following types of iteration statements
1. while
2. for
Four Essential parts of Looping:
i. Initialization of control variable
ii. Condition testing with control variable
iii. Body of loop Construct
iv. Increment / decrement in control variable

39
for loop
For loops are useful when you need to do something for every element of a sequence
<statements before for loop>
for <variable> in <sequence>:
<body of for loop>
<statements after for loop>
Example
s = input("Please type some characters and press enter:")
for c in s:
print(c)
print("Done")

while Loop
Python's while statement is its most general iteration construct. In simple terms, it repeatedly
executes a block of indented statements, as long as a test at the top keeps evaluating to a true value.
When the test becomes false, control continues after all the statements in the while, and the body
never runs if the test is false to begin with.
while <test>: # loop test
<statements1> # loop body
else: # optional else
<statements2> # run if didn't exit loop with b
Example
count = 0
while (count < 9):
print ('The count is:', count )
count = count + 1
print ("Good bye!" )

Python supports to have an else statement associated with a loop statement. If the else statement is
used with a for loop, the else statement is executed when the loop has exhausted iterating the list. If
the else statement is used with a while loop, the else statement is executed when the condition
becomes false
Example:
count = 0
while count < 5:
print (count, " is less than 5" )
count = count + 1
else:
print( count, " is not less than 5”)

Single Statement Suites: If there is only one executable statement in while loop, then we can use this

40
format.
Example:
flag = 1
while (flag): print ('Given flag is really true!' )
print( "Good bye!" )

Jump Statements
Now that we‘ve seen a few Python loops in action, it‘s time to take a look at two simple statements that
have a purpose only when nested inside loops—the break and continue statements.

In Python:
pass
Does nothing at all: it‘s an empty statement placeholder
break
Jumps out of the closest enclosing loop (past the entire loop statement)
continue
Jumps to the top of the closest enclosing loop (to the loop‘s header line)

---------------------------------------------------------------------------------------------------------------------

Python range( ) Function


The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1
(by default), and ends at a specified number.
Syntax:
range( start value, stop value, step value )
Where all 3 parameters are of integer type
● Start value is Lower Limit
● Stop value is Upper Limit
● Step value is Increment / Decrement
Note: The Lower Limit is included but Upper Limit is not included in result.

Example
range(5) => sequence of 0,1,2,3,4
range(2,5) => sequence of 2,3,4
range(1,10,2) => sequence of 1,3,5,7,9
range(5,0,-1) => sequence of 5,4,3,2,1
range(0,-5) => sequence of [ ] blank list
(default Step is +1)
range(0,-5,-1) => sequence of 0, -1, -2, -3, -4
range(-5,0,1) => sequence of -5, -4, -3, -2, -1
41
range(-5,1,1) => sequence of -5, -4, -3, -2, -1, 0

42
WORK SHEET

LEVEL-1

Questions
Q.No Marks

Which of the following is not a Tuple in Python ? (1)


(a) (1,2,3) (b) (‘one’,two’,’three’) (c) (10,) (d) (‘one’)
1
Ans: (‘one’)

What will be output of the following code snippet: (1)


A=[1.2.3.4,5]
2
print(a[3:0:-1])
Ans : [4,3,2]
Write the output of the code given below: (2)
my_dict = {"name": "Kuhan",'Door No.': 100}
my_dict["Door No."] = 128
3
my_dict['address'] = "Karnataka"
print(my_dict.items())
Ans: dict_items([('name', 'Kuhan'), ('Door No.', 128), ('address', 'Karnataka')])
Find and write the output of the following python code:
Msg="CompuTer"
Msg1=''
for i in range(0, len(Msg)):
if Msg[i].isupper():
Msg1=Msg1+Msg[i].lower()
4 (4)
elif i%2==0:
Msg1=Msg1+'*'
else:
Msg1=Msg1+Msg[i].upper()
print(Msg1)
Ans: cO*P*t*R

43
LEVEL-2

1 D={“AMIT”:90,”RESHMA”:96,”SUMAN”:92} (1)
Print(“SUMAN” in D, 90 in D, sep=”#”)
(a) True#False (b) True#True (c) False#True (d) False#False
Ans : (a) True#False
2 Find and write the output of the following python code: (1)
x = "Welcome"
i = "e"
while i in x:
print(i, end = "$")
Ans :e$e$e$e$e$......
3. What is the output of the following Python statement : print(5+3**2/2) (1)
Ans : 9.5
4. The return type of the input() function is Ans:String (1)

5. Consider the given expression : (1)


not True and True or False
Ans : False
6. Given is a Python string declaration: (2)
myexam="@@CBSE Examination 2022@@"
Write the output of: print(myexam[::-3])
Ans: @2 ina B@
7. What will be the output if entered number n is 1 and n is 4 : (3)
i=2
n=int(input("enter the value of n"))
while i<n:
if n % i==0:
break
print(i)
i=i+1

44
else:
print("done")
Ans : n=1 ------ done
n=4 ------- no output
8. What is the output of the following code snippet?
def ChangeVal(M,N):
for i in range(N):
if M[i]%5 == 0:
M[i]//=5
if M[i]%3 == 0:
M[i]//=3
L = [25,8,75,12] (4)
ChangeVal(L,4)
for i in L:
print(i,end="#")

Ans : 5#8#5#4#

LEVEL-3

1 State True or False:


The # symbol used for inserting comments in python is a token (1)
Ans : True
2 Which of the following invalid identifier in Python?
(a) name (b) section (c) true (d) break (1)
Ans: (d) break
3 Evaluate the following expressions :
(2)

a) 8 // 4 + 18 * 6 / 3– 3
45
b) 35/5 or 5.0 + 30/10
Ans: a) 35.0
b)7.0
4 Concatenation operator in list is :
(a) * (b) , (c) + (d) = (1)
Ans : +
Find error in the following code(if any) and correct code by rewriting code and underline
the correction;‐
5
x= int(input(“Enter value of x:”) )
for I in range [0,10]:
(2)
if x=y:
print( x + y)
else:
print( x‐y)

WORKING WITH FUNCTIONS


Function Definition:
A function is a programming block of codes which is used to perform a single, related,
specific task. It only works when it is called. We can pass data, known as parameters, into a function.
A function can return data as a result.
Python treats functions like a first-class member. It implies that in Python, functions and other
objects are of same significance.Functions can be assigned to variables, stored in collections, or
passed as arguments. This brings additional flexibility to the language.

Advantages of Functions
• Reducing duplication of code
• Decomposing complex problems into simpler pieces
• Improving clarity of the code
• Reuse of code
• Information hiding

Python function types


There are three categories of functions:
• Built-in functions

46
• Function defined in modules
• User defined functions.
Built-in functions
The functions whose functionality is predefined in Python are referred to as built-in functions.
The python interpreter has several such functions that are always available for use.
E.g. len(), type(), int(), input()
Function defined in modules
These functions are pre-defined in particular modules and can only be used after the specific
module is imported.
E.g. All mathematical functions are defined in the module math.
User-defined functions
Python User Defined Functions allow users to write unique logic that the user defines. It is
the most important feature in Python that consists of custom-defined logics with a set of rules and
regulations that can be passed over the data frame and used for specific purposes.

Structure of functions in Python

Internally Python names the segment with top-level statements (no indentation) as
_main_ Python begins execution of a program from top-level statements.
Defining a Function
A function in Python is defined as given below:
def< function name >(parameters):
[“ ” ”<function’s docstring>” “ “]
<statements>
[<statements>]
……………………..

47
• Keyword def that marks the start of the function header.
• A function name to uniquely identify the function. Function naming follows the same rules
of writing identifiers in Python.
• Parameters (arguments) through which we pass values to a function. They are optional.
• A colon (:) to mark the end of the function header.
• Optional documentation string (docstring) to describe what the function does.
• One or more valid python statements that make up the function body. Statements must have
the same indentation level (usually 4 spaces).
• An optional return statement to return a value from the function.

Function header:
The Header of a function specifies the name of the function and the name of each
of its parameters. It begins with the keyword def.
Parameters:
Variables that are listed within the parenthesis of a function header.
Function Body:
The block of statements to be carried out, ie the action performed by the function.
Indentation:
The blank space needed for the python statements. (four spaces convention)

Flow of execution in a function call


The flow refers to the order in which statements are executed during a program run. The
function body is a block of statements and python executes every block in an execution frame.
An execution frame contains:
• Some internal information (used for debugging)
• Name of the function
• Values passed to the function
• Variables created within the function
48
• Information about the next instruction to be executed

Whenever a function call statement is encountered, an execution frame for the function is created
and the control is transferred to it. The statements are then executed and if there is return
statement in the program, it will be executed and returns to the function call statement block.

def message():
print('Hello I am learning how to create function in python.')

def sum(a,b):
c=a+b
print('Sum of %d and %d is %d' %(a,b,c))

# main program
# calling the function message()
message()
# calling the function sum()
sum(10,20)
In the above program, two functions message() and sum() is declared. The message() function
does not accept any argument but displays a text on the screen whenever we call it. On the other
hand, the sum() function accept two arguments and display their sum on the screen. when the main
program calls the function message(), the program flow goes to the body of the function message()
and execute its codes. After that, it returns to the main program and then calls the second function
sum() by sending it two arguments (10,20), the program flow goes to the body of the function sum(),
and execute its code and again returns to the main program. At last, the main programs end.
The function calling another function is called the caller and the functions being called
is the called function or callee.

Parameters and Arguments


The parameters are the variables that we can define in the function declaration. In fact, we
utilized these variables within the function. Also, the programming language in the function
description determines the data type specification. These variables facilitate the function’s entire
execution. In addition, they are known as local variables because they are only available within the
function.
The arguments are the variables given to the function for execution. Besides, the local
variables of the function take the values of the arguments and therefore can process these parameters
for the final output.

49
Passing parameters:-
Python support three types of formal arguments/parameters:
1. Positional argument (required arguments):-
When the functions call statement must match the number and order of arguments as define
in the functions definition this is called the positional arguments.
Example:-
def check(a,b,c):
:
Then possible functions call for this can be:-
check(x,y,z)#3values(allvariables)passed
check(2,x,y)#3values(literal+variables)passed
check ( 2 , 3 , 4 ) # 3 values ( all literal ) passed.
Thus through such function calls-
• The argument must be provided for all parameters (required)
• The values of argument are matched with parameters, position(order)wise(positional)

2. Default arguments:-
A parameter having defined value in the function header is known as a default parameter.
Example:-
def interest(principal,time,rate=10):
si=interest(5400,2) #third argument missing
So the parameter principal get value 5400,time get 2 and since the third argument rate is missing, so
default value 0.10 is used for rate.
• Default argument are useful in situations where some parameters always have same
value.
Some advantages of the default parameters are listed below:-

50
• They can be used to add new parameters to the existing functions.
• They can be used to combine similar function in to one.

3. Keyword(or named)arguments:-
Keyword arguments are the named arguments with assigned values being passed in the function
call statement.
Example:-
def interest(prin,time,rate):
return prin * time * rate
print (interest ( prin = 2000 , time = 2 , rate 0.10 ))
print (interest ( time = 4 , prin = 2600 , rate = 0.09 ))
print(interest(time=2,rate=0.12,prin=2000))
All the above functions call are valid now, even if the order of arguments does not match.
4. Using multiple argument type together:-
Python allows you to combine multiple argument types in a function call.
Rules for combining all three types of arguments:-
• And argument list must first contain positional(required) arguments followed by any
keyword argument.
• Keyword arguments should be taken from the required arguments preferably.
• You cannot specify a value for an argument more than once.
Example:-
def interest(prin,cc,time=2,rate=0.09):
return prin * time * rate
Types of user defined function
1. No Argument No return
2. With Argument No return
3. No Argument with return
4. With Argument with return

1. No Argument No return
def Add():
a= int (input(“Enter First Number”))
b= int (input(“Enter Second Number”))
c=a+b
print (“The Sum of inputted Numbers is:”, c)
Add()
print(“ Executed”)

2. With Argument No return


def Add(a,b):
c=a+b
51
print(“The Sum of inputted Numbers is:”, c)
num1=int (input(“Enter First Number”))
num2= int (input(“Enter Second Number”))
add(num1,num2)

Remember: The variable in main program are differ from the variable in function definition i.e. a
and b should be x and y. In this scenario the variable passed (num1,num2)will be called argument,
and when it replace with the variable defined in the function will be called as parameter.
3. No Argument with return
def Add():
a=int (input(“Enter First Number”))
b= int (input(“Enter Second Number”))
c=a+b
return c
x= add()
print (“The Sum of inputted Numbers is:”, x)

Note: { As return does not show the result we have to store the returned value on another
variable x}
4. With Argument with return
def Add (a,b):
c=a+b
return c
a=int (input(“Enter First Number”))
b= int (input(“Enter Second Number”))
x= add(a,b)
print (“The Sum of inputted Numbers is:”, x)

Calling function and Called function:


• Function which is called by another Function is called Called Function. The called
function contains the definition of the function and formal parameters are associated
with them.
• The Function which calls another Function is called Calling Function and actual
Paramaters are associated with them.
• In python, a function must be defined before the function call otherwise
python interpreter gives an error.

Difference between Arguments and parameters


These two terms are very interchangeable, so it is not so important to know the difference.
The terms they refer to are almost identical. However, in order to sound more professional, correct
terminology is important.
Function Parameters: Variables that are in brackets when defining the function. When a method is
called, the arguments are the data passed to the method’s parameters.
52
Function arguments : Arguments are used to pass information from the rest of the program to the
function. This information return a result. There is no limit to the number of arguments that can be
written. Depending on the type of function you’re performing, there might even be no argument.
Use commas to separate the arguments in a function. Take into account the number of
arguments you put in a function call. The number of arguments must be exactly the same as the
number of parameters.

In the example below, the variable name is the input parameter, where as the value, “Arnav”, passed
in the function call is the argument.

def welcome(name):
print("Hello! " + name + " Good Morning!!")
welcome("Arnav")
Output:
Hello! Arnav Good Morning!!

Returning a Function
If you wish to return some values from the function to the rest of the program, you can use
the return statement. As the name suggests, it returns a value without printing it. Executing this
statement will cause the Python function to end immediately and store the value being returned into
a variable.
Scope of variables
Scope means in which part(s) of the program, a particular piece of code or data is accessible
or known.
In python there are broadly 2 kinds of Scopes:
• Global Scope
• Local Scope
Global Scope:
• A name declared in top level segment(_main_) of a program is said to have global scope
and can be used in entire program.
• Variable defined outside of the all functions are global variables.
Local Scope :
• A name declared in a function body is said to have local scope i.e. it can be used only
within this function and the other block inside the function.
• The formal parameters are also having local scope.

When dealing with Python functions, you should also consider the scope of the variables. The
code in a function is in its own little world, separate from the rest of the program. Any variable
declared in the function is ignored by the rest of the function. This means that two variables with the
same name can exist, one inside the function and the other outside the function. However, this is not
a good practice. All variable names must be unique regardless of their scope.

53
Local variable: A variable that is defined within a function and can only be used within that
particular function. With respect to the local variable, the area in a function is called “local area”.
Global variable: A variable that is defined in the main part of the programming and, unlike local
variables, can be accessed via local and global areas.
Example:

Lifetime of Variables:
Lifetime is the time for which a variable lives in memory. For global variables the lifetime is
entire program run i.e. as long as program is executing. For local variable, lifetime is their function’s
run i.e. as long as function is executing.

Name Resolution(Scope Resolution)


For every name used within program, python follows name resolution rules known as
LEGB rule.
• Local Environment : first check whether name is in local environment, if yes Python uses
its value otherwise moves to (ii)

• Enclosing Environment:if not in local,Python checks whether name is in Enclosing


Environment, if yes Python uses its value otherwise moves to (iii)

• Global Environment:if not in above scope Python checks it in Global environment, if


yes Python uses it otherwise moves to (iv)

• Built-In Environment:if not in above scope, Python checks it in built-in environment, if


yes, Python uses its value otherwise Python would report the error: name <variable>
notdefined.

WORKSHEET
LEVEL I
I. Questions (1 mark)
54
1. Which of the following is the use of function in python?
a) Functions are reusable pieces of programs
b) Functions don’t provide better modularity for your application
c) you can’t also create your own functions
d) All of the mentioned
2. What is the output of the below program?
def printMax(a, b):
if a > b:
print(a, ‘is maximum’)
elif a == b:
print(a, ‘is equal to’, b)
else:
print(b, ‘is maximum’)
printMax(3, 4)
a) 3 b) 4 c) 4 is maximum d) None of the mentioned
3. What is the output of the below program?
x = 50
def func():
global x
print('x is', x)
x=2
print('Changed global x to', x)
func()
print('Value of x is', x)
a) x is 50
Changed global x to 2
Value of x is 50
b) x is 50
Changed global x to 2
Value of x is 2
c) x is 50
Changed global x to 50
Value of x is 50
d) None of the mentioned

4. What is the output of the below program?

def C2F(c):
return c * 9/5 + 32
print (C2F(100))
print (C2F(0))
a) 212.0
32.0
55
b) 314.0
24.0
c) 567.0
98.0
d) None of the mentioned

5. The default value for a parameter is defined in function ………..


6. Python names the top level segment as…………..
7. Variable declared inside functions may have global scope (True/False)
8. Which arguments given below is skipped from function call?
a)Positional b)Default c)Keyword d)named
9. What is the order of resolving scope in Python?
a)BGEL b)LEGB c)GEBL d)LBEG
10.Complete the function body.
def f(num):
…………..
print (f(8))
a)return 0 b)print(num) c)print(“num”) d)return num
11. The function pow(x,y,z) is evaluated as:
a) (x**y)**z b) (x**y) / z c) (x**y) % z d) (x**y)*z
12. The function seed is a function which is present in the ……………..module
13. What are the outcomes of the functions shown below?
sum(2,4,6)
sum([1,2,3])
14. What is the output of the functions shown below?
min(max(False,-3,-4), 2,7)
a) 2 b) False c) -3 d)0
15. What is the output of the programgiven below?
a = 100
def func (a) :
a = 20
func (a)
print (' a is now ', a)
A. a is now 50
B. a is now 100
C. a is now 2
D. error

16. What will be the output of the following python code:


val = 100
def display(N):
global val
val = 50
if N%14==0:
56
val = val + N
else:
val = val - N
print(val, end="@")
display(40)
print(val)
A. 100@10
B. 50@5
C. 5@50
D. 100@10@
17. What will be the output of the following python code:
def A_func (x=10, y=20):
x =x+1
y=y-2
return (x+y)
print(A_func(5),A_func())
A. 24,29
B. 15,20
C. 20,30
D. 25,30
18. Consider the following code and choose correct answer
def nameage(name=”kishan”, age=20):
return age,name
t=nameage(20,”kishan”)
print(t[1])
A. kishan
B. 20
C. (kishan, 20)
D. (20,kishan)

II. Questions (2 marks)


1. Write the output of the pseudocode
def absolute_value(num):
if num>= 0:
return num
else:
return -num
print(absolute_value(2))

print(absolute_value(-4))
III. Questions (3 marks)
1. Differentiate ceil() and floor() function?
IV.Questions (5 marks)

57
1. What are the arguments supported by python? Explain each of them with a suitable example.
2. What is the difference between the formal parameters and actual parameters? What are their
alternative names? Also, give a suitable Python code to illustrate both.

ANSWERS
I Answer the following 1 mark
1 A
2 C
3 B
4 A
5 Header
6 _main_
7 False
8 B
9 B
10 B
11 C
12 Random
13 The first function will result in an error because the function sum() is used to
find the sum of iterablenumbers. Hence the outcomes will be Error and
6respectively.
14 The function max() is being used to find themaximum value from among -3,
-4 and false. Since falseamounts to the value zero, hence we are left with
min(0, 2, 7)Hence the output is 0 (false)
15 B
16 A
17 A
18 B
II Answer the following 2 marks
1 2

58
4

III Answer the following 3 marks

1 Floor Function Ceil Function


floor function returns the integer ceil function returns the integer
value just lesser than the given value just greater than the given
rational value. rational value
represented as floor(x). represented as ceil(x)
The floor of negative fractional The ceil of negative fractional
numbers is represented using the numbers are represented using ceil
floor function function.
It returns the value which is just It returns the value which is just
less than or equal to the given greater than or equal to the given
value. value.
Eg. the floor of 78.38 is 78 and the Eg. ceil of 78.38 is 79 and ceil of -
floor of -39.78 is -40. 39.78 is -39.

IV Answer the following 5 marks


1 Python supports four argument types:
Positional Arguments: Arguments passed to a function in correct positional
order, no. of arguments must match with no. of parameters required.
Default Arguments: Assign a default value to a certain parameter, it is used
when the user knows the value of the parameter, default values are specified
in the function header. It is optional in the function call statement. If not
provided in the function call statement then the default value is considered.
Default arguments must be provided from right to left.
Key Word Arguments: Keyword arguments are the named arguments with
assigned values being passed in the function call statement, the user can
combine any type of argument.
Variable Length Arguments: It allows the user to pass as many arguments
as required in the program. Variable-length arguments are defined with the *
symbol.

59
2 Actual Parameter is a parameter, which is used in function call statement to
send the value from calling function to the called function. It is also known
as Argument.

Formal Parameter is a parameter, which is used in function header of the


called function to receive the value from actual parameter. It is also known
as Parameter. For example,

def addEm(x, y, z):


print(x + y + z)
addEm (6, 16, 26)

In the above code, actual parameters are 6, 16 and 26; and formal parameters
are x, y and z.

LEVEL II
IV. Questions (1 mark)
1. Name the Python Library modules which need to be imported to invoke the following
functions :
load ()
pow ()
2. What is the output of the below program ?
x = 50
def func(x):
#print(‘x is’, x)
x=2
#print(‘Changed local x to’, x)
func(x)
print(‘x is now’, x)
a) x is now 50
b) x is now 2
c) x is now 100
d) None of the mentioned

3. What is the output of the below program?


def func(a, b=5, c=10):
print('a is', a, 'and b is', b, 'and c is', c)
func(3, 7)
func(25, c = 24)
func(c = 50, a = 100)
60
a)
a is 7 and b is 3 and c is 10
a is 25 and b is 5 and c is 24
a is 5 and b is 100 and c is 50
b)
a is 3 and b is 7 and c is 10
a is 5 and b is 25 and c is 24
a is 50 and b is 100 and c is 5
c)
a is 3 and b is 7 and c is 10
a is 25 and b is 5 and c is 24
a is 100 and b is 5 and c is 50
d) None of the mentioned
4. What is the output of below program?
def maximum(x, y):
if x > y:
return x
elif x == y:
return 'The numbers are equal'
else:
return y
print(maximum(2, 3))
a) 2
b) 3
c) The numbers are equal
d) None of the mentioned

5. A function is executed in an execution frame. True / False


6. Function returning values are also known as ………. Functions
7. Default return value for a function that does not return any value is …..
8. Where is the function call and parameters stored in the system?
a.Heap b.Queue c.Array d.Stack
9. What is the output of the function shown below?all([2,4,0,6])
a) Error b) True c) False d)0
10. What is the output of the following function?any([2>8, 4>2, 1>2])
a) Error b) True c) False d) 4>2
11. What is the output of the function shown below?
import math.abs(math.sqrt(25))
a) Error b) -5 c) 5 d) 5.0
12. What is the output of the function: all(3,0,4.2)
a) True b) False c) Error d)0
13. What is the output of the function complex() ?
a) 0j b) 0+0j c) 0 d) Error

61
14. Predict the output of the following code
def fun3(num1,num2):
for x in range(num1,num2):
if x%4==0:
print(x,end=’ ‘)
fun3(10,20)
A. 10 12 16 20
B. 12 16
C. 12 16 20

15. Identify correct output (K)


def fun3(a,b,c):
return a+1,b+2,c+3
t=fun3(10,20,30)
print(t)
A. 11,22,33
B. 11 22 33
C. (11, 22, 33)
D. (11 22 33)
16. The correct way to call a function is:
A. A_func()
B. def A_func()
C. return A_func()
D. call A_func()
Questions (2 marks)
1. What is the output of the below program?
def sayHello():
print('Hello World!')
sayHello()
sayHello()

2. From the program code given below, identify the parts mentioned below:
def processNumber(x):
x = 72
return x + 3
y = 54
res processNumber(y)
Identify these parts: function header, function call, arguments, parameters

Questions (3 marks)
1. What is a function? Why is it needful?
2. Compute the code. Write the output of the pseudocode.
r=30
t=15
62
def swap(f,g):
f = r+t
g= f - g
g=f-g
print("f=", f,"g=", g)
swap(r,t)
swap(11,3)
swap(t,10)
swap(r,t)

3. Trace the following code and predict output produced by it.


(a)
1. def power (b, p):
2. y = b **p
3 return y
4.
5 def calcSquare(x) :
6. a = power (x, 2)
7. return a
8.
9. n=5
10. result = calcSquare (n) + power (3, 3)
11. print(result)

(b)
1.def power (b, p):
2 .r = b ** p
3. return r
4
5. def calcSquare(a):
6. a = power (a, 2)
7. return a

9.n = 5
10. result = calcSquare(n)
11. print (result)

(c)
1. def increment(X):
2. X=X+1
3.
4. # main program
5. X = 3
6. print(x)
7. increment(x)
8. print(x)
63
Questions (5 marks)
1. Differentiate between parameters and arguments.
2. Differentiate between actual parameter(s) and a formal parameter(s) with a suitable example
for each.

ANSWERS
I Answer the following 1 mark
1 pickle
math

2 A
3 C
4 B
5 True
6 Fruitful functions
7 None
8 D
9 C
10 True
11 5.0
12 The function all() returns ‘True’ if any one
or more of the elements of the iterable are non zero. In theabove case, the
values are not iterable, hence an error isthrown.
13 A
14 B
15. C
16 A

II Answer the following 2 marks


64
1 Hello World!
Hello World!
2 Function header-- def processNumber(x):
Function call--- processNumber (y)
Arguments----- y
Parameters ----- x
Function body-------x = 72
return x + 3
Main program-------- y = 54
res processNumber(y)

III Answer the following 3 marks


1 A function is a set of instructions or subprograms that are used to perform a
specific task. It divides the large program into smaller blocks of a program that
processes the data and often returns a value. Functions are needful
-To make the program easy
-Divide the large program into a small block of codes
-Reduce the lines of code
-Easy to update
-Reuse of the code is possible
-Error correction is easier

2 f= {45} g= {15}
f= {45} g= {3}
f= {45} g= {10}
f= {45} g= {15}
3 (a)1→5→9→10→5→6→1→2→36→7→10→1→2→3→10→11

(b) 1-59→10→56→1→2→36→710→11

(c) 1-5-6-7→1→2→8

65
IV Answer the following 5 marks
1 Parameters Arguments
These are specified during the Values passed during the function
function definition. call.
They are also known as formal They are also known as actual
parameters. parameters.
The values passed as parameters are Every argument is assigned to a
local variables and are assigned parameter when the function is
values of the arguments during the defined.
function call.
These variables help in the These variables are passed to the
complete execution of the function. function for execution.
The values contained by these The arguments are accessible
parameters can only be accessed throughout the program depending
from function return statements or upon the scope of the variable
if the scope of these parameters is assigned.
made global.
2 Actual Parameter is a parameter, which is used in function call statement to
send the value from calling function to the called function. It is also known as
Argument.

Formal Parameter is a parameter, which is used in function header of the called


function to receive the value from actual parameter. It is also known as
Parameter. For example,

def addEm(x, y, z):


print(x + y + z)
addEm (6, 16, 26)

In the above code, actual parameters are 6, 16 and 26; and formal parameters
are x, y and z.

LEVEL III
I Questions (1 mark)

66
1. Which keyword is used for function?
a) fun
b) define
c) def
d) function
2. What are the two main types of functions?
a) Custom function & User defined function
b) Built-in function & User defined function
c) User defined function & System function
d) System function & Built-in functions
3. What is the output of below program?
def cube(x):
return x * x * x
x = cube(3)
print( x)
a) 9
b) 3
c) 27
d) 30
4. Which of the following functions is a built-in function in python?
a) seed() b) sqrt() c) factorial() d) print()
5. What is the output of the expression?round(4.5676,2)?
a) 4.5 b) 4.6 c) 4.57 d) 4.56
6. What is the output of the following function?complex(1+2j)
a) Error b) 1 c) 2j d) 1+2j
7. The function divmod(a,b), where both ‘a’ and ‘b’ are integers is evaluated as:
a) (a%b, a//b) b) (a//b, a%b) c) (a//b, a*b) d) (a/b, a%b)
8. What is the output of the function shown below?
list(enumerate([2, 3]))
9. What is the result of the code?
def p(x):
print(2**x)
p(3)
a)8 b)64 c)6 d)x
10. The default value of the parameter is defined in the ………….
11. Choose correct answer for the following code
def abc(X,Y):
print(X,Y)
abc(10,20)
A. X and Y are called actual parameter
B. X and Y are default argument
C. 10 and 20 are formal parameter
D. None of above
12. Predict the output of the following code
def fun2(list1):
for x in list1:
print(x.upper(),end=”#”)

67
fun2([‘Rajesh’,’Kumar’)
13. What will be the result of thefollowing code:
def func1(a):
a= a + '1'
a=a*2
func1("good")
A. good
B. good2good
C. goodgood
D. indentation error
14. Which of the following functions acceptsinteger as argument:
A. chr()
B. ord()
C. sum()
D. mul()
15. The function header contains:
A. Function name only
B. Parameter list only
C. Both function name & Parameter list
D. Return valu
16. A variable defined outside of all functions is known as :
A. Local variable
B. Global variable
C. Static variable
D. Unknown variable

II. Questions (2 marks)


1. What is the local variable and global variable?
2. Write the output of the code
def res():
eng = 56
math = 40
sci = 60
if eng<=35 || math<=35 || sci=35:
print(‘Not Qualified’)
else:
print(“Qualified”)

res()

3. Write the output of the code


def my_func():
x = 10
print("Value inside function:",x)
x = 20
my_func()

68
print("Value outside function:",x)
4. What are default arguments? What are the advantages of keyword arguments?

III. Questions (3 marks)


1. What is a function? Why do we need functions in python programming?
2. Write and explain the types of functions supported by python.
3. What are keyword arguments?
4.
IV. Questions (5 marks)
1. Explain the following built-in functions.
(a) id ()
(b) chr ()
(c) round ()
(d) type ()
(e) pow ()

ANSWERS
I Answer the following 1 mark
1 C
2 B
3 C
4 D
5 C
6 D
7 B
8 The built-in function enumerate() accepts an iterable as an argument. The
function shown in the above case returns containing pairs of the numbers
given, starting from 0.Hence the output will be: [(0, 2), (1,3)].
9 A
10 Header
11 D
12 B
13 D
14 A
15 C
16 B

69
II Answer the following 2 marks
1 Global Variable: A variable that is declared in top-level statements is called
a global variable. To access the value of a global variable user need to write
a global keyword in front of the variable in a function.

Local Variable: A name declared in a specific function body is called a


local variable
2 Qualified
3 Value inside function: 10
Value outside function: 20
4 Python allows function arguments to have default values; if the function is
called without the argument, the argument gets its default value
III Answer the following 3 marks
2 Built in Functions: Pre-defined functions of python such as len(), type(),
input() etc.
Functions defined in modules: Functions defined in particular modules, can
be used when the module is imported. A module is a container of functions,
variables, constants, classes in a separate file which can be reused.
User Defined Functions: Function created by the programmer
4 If there is a function with many parameters and we want to specify only
some of them in function call,
then value for such parameters can be provided by using their names instead
of the positions. These are called keyword argument.

(eg) def simpleinterest(p, n=2, r=0.6)


def simpleinterest(p, r=0.2, n=3)

It is easier to use since we need not remember the order of the arguments.
We can specify the values for only those parameters which we want, and
others have default values.
IV Answer the following 5 marks

70
a)id():
Return the “identity” of an object. This is an integer which is guaranteed to
be unique and constant for this object during its lifetime. Two objects with
non-overlapping lifetimes may have the same id() value. This is the address
of the object in memory.

(b) chr ():


Return the string representing a character whose Unicode code point is the integer
i. For example, chr(97) returns the string 'a', while chr(8364) returns the string
'€'. This is the inverse of ord().
The valid range for the argument is from 0 through 1,114,111 (0x10FFFF in base
16). ValueError will be raised if i is outside that range.

(c) round ()
Return number rounded to ndigits precision after the decimal point. If ndigits is
omitted or is None, it returns the nearest integer to its input.

For the built-in types supporting round(), values are rounded to the closest
multiple of 10 to the power minus ndigits; if two multiples are equally close,
rounding is done toward the even choice (so, for example, both round(0.5) and
round(-0.5) are 0, and round(1.5) is 2). Any integer value is valid for ndigits
(positive, zero, or negative). The return value is an integer if ndigits is omitted
or None. Otherwise, the return value has the same type as number

(d) type ()
With one argument, return the type of an object. The return value is a type object
and generally the same object as returned by object.__class__.

(e) pow ()
Return base to the power exp; if mod is present, return base to the power
exp, modulo mod (computed more efficiently than pow(base, exp) % mod).
The two-argument form pow(base, exp) is equivalent to using the power
operator: base**exp.

The arguments must have numeric types. With mixed operand types, the
coercion rules for binary arithmetic operators apply. For int operands, the
result has the same type as the operands (after coercion) unless the second
argument is negative; in that case, all arguments are converted to float and a
float result is delivered. For example, pow(10, 2) returns 100, but pow(10, -
2) returns 0.01. For a negative base of type int or float and a non-integral

71

You might also like