CH-3 Notes and Questions-1
CH-3 Notes and Questions-1
CH-3 Notes and Questions-1
INTRODUCTION
where:
def means a function definition is starting
identifier following 'def' is the name of the function, i.e.,
here the function name is calcSomething
the variables/identifiers inside the parentheses are the
arguments or parameters (values given to function),
i.e., here x is the argument to function calcSomething.
there is a colon at the end of def line, meaning it
requires a block
the statements indented below the function, (i.e., block
below def line) define the functionality (working) of the
function. This block is also called body-of-the-
function.
Here, there are two statements in the body of function
calcSomething
The return statement returns the computed result.
Calling/Invoking/Using a Function
To use a function that has been defined earlier, you need to write
a function call statement in Python. A function call statement
takes the following form:
<function-name>(<value-to-be-passed-to-argument>)
As you can make out that the above function's name is cube()
and it takes one argument. Now its function call statement(s)
would be like the ones shown below:
Python comes preloaded with many that you can use as per your
needs. You can even create new functions. Broadly, Python
functions can belong to one of the following three categories:
def function_name(arguments):
# function body
return
Here,
Or
def sum(x,y):
s = x+y
return s
Here,
we have created a function named test(). It simply prints the
text Hello World!.
hello()
Here,
This code defines a function called hello().
When the function is called, it prompts the user to enter their
name using the input() function and stores the input as a
string in the variable name.
The code then checks if name is not an empty string using
the if statement.
If name is not empty, the function prints "Hello" followed by
the value of name.
If name is empty, the function prints "Hello World".
Finally, the function returns None as there is no explicit return
value specified.
When the code is run, the hello() function is called,
prompting the user to enter their name and printing the
appropriate greeting based on the input.
In order to ensure that a function is defined before its first use, you
have to know the order in which statements are executed, which
is called the flow of execution.
Execution always begins at the first statement of the program.
Statements are executed one at a time, in order from top to
bottom.
unction definitions do not alter the flow of execution of the
program, but remember that statements inside the function are
not executed until the function is called.
Example:
def firstPrint():
print("First")
secondPrint()
def secondPrint():
print("Second")
thirdPrint()
def thirdPrint():
print("Third")
firstPrint()
Arguments and Parameters
sum(1,2)
Example:
Example:
Output:
Student Details: Kelly 12 Six ABC School
Student Details: Jessa 12 Seven XYZ School
Keyword Arguments: Usually, at the time of the function call, values
get assigned to the arguments according to their position. So we must
pass values in the same sequence defined in a function definition.
For example, when we call student('Jon', 12, 'Five', 'ABC School'), the
value “Jon” gets assigned to the argument name, and similarly, 12
to age and so on as per the sequence.
Example:
Output:
Student Details: Jessa 14
Student Details: Jon 12
Student Details: Donald 13
SCOPE OF A VARIABLES
1. Local Scope
Local scope variables can only be accessed within its block.
Example.
a = 10
def function():
print(“Hello”)
b = 20
function()
print(a)
print(b)
Output:
Hello
10
Traceback (most recent call last):
File “main.py”, line 7, in <module print(b)
NameError: name ‘b’ is not defined
In the above example, we see that Python prints the value of variable
a but it cannot find variable b. This is because b was defined as a local
scope in the function so, we cannot access the variable outside the
function. This is the nature of the local scope.
2. Global Scope
The variables that are declared in the global scope can be accessed
from anywhere in the program. Global variables can be used inside
any functions. We can also change the global variable value.
Example-
msg = “global variable”
def function():
msg = “local variable”
print(msg)
function()
print(msg)
Output:
local variable
global variable
As you can see, if we declare a local variable with the same name as
a global variable then the local scope will use the local variable.
If you want to use the global variable inside local scope then you will
need to use the “global” keyword.
3. Enclosing Scope
A scope that isn’t local or global comes under enclosing scope.
Example-
def vehicle():
fun= “Start”
def car():
model= “Toyota”
print(fun)
print(model)
car()
vehicle()
Output:
Start
Toyota
In the example code, the variable fun is used inside the car() function.
In that case, it is neither a local scope nor a global scope. This is called
the enclosing scope.
4. Built-in Scope
This is the widest scope in Python. All the reserved names in Python
built-in modules have a built-in scope.
When the Python does not find an identifier in it’s local, enclosing or
global scope, it then looks in the built-in scope to see if it’s defined
there.
Example-
a = 5.5
int(a)
print(a)
print(type(a))
Python would see in the local scope first to see which of the variables
are defined in the local scope, then it will look in the enclosing scope
and then global scope.
If the identifier is not found anywhere then, at last, it will check the built-
in scope.
Here, the functions int(), print(), type() does not need to be defined
because they are already defined in the built-in scope of Python.
1. global Keyword
Example-
a = 100
def method():
a = 50
print(a)
method()
print(a)
Output:
50
100
The above code will print the values 50 and 100 because in the local
scope variable, a is referenced to 50 and outside the method ()
function, it is being referenced to the global variable.
But, what if we wanted to access the global variable inside the method
() function.
Example-
a = 100
def method():
global a
a = 50
print(a)
method()
print(a)
Output:
50
50
Now we see that by using the global keyword, we can declare that we
want to use the variable a which is defined in the global scope.
So, when assigning the 50 to the variable, we also changed the value
outside the function.
2. nonlocal Keyword
Like the global keyword, we have a “nonlocal” keyword for times when
we need to change a nonlocal variable.
Example-
a = "global variable"
def method():
a = "nonlocal variable"
def function():
a = "local variable"
print(a)
function()
print(a)
method()
print(a)
Output:
local variable
nonlocal variable
global variable
1. What is the default return value for a function that does not
return any value explicitly ?
(a) None (b) int
(c) double (d) null
(a) 8 (b) 6
(c) 4 (d) 10
Here are some function calls given below. Find out which of these
are correct and which of these are incorrect stating reasons:
a. info(obj1)
b. info(spacing=20)
c. info( obj2, 12)
d. info( obj11, object = obj12)
e. info( obj3, collapse = 0)
f. info()
g. info(collapse = 8, obj3)
h. info( spacing=15, object=obj4)
Ans.
(a) Correct : oby1 is for positional parameter object; spacing gets
its default value of 10 and collapse gets its default value of 1.
(b) Incorrect: Required positional argument (object) missing;
required arguments cannot be missed.
(c) Correct: Required parameter object gets its value as obj2;
spacing gets value 12 and for skipped argument collapse, default
value 1 is taken.
(d) Incorrect: Same parameter object is given multiple values - one
through positional argument and one through keyword(named)
argument.
(e) Correct: Required parameter object gets its value as obj3;
collapse gets value 0 and for skipped argument spacing, default value
10 is taken
(f) Incorrect: Required parameter object's value cannot be
skipped.
(g) Incorrect: Positional arguments should be before keyword
arguments.
(h) Correct: Required argument object gets its value through a
keyword argument.
Ans. 48
None 36
10. Explain the use of global key word used in a function with the
help of a suitable example.
Ans. global keyword: In Python, global keyword allows the
programmer to use a global variable in the local context. A
variable declared inside a function is by default local and a
variable declared outside the function is global by default. The
keyword global is written inside the function to use its global
value. Outside the function, global keyword has no effect.
For Example-
c = 10
def add():
global c # now on c will refer to global variable
c=c+2 #global value of c is incremented by 2
print("Inside add():", c)
add()
c = 15
print("In main:",c)
Output
Inside add(): 12
In main: 15
11. Which names are local, which are global and which are built-
in in the following code fragment?
invaders=“Big names”
pos = 200
level = 1
def play():
max_level = level + 10
print(len (invaders) == 0)
return max_level
res = play()
print(res)
Ans.
Global names: invaders, pos, level, res
Local names: max_level
Built-in: len
12. Find and write the output of the following python code:
a=10
def call():
global a
a=15
b=20
print(a)
call()
Ans. 15
14. Find and write the output of the following python code:
def fun(s):
k= len(s)
m=” “
for i in range(0, k):
if(s[i].isupper()):
m=m+s[i].lower()
elif s[i].isalpha():
m=m+s[i].upper()
else:
m=m+’bb’
print(m)
fun('school2@com')
Ans.
SCHOOLbbbbCOM
Ans.
610.0
500.0
1800.0
2000.0