Python Revision &functions
Python Revision &functions
Python Revision &functions
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.
23
• Computer Vision or Image Processing Applications.
• Speech Recognitions
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
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
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)
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.
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
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!'
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 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
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
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))
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.
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’
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()]
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
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)
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
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)
---------------------------------------------------------------------------------------------------------------------
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
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)
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
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)
Advantages of Functions
• Reducing duplication of code
• Decomposing complex problems into simpler pieces
• Improving clarity of the code
• Reuse of code
• Information hiding
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.
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)
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.
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”)
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)
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.
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
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
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
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.
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
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
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)
(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
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.
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
res()
68
print("Value outside function:",x)
4. What are default arguments? What are the advantages of keyword arguments?
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.
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.
(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