Functions with questions part 2
Functions with questions part 2
Ex: 1
def outer(): 10
a=10 #local
print(a)
outer()
Ex: 2
a=10 is local variable which cannot be accessed outside of the function
and will result in error as given below.
def outer(): NameError: name 'a' is not defined
a=10
print(a)
outer()
print(a)
Ex: 3
def outer(): 10
a=10 #local 100
print(a)
a=100 #global
outer()
print(a)
Ex: 4
def outer(): 100
print(a) #return global value 100
a=100 #global
outer()
print(a)
Ex: 5
def outer(): 10
a=10 #nonlocal 20
print(a) 10
def inner(): 100
a=20 #local
print(a)
inner()
print(a)
a=100 #global
outer()
print(a)
Ex:6
def outer(): 10
a=10 10
print(a) 10
def inner(): 100
print(a)
inner()
print(a)
a=100
outer()
print(a)
Ex:7
Ex: 9
Ex: 10
def outer(): 20
a=20 50
print(a) #20 20
def inner(): 50
global a
a=50
print(a) #50
inner()
print(a) #20
a=100
outer()
print(a) #50
Ex: 11
def outer(): 20
a=20 50
print(a) #20 50
def inner(): 100
nonlocal a
a=50
print(a) #50
inner()
print(a) #50 because of nonlocal
a=100
outer()
print(a) #100
Flow of control
Ex: 12
Ex: 13
a=10 10
print(a) 140706674972720
print(id(a)) 30
a+=20 140706674973360
print(a)
print(id(a))
Ex: 16
Ex: 18
Mode
Definition: The mode is the number that appears most frequently in
a dataset.
Usage in statistics module: statistics.mode(data)
import statistics
Median
Definition: The median is the middle value of a dataset when it is
ordered in ascending or descending order. If there is an even
number of observations, the median is the average of the two middle
numbers.
Usage in statistics module: statistics.median(data)
import statistics
Explanation: The ordered list [10, 20, 30, 40, 50] has 30 as the middle
value.
Questions
b=100
def test(a):
__________ # missing statement
b=b+a
print(a,b)
test(10)
print(b)
a. global a
b. global b=100
c. global b
d. global a=100
chr(ord(‘A’))
a. A
b. B
c. a
d. Error
Ans: Both A and R are true but R is not the correct explanation for A
Output:
LONDON NEW YORK
def lenWords(STRING):
T=()
L=STRING.split()
for word in L:
print(word)
length=len(word)
T=T+ (length,)
return T
st="Come let us have some fun"
result=lenWords(st)
print("Length of each word of a string\n",result)
Output:
Come
let
us
have
some
fun
Length of each word of a string
(4, 3, 2, 4, 4, 3)
7. Write the Python statement for each of the following tasks using
BUILT-IN functions/methods only:
(i) To insert an element 200 at the third position, in the list L1.
Output:
[10, 20, 200, 30, 40]
(ii) To check whether a string named, message ends with a full stop /
period or not.
8. A list named student Age stores age of students of a class. Write the
Python command to import the required module and (using built-in
function) to display the most common age value from the given list.
import statistics
print( statistics.mode(studentAge) )